hunk
dict | file
stringlengths 0
11.8M
| file_path
stringlengths 2
234
| label
int64 0
1
| commit_url
stringlengths 74
103
| dependency_score
sequencelengths 5
5
|
---|---|---|---|---|---|
{
"id": 6,
"code_window": [
"\t\tpath = path.replace(/\\\\/g, '/');\n",
"\t\treturn resources.toLocalResource(URI.from({ scheme: this.scheme, path }), this.scheme === Schemas.file ? undefined : this.remoteAuthority);\n",
"\t}\n",
"\n",
"\tprivate getScheme(defaultUri: URI | undefined, available: string[] | undefined): string {\n",
"\t\treturn defaultUri ? defaultUri.scheme : (available ? available[0] : Schemas.file);\n",
"\t}\n",
"\n",
"\tprivate async getRemoteAgentEnvironment(): Promise<IRemoteAgentEnvironment | null> {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tprivate getScheme(available: string[] | undefined): string {\n",
"\t\treturn available ? available[0] : Schemas.file;\n"
],
"file_path": "src/vs/workbench/services/dialogs/browser/remoteFileDialog.ts",
"type": "replace",
"edit_start_line_idx": 152
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as assert from 'assert';
import { URI as uri } from 'vs/base/common/uri';
import { IModelService } from 'vs/editor/common/services/modelService';
import { ModelServiceImpl } from 'vs/editor/common/services/modelServiceImpl';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { TestConfigurationService } from 'vs/platform/configuration/test/common/testConfigurationService';
import { TestInstantiationService } from 'vs/platform/instantiation/test/common/instantiationServiceMock';
import { IFileMatch, ITextSearchMatch, OneLineRange, QueryType } from 'vs/workbench/services/search/common/search';
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
import { TestWorkspace } from 'vs/platform/workspace/test/common/testWorkspace';
import { FileMatch, Match, searchMatchComparer, SearchResult } from 'vs/workbench/contrib/search/common/searchModel';
import { TestContextService } from 'vs/workbench/test/workbenchTestServices';
suite('Search - Viewlet', () => {
let instantiation: TestInstantiationService;
setup(() => {
instantiation = new TestInstantiationService();
instantiation.stub(IModelService, stubModelService(instantiation));
instantiation.set(IWorkspaceContextService, new TestContextService(TestWorkspace));
});
test('Data Source', function () {
let result: SearchResult = instantiation.createInstance(SearchResult, null);
result.query = {
type: QueryType.Text,
contentPattern: { pattern: 'foo' },
folderQueries: [{
folder: uri.parse('file://c:/')
}]
};
result.add([{
resource: uri.parse('file:///c:/foo'),
results: [{
preview: {
text: 'bar',
matches: {
startLineNumber: 0,
startColumn: 0,
endLineNumber: 0,
endColumn: 1
}
},
ranges: {
startLineNumber: 1,
startColumn: 0,
endLineNumber: 1,
endColumn: 1
}
}]
}]);
let fileMatch = result.matches()[0];
let lineMatch = fileMatch.matches()[0];
assert.equal(fileMatch.id(), 'file:///c%3A/foo');
assert.equal(lineMatch.id(), 'file:///c%3A/foo>[2,1 -> 2,2]b');
});
test('Comparer', () => {
let fileMatch1 = aFileMatch('C:\\foo');
let fileMatch2 = aFileMatch('C:\\with\\path');
let fileMatch3 = aFileMatch('C:\\with\\path\\foo');
let lineMatch1 = new Match(fileMatch1, ['bar'], new OneLineRange(0, 1, 1), new OneLineRange(0, 1, 1));
let lineMatch2 = new Match(fileMatch1, ['bar'], new OneLineRange(0, 1, 1), new OneLineRange(2, 1, 1));
let lineMatch3 = new Match(fileMatch1, ['bar'], new OneLineRange(0, 1, 1), new OneLineRange(2, 1, 1));
assert(searchMatchComparer(fileMatch1, fileMatch2) < 0);
assert(searchMatchComparer(fileMatch2, fileMatch1) > 0);
assert(searchMatchComparer(fileMatch1, fileMatch1) === 0);
assert(searchMatchComparer(fileMatch2, fileMatch3) < 0);
assert(searchMatchComparer(lineMatch1, lineMatch2) < 0);
assert(searchMatchComparer(lineMatch2, lineMatch1) > 0);
assert(searchMatchComparer(lineMatch2, lineMatch3) === 0);
});
function aFileMatch(path: string, searchResult?: SearchResult, ...lineMatches: ITextSearchMatch[]): FileMatch {
let rawMatch: IFileMatch = {
resource: uri.file('C:\\' + path),
results: lineMatches
};
return instantiation.createInstance(FileMatch, null, null, null, searchResult, rawMatch);
}
function stubModelService(instantiationService: TestInstantiationService): IModelService {
instantiationService.stub(IConfigurationService, new TestConfigurationService());
return instantiationService.createInstance(ModelServiceImpl);
}
});
| src/vs/workbench/contrib/search/test/browser/searchViewlet.test.ts | 0 | https://github.com/microsoft/vscode/commit/985de26b3446636f86e2bb2b14dbeb9ec1e33207 | [
0.0001762273459462449,
0.00017359443882014602,
0.00016537154442630708,
0.00017423430108465254,
0.0000029797856768709607
] |
{
"id": 6,
"code_window": [
"\t\tpath = path.replace(/\\\\/g, '/');\n",
"\t\treturn resources.toLocalResource(URI.from({ scheme: this.scheme, path }), this.scheme === Schemas.file ? undefined : this.remoteAuthority);\n",
"\t}\n",
"\n",
"\tprivate getScheme(defaultUri: URI | undefined, available: string[] | undefined): string {\n",
"\t\treturn defaultUri ? defaultUri.scheme : (available ? available[0] : Schemas.file);\n",
"\t}\n",
"\n",
"\tprivate async getRemoteAgentEnvironment(): Promise<IRemoteAgentEnvironment | null> {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tprivate getScheme(available: string[] | undefined): string {\n",
"\t\treturn available ? available[0] : Schemas.file;\n"
],
"file_path": "src/vs/workbench/services/dialogs/browser/remoteFileDialog.ts",
"type": "replace",
"edit_start_line_idx": 152
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
.monaco-workbench .activitybar > .content .monaco-action-bar .action-label.scm {
-webkit-mask: url('icon-dark.svg') no-repeat 50% 50%;
}
.monaco-workbench .viewlet.scm-viewlet .collapsible.header .actions {
width: initial;
flex: 1;
}
.scm-viewlet .empty-message {
box-sizing: border-box;
height: 100%;
padding: 10px 22px 0 22px;
}
.scm-viewlet:not(.empty) .empty-message,
.scm-viewlet.empty .monaco-panel-view {
display: none;
}
.scm-viewlet .scm-status {
height: 100%;
position: relative;
}
.scm-viewlet .monaco-list-row > .scm-provider {
display: flex;
align-items: center;
flex-wrap: wrap;
height: 100%;
}
.scm-viewlet .monaco-list-row > .scm-provider > .monaco-action-bar {
flex: 1;
}
.scm-viewlet .monaco-list-row > .scm-provider > .monaco-action-bar .action-item {
overflow: hidden;
text-overflow: ellipsis;
}
.scm-viewlet .scm-provider > .count {
margin: 0 0.5em;
}
.scm-viewlet .scm-provider > .count.hidden {
display: none;
}
.scm-viewlet .scm-provider > .type,
.scm-viewlet .scm-provider > .name > .type {
opacity: 0.7;
margin-left: 0.5em;
font-size: 0.9em;
}
.scm-viewlet .monaco-list-row {
padding: 0 12px 0 20px;
line-height: 22px;
}
.scm-viewlet .monaco-list-row > .resource-group {
display: flex;
height: 100%;
}
.scm-viewlet .monaco-list-row > .resource-group > .name {
flex: 1;
font-size: 11px;
font-weight: bold;
text-transform: uppercase;
overflow: hidden;
text-overflow: ellipsis;
}
.scm-viewlet .monaco-list-row > .resource {
display: flex;
height: 100%;
}
.scm-viewlet .monaco-list-row > .resource.faded {
opacity: 0.7;
}
.scm-viewlet .monaco-list-row > .resource > .name {
flex: 1;
overflow: hidden;
}
.scm-viewlet .monaco-list-row > .resource > .name.strike-through > .monaco-icon-label > .monaco-icon-label-description-container > .label-name {
text-decoration: line-through;
}
.scm-viewlet .monaco-list-row > .resource > .name > .monaco-icon-label::after {
padding: 0 4px;
}
.scm-viewlet .monaco-list-row > .resource > .decoration-icon {
width: 16px;
height: 100%;
background-repeat: no-repeat;
background-position: 50% 50%;
}
.scm-viewlet .monaco-list .monaco-list-row > .resource > .name > .monaco-icon-label > .actions {
flex-grow: 100;
}
.scm-viewlet .monaco-list .monaco-list-row > .resource-group > .actions,
.scm-viewlet .monaco-list .monaco-list-row > .resource > .name > .monaco-icon-label > .actions {
display: none;
}
.scm-viewlet .monaco-list .monaco-list-row:hover > .resource-group > .actions,
.scm-viewlet .monaco-list .monaco-list-row:hover > .resource > .name > .monaco-icon-label > .actions,
.scm-viewlet .monaco-list .monaco-list-row.selected > .resource-group > .actions,
.scm-viewlet .monaco-list .monaco-list-row.focused > .resource-group > .actions,
.scm-viewlet .monaco-list .monaco-list-row.selected > .resource > .name > .monaco-icon-label > .actions,
.scm-viewlet .monaco-list .monaco-list-row.focused > .resource > .name > .monaco-icon-label > .actions,
.scm-viewlet .monaco-list:not(.selection-multiple) .monaco-list-row > .resource:hover > .actions {
display: block;
}
.scm-viewlet .scm-status.show-actions > .monaco-list .monaco-list-row > .resource-group > .actions,
.scm-viewlet .scm-status.show-actions > .monaco-list .monaco-list-row > .resource > .name > .monaco-icon-label > .actions {
display: block;
}
.scm-viewlet .monaco-list-row > .resource > .name > .monaco-icon-label > .actions .action-label,
.scm-viewlet .monaco-list-row > .resource-group > .actions .action-label {
width: 16px;
height: 100%;
background-position: 50% 50%;
background-repeat: no-repeat;
}
.scm-viewlet .scm-editor {
box-sizing: border-box;
padding: 5px 9px 5px 16px;
}
.scm-viewlet .scm-editor.hidden {
display: none;
}
.scm-viewlet .scm-editor > .monaco-inputbox {
width: 100%;
}
.scm-viewlet .scm-editor > .monaco-inputbox > .wrapper > .mirror {
max-height: 134px;
}
.scm-viewlet .scm-editor > .monaco-inputbox > .wrapper > textarea.input {
min-height: 26px;
}
.scm-viewlet .scm-editor.scroll > .monaco-inputbox > .wrapper > textarea.input {
overflow-y: scroll;
}
| src/vs/workbench/contrib/scm/browser/media/scmViewlet.css | 0 | https://github.com/microsoft/vscode/commit/985de26b3446636f86e2bb2b14dbeb9ec1e33207 | [
0.0001766504574334249,
0.00017495355859864503,
0.00017037086945492774,
0.00017524858412798494,
0.0000014153954452922335
] |
{
"id": 7,
"code_window": [
"\t\t\t\tisAcceptHandled = true;\n",
"\t\t\t\tisResolving++;\n",
"\t\t\t\tif (this.options.availableFileSystems && (this.options.availableFileSystems.length > 1)) {\n",
"\t\t\t\t\tthis.options.availableFileSystems.shift();\n",
"\t\t\t\t}\n",
"\t\t\t\tthis.options.defaultUri = undefined;\n",
"\t\t\t\tthis.filePickBox.hide();\n",
"\t\t\t\tif (isSave) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/services/dialogs/browser/remoteFileDialog.ts",
"type": "replace",
"edit_start_line_idx": 256
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as nls from 'vs/nls';
import { URI } from 'vs/base/common/uri';
import * as errors from 'vs/base/common/errors';
import * as objects from 'vs/base/common/objects';
import { Event, Emitter } from 'vs/base/common/event';
import * as platform from 'vs/base/common/platform';
import { IWindowsService } from 'vs/platform/windows/common/windows';
import { IBackupFileService } from 'vs/workbench/services/backup/common/backup';
import { IResult, ITextFileOperationResult, ITextFileService, ITextFileStreamContent, IAutoSaveConfiguration, AutoSaveMode, SaveReason, ITextFileEditorModelManager, ITextFileEditorModel, ModelState, ISaveOptions, AutoSaveContext, IWillMoveEvent, ITextFileContent, IResourceEncodings, IReadTextFileOptions, IWriteTextFileOptions, toBufferOrReadable, TextFileOperationError, TextFileOperationResult } from 'vs/workbench/services/textfile/common/textfiles';
import { ConfirmResult, IRevertOptions } from 'vs/workbench/common/editor';
import { ILifecycleService, ShutdownReason, LifecyclePhase } from 'vs/platform/lifecycle/common/lifecycle';
import { IWorkspaceContextService, WorkbenchState } from 'vs/platform/workspace/common/workspace';
import { IFileService, IFilesConfiguration, FileOperationError, FileOperationResult, AutoSaveConfiguration, HotExitConfiguration, IFileStatWithMetadata, ICreateFileOptions } from 'vs/platform/files/common/files';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { Disposable } from 'vs/base/common/lifecycle';
import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService';
import { IUntitledEditorService } from 'vs/workbench/services/untitled/common/untitledEditorService';
import { UntitledEditorModel } from 'vs/workbench/common/editor/untitledEditorModel';
import { TextFileEditorModelManager } from 'vs/workbench/services/textfile/common/textFileEditorModelManager';
import { IInstantiationService, ServiceIdentifier } from 'vs/platform/instantiation/common/instantiation';
import { ResourceMap } from 'vs/base/common/map';
import { Schemas } from 'vs/base/common/network';
import { IHistoryService } from 'vs/workbench/services/history/common/history';
import { IContextKey, IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { createTextBufferFactoryFromSnapshot, createTextBufferFactoryFromStream } from 'vs/editor/common/model/textModel';
import { IModelService } from 'vs/editor/common/services/modelService';
import { INotificationService, Severity } from 'vs/platform/notification/common/notification';
import { isEqualOrParent, isEqual, joinPath, dirname, extname, basename, toLocalResource } from 'vs/base/common/resources';
import { posix } from 'vs/base/common/path';
import { getConfirmMessage, IDialogService, IFileDialogService, ISaveDialogOptions, IConfirmation } from 'vs/platform/dialogs/common/dialogs';
import { IModeService } from 'vs/editor/common/services/modeService';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { coalesce } from 'vs/base/common/arrays';
import { trim } from 'vs/base/common/strings';
import { VSBuffer } from 'vs/base/common/buffer';
import { ITextSnapshot } from 'vs/editor/common/model';
import { ITextResourceConfigurationService } from 'vs/editor/common/services/resourceConfiguration';
import { PLAINTEXT_MODE_ID } from 'vs/editor/common/modes/modesRegistry';
/**
* The workbench file service implementation implements the raw file service spec and adds additional methods on top.
*/
export abstract class TextFileService extends Disposable implements ITextFileService {
_serviceBrand: ServiceIdentifier<any>;
private readonly _onAutoSaveConfigurationChange: Emitter<IAutoSaveConfiguration> = this._register(new Emitter<IAutoSaveConfiguration>());
get onAutoSaveConfigurationChange(): Event<IAutoSaveConfiguration> { return this._onAutoSaveConfigurationChange.event; }
private readonly _onFilesAssociationChange: Emitter<void> = this._register(new Emitter<void>());
get onFilesAssociationChange(): Event<void> { return this._onFilesAssociationChange.event; }
private readonly _onWillMove = this._register(new Emitter<IWillMoveEvent>());
get onWillMove(): Event<IWillMoveEvent> { return this._onWillMove.event; }
private _models: TextFileEditorModelManager;
get models(): ITextFileEditorModelManager { return this._models; }
abstract get encoding(): IResourceEncodings;
private currentFilesAssociationConfig: { [key: string]: string; };
private configuredAutoSaveDelay?: number;
private configuredAutoSaveOnFocusChange: boolean;
private configuredAutoSaveOnWindowChange: boolean;
private configuredHotExit: string;
private autoSaveContext: IContextKey<string>;
constructor(
@IWorkspaceContextService private readonly contextService: IWorkspaceContextService,
@IFileService protected readonly fileService: IFileService,
@IUntitledEditorService private readonly untitledEditorService: IUntitledEditorService,
@ILifecycleService private readonly lifecycleService: ILifecycleService,
@IInstantiationService protected instantiationService: IInstantiationService,
@IConfigurationService private readonly configurationService: IConfigurationService,
@IModeService private readonly modeService: IModeService,
@IModelService private readonly modelService: IModelService,
@IWorkbenchEnvironmentService protected readonly environmentService: IWorkbenchEnvironmentService,
@INotificationService private readonly notificationService: INotificationService,
@IBackupFileService private readonly backupFileService: IBackupFileService,
@IWindowsService private readonly windowsService: IWindowsService,
@IHistoryService private readonly historyService: IHistoryService,
@IContextKeyService contextKeyService: IContextKeyService,
@IDialogService private readonly dialogService: IDialogService,
@IFileDialogService private readonly fileDialogService: IFileDialogService,
@IEditorService private readonly editorService: IEditorService,
@ITextResourceConfigurationService protected readonly textResourceConfigurationService: ITextResourceConfigurationService
) {
super();
this._models = this._register(instantiationService.createInstance(TextFileEditorModelManager));
this.autoSaveContext = AutoSaveContext.bindTo(contextKeyService);
const configuration = configurationService.getValue<IFilesConfiguration>();
this.currentFilesAssociationConfig = configuration && configuration.files && configuration.files.associations;
this.onFilesConfigurationChange(configuration);
this.registerListeners();
}
//#region event handling
private registerListeners(): void {
// Lifecycle
this.lifecycleService.onBeforeShutdown(event => event.veto(this.beforeShutdown(event.reason)));
this.lifecycleService.onShutdown(this.dispose, this);
// Files configuration changes
this._register(this.configurationService.onDidChangeConfiguration(e => {
if (e.affectsConfiguration('files')) {
this.onFilesConfigurationChange(this.configurationService.getValue<IFilesConfiguration>());
}
}));
}
private beforeShutdown(reason: ShutdownReason): boolean | Promise<boolean> {
// Dirty files need treatment on shutdown
const dirty = this.getDirty();
if (dirty.length) {
// If auto save is enabled, save all files and then check again for dirty files
// We DO NOT run any save participant if we are in the shutdown phase for performance reasons
if (this.getAutoSaveMode() !== AutoSaveMode.OFF) {
return this.saveAll(false /* files only */, { skipSaveParticipants: true }).then(() => {
// If we still have dirty files, we either have untitled ones or files that cannot be saved
const remainingDirty = this.getDirty();
if (remainingDirty.length) {
return this.handleDirtyBeforeShutdown(remainingDirty, reason);
}
return false;
});
}
// Auto save is not enabled
return this.handleDirtyBeforeShutdown(dirty, reason);
}
// No dirty files: no veto
return this.noVeto({ cleanUpBackups: true });
}
private handleDirtyBeforeShutdown(dirty: URI[], reason: ShutdownReason): boolean | Promise<boolean> {
// If hot exit is enabled, backup dirty files and allow to exit without confirmation
if (this.isHotExitEnabled) {
return this.backupBeforeShutdown(dirty, this.models, reason).then(didBackup => {
if (didBackup) {
return this.noVeto({ cleanUpBackups: false }); // no veto and no backup cleanup (since backup was successful)
}
// since a backup did not happen, we have to confirm for the dirty files now
return this.confirmBeforeShutdown();
}, errors => {
const firstError = errors[0];
this.notificationService.error(nls.localize('files.backup.failSave', "Files that are dirty could not be written to the backup location (Error: {0}). Try saving your files first and then exit.", firstError.message));
return true; // veto, the backups failed
});
}
// Otherwise just confirm from the user what to do with the dirty files
return this.confirmBeforeShutdown();
}
private async backupBeforeShutdown(dirtyToBackup: URI[], textFileEditorModelManager: ITextFileEditorModelManager, reason: ShutdownReason): Promise<boolean> {
const windowCount = await this.windowsService.getWindowCount();
// When quit is requested skip the confirm callback and attempt to backup all workspaces.
// When quit is not requested the confirm callback should be shown when the window being
// closed is the only VS Code window open, except for on Mac where hot exit is only
// ever activated when quit is requested.
let doBackup: boolean | undefined;
switch (reason) {
case ShutdownReason.CLOSE:
if (this.contextService.getWorkbenchState() !== WorkbenchState.EMPTY && this.configuredHotExit === HotExitConfiguration.ON_EXIT_AND_WINDOW_CLOSE) {
doBackup = true; // backup if a folder is open and onExitAndWindowClose is configured
} else if (windowCount > 1 || platform.isMacintosh) {
doBackup = false; // do not backup if a window is closed that does not cause quitting of the application
} else {
doBackup = true; // backup if last window is closed on win/linux where the application quits right after
}
break;
case ShutdownReason.QUIT:
doBackup = true; // backup because next start we restore all backups
break;
case ShutdownReason.RELOAD:
doBackup = true; // backup because after window reload, backups restore
break;
case ShutdownReason.LOAD:
if (this.contextService.getWorkbenchState() !== WorkbenchState.EMPTY && this.configuredHotExit === HotExitConfiguration.ON_EXIT_AND_WINDOW_CLOSE) {
doBackup = true; // backup if a folder is open and onExitAndWindowClose is configured
} else {
doBackup = false; // do not backup because we are switching contexts
}
break;
}
if (!doBackup) {
return false;
}
await this.backupAll(dirtyToBackup, textFileEditorModelManager);
return true;
}
private backupAll(dirtyToBackup: URI[], textFileEditorModelManager: ITextFileEditorModelManager): Promise<void> {
// split up between files and untitled
const filesToBackup: ITextFileEditorModel[] = [];
const untitledToBackup: URI[] = [];
dirtyToBackup.forEach(s => {
if (this.fileService.canHandleResource(s)) {
const model = textFileEditorModelManager.get(s);
if (model) {
filesToBackup.push(model);
}
} else if (s.scheme === Schemas.untitled) {
untitledToBackup.push(s);
}
});
return this.doBackupAll(filesToBackup, untitledToBackup);
}
private async doBackupAll(dirtyFileModels: ITextFileEditorModel[], untitledResources: URI[]): Promise<void> {
// Handle file resources first
await Promise.all(dirtyFileModels.map(model => model.backup()));
// Handle untitled resources
await Promise.all(untitledResources
.filter(untitled => this.untitledEditorService.exists(untitled))
.map(async untitled => (await this.untitledEditorService.loadOrCreate({ resource: untitled })).backup()));
}
private async confirmBeforeShutdown(): Promise<boolean> {
const confirm = await this.confirmSave();
// Save
if (confirm === ConfirmResult.SAVE) {
const result = await this.saveAll(true /* includeUntitled */, { skipSaveParticipants: true });
if (result.results.some(r => !r.success)) {
return true; // veto if some saves failed
}
return this.noVeto({ cleanUpBackups: true });
}
// Don't Save
else if (confirm === ConfirmResult.DONT_SAVE) {
// Make sure to revert untitled so that they do not restore
// see https://github.com/Microsoft/vscode/issues/29572
this.untitledEditorService.revertAll();
return this.noVeto({ cleanUpBackups: true });
}
// Cancel
else if (confirm === ConfirmResult.CANCEL) {
return true; // veto
}
return false;
}
private noVeto(options: { cleanUpBackups: boolean }): boolean | Promise<boolean> {
if (!options.cleanUpBackups) {
return false;
}
if (this.lifecycleService.phase < LifecyclePhase.Restored) {
return false; // if editors have not restored, we are not up to speed with backups and thus should not clean them
}
return this.cleanupBackupsBeforeShutdown().then(() => false, () => false);
}
protected async cleanupBackupsBeforeShutdown(): Promise<void> {
if (this.environmentService.isExtensionDevelopment) {
return;
}
await this.backupFileService.discardAllWorkspaceBackups();
}
protected onFilesConfigurationChange(configuration: IFilesConfiguration): void {
const wasAutoSaveEnabled = (this.getAutoSaveMode() !== AutoSaveMode.OFF);
const autoSaveMode = (configuration && configuration.files && configuration.files.autoSave) || AutoSaveConfiguration.OFF;
this.autoSaveContext.set(autoSaveMode);
switch (autoSaveMode) {
case AutoSaveConfiguration.AFTER_DELAY:
this.configuredAutoSaveDelay = configuration && configuration.files && configuration.files.autoSaveDelay;
this.configuredAutoSaveOnFocusChange = false;
this.configuredAutoSaveOnWindowChange = false;
break;
case AutoSaveConfiguration.ON_FOCUS_CHANGE:
this.configuredAutoSaveDelay = undefined;
this.configuredAutoSaveOnFocusChange = true;
this.configuredAutoSaveOnWindowChange = false;
break;
case AutoSaveConfiguration.ON_WINDOW_CHANGE:
this.configuredAutoSaveDelay = undefined;
this.configuredAutoSaveOnFocusChange = false;
this.configuredAutoSaveOnWindowChange = true;
break;
default:
this.configuredAutoSaveDelay = undefined;
this.configuredAutoSaveOnFocusChange = false;
this.configuredAutoSaveOnWindowChange = false;
break;
}
// Emit as event
this._onAutoSaveConfigurationChange.fire(this.getAutoSaveConfiguration());
// save all dirty when enabling auto save
if (!wasAutoSaveEnabled && this.getAutoSaveMode() !== AutoSaveMode.OFF) {
this.saveAll();
}
// Check for change in files associations
const filesAssociation = configuration && configuration.files && configuration.files.associations;
if (!objects.equals(this.currentFilesAssociationConfig, filesAssociation)) {
this.currentFilesAssociationConfig = filesAssociation;
this._onFilesAssociationChange.fire();
}
// Hot exit
const hotExitMode = configuration && configuration.files && configuration.files.hotExit;
if (hotExitMode === HotExitConfiguration.OFF || hotExitMode === HotExitConfiguration.ON_EXIT_AND_WINDOW_CLOSE) {
this.configuredHotExit = hotExitMode;
} else {
this.configuredHotExit = HotExitConfiguration.ON_EXIT;
}
}
//#endregion
//#region primitives (read, create, move, delete, update)
async read(resource: URI, options?: IReadTextFileOptions): Promise<ITextFileContent> {
const content = await this.fileService.readFile(resource, options);
// in case of acceptTextOnly: true, we check the first
// chunk for possibly being binary by looking for 0-bytes
// we limit this check to the first 512 bytes
this.validateBinary(content.value, options);
return {
...content,
encoding: 'utf8',
value: content.value.toString()
};
}
async readStream(resource: URI, options?: IReadTextFileOptions): Promise<ITextFileStreamContent> {
const stream = await this.fileService.readFileStream(resource, options);
// in case of acceptTextOnly: true, we check the first
// chunk for possibly being binary by looking for 0-bytes
// we limit this check to the first 512 bytes
let checkedForBinary = false;
const throwOnBinary = (data: VSBuffer): Error | undefined => {
if (!checkedForBinary) {
checkedForBinary = true;
this.validateBinary(data, options);
}
return undefined;
};
return {
...stream,
encoding: 'utf8',
value: await createTextBufferFactoryFromStream(stream.value, undefined, options && options.acceptTextOnly ? throwOnBinary : undefined)
};
}
private validateBinary(buffer: VSBuffer, options?: IReadTextFileOptions): void {
if (!options || !options.acceptTextOnly) {
return; // no validation needed
}
// in case of acceptTextOnly: true, we check the first
// chunk for possibly being binary by looking for 0-bytes
// we limit this check to the first 512 bytes
for (let i = 0; i < buffer.byteLength && i < 512; i++) {
if (buffer.readUInt8(i) === 0) {
throw new TextFileOperationError(nls.localize('fileBinaryError', "File seems to be binary and cannot be opened as text"), TextFileOperationResult.FILE_IS_BINARY, options);
}
}
}
async create(resource: URI, value?: string | ITextSnapshot, options?: ICreateFileOptions): Promise<IFileStatWithMetadata> {
const stat = await this.doCreate(resource, value, options);
// If we had an existing model for the given resource, load
// it again to make sure it is up to date with the contents
// we just wrote into the underlying resource by calling
// revert()
const existingModel = this.models.get(resource);
if (existingModel && !existingModel.isDisposed()) {
await existingModel.revert();
}
return stat;
}
protected doCreate(resource: URI, value?: string | ITextSnapshot, options?: ICreateFileOptions): Promise<IFileStatWithMetadata> {
return this.fileService.createFile(resource, toBufferOrReadable(value), options);
}
async write(resource: URI, value: string | ITextSnapshot, options?: IWriteTextFileOptions): Promise<IFileStatWithMetadata> {
return this.fileService.writeFile(resource, toBufferOrReadable(value), options);
}
async delete(resource: URI, options?: { useTrash?: boolean, recursive?: boolean }): Promise<void> {
const dirtyFiles = this.getDirty().filter(dirty => isEqualOrParent(dirty, resource, !platform.isLinux /* ignorecase */));
await this.revertAll(dirtyFiles, { soft: true });
return this.fileService.del(resource, options);
}
async move(source: URI, target: URI, overwrite?: boolean): Promise<IFileStatWithMetadata> {
const waitForPromises: Promise<unknown>[] = [];
// Event
this._onWillMove.fire({
oldResource: source,
newResource: target,
waitUntil(promise: Promise<unknown>) {
waitForPromises.push(promise.then(undefined, errors.onUnexpectedError));
}
});
// prevent async waitUntil-calls
Object.freeze(waitForPromises);
await Promise.all(waitForPromises);
// Handle target models if existing (if target URI is a folder, this can be multiple)
const dirtyTargetModels = this.getDirtyFileModels().filter(model => isEqualOrParent(model.getResource(), target, false /* do not ignorecase, see https://github.com/Microsoft/vscode/issues/56384 */));
if (dirtyTargetModels.length) {
await this.revertAll(dirtyTargetModels.map(targetModel => targetModel.getResource()), { soft: true });
}
// Handle dirty source models if existing (if source URI is a folder, this can be multiple)
const dirtySourceModels = this.getDirtyFileModels().filter(model => isEqualOrParent(model.getResource(), source, !platform.isLinux /* ignorecase */));
const dirtyTargetModelUris: URI[] = [];
if (dirtySourceModels.length) {
await Promise.all(dirtySourceModels.map(async sourceModel => {
const sourceModelResource = sourceModel.getResource();
let targetModelResource: URI;
// If the source is the actual model, just use target as new resource
if (isEqual(sourceModelResource, source, !platform.isLinux /* ignorecase */)) {
targetModelResource = target;
}
// Otherwise a parent folder of the source is being moved, so we need
// to compute the target resource based on that
else {
targetModelResource = sourceModelResource.with({ path: joinPath(target, sourceModelResource.path.substr(source.path.length + 1)).path });
}
// Remember as dirty target model to load after the operation
dirtyTargetModelUris.push(targetModelResource);
// Backup dirty source model to the target resource it will become later
await sourceModel.backup(targetModelResource);
}));
}
// Soft revert the dirty source files if any
await this.revertAll(dirtySourceModels.map(dirtySourceModel => dirtySourceModel.getResource()), { soft: true });
// Rename to target
try {
const stat = await this.fileService.move(source, target, overwrite);
// Load models that were dirty before
await Promise.all(dirtyTargetModelUris.map(dirtyTargetModel => this.models.loadOrCreate(dirtyTargetModel)));
return stat;
} catch (error) {
// In case of an error, discard any dirty target backups that were made
await Promise.all(dirtyTargetModelUris.map(dirtyTargetModel => this.backupFileService.discardResourceBackup(dirtyTargetModel)));
throw error;
}
}
//#endregion
//#region save/revert
async save(resource: URI, options?: ISaveOptions): Promise<boolean> {
// Run a forced save if we detect the file is not dirty so that save participants can still run
if (options && options.force && this.fileService.canHandleResource(resource) && !this.isDirty(resource)) {
const model = this._models.get(resource);
if (model) {
options.reason = SaveReason.EXPLICIT;
await model.save(options);
return !model.isDirty();
}
}
const result = await this.saveAll([resource], options);
return result.results.length === 1 && !!result.results[0].success;
}
async confirmSave(resources?: URI[]): Promise<ConfirmResult> {
if (this.environmentService.isExtensionDevelopment) {
return ConfirmResult.DONT_SAVE; // no veto when we are in extension dev mode because we cannot assum we run interactive (e.g. tests)
}
const resourcesToConfirm = this.getDirty(resources);
if (resourcesToConfirm.length === 0) {
return ConfirmResult.DONT_SAVE;
}
const message = resourcesToConfirm.length === 1 ? nls.localize('saveChangesMessage', "Do you want to save the changes you made to {0}?", basename(resourcesToConfirm[0]))
: getConfirmMessage(nls.localize('saveChangesMessages', "Do you want to save the changes to the following {0} files?", resourcesToConfirm.length), resourcesToConfirm);
const buttons: string[] = [
resourcesToConfirm.length > 1 ? nls.localize({ key: 'saveAll', comment: ['&& denotes a mnemonic'] }, "&&Save All") : nls.localize({ key: 'save', comment: ['&& denotes a mnemonic'] }, "&&Save"),
nls.localize({ key: 'dontSave', comment: ['&& denotes a mnemonic'] }, "Do&&n't Save"),
nls.localize('cancel', "Cancel")
];
const index = await this.dialogService.show(Severity.Warning, message, buttons, {
cancelId: 2,
detail: nls.localize('saveChangesDetail', "Your changes will be lost if you don't save them.")
});
switch (index) {
case 0: return ConfirmResult.SAVE;
case 1: return ConfirmResult.DONT_SAVE;
default: return ConfirmResult.CANCEL;
}
}
async confirmOverwrite(resource: URI): Promise<boolean> {
const confirm: IConfirmation = {
message: nls.localize('confirmOverwrite', "'{0}' already exists. Do you want to replace it?", basename(resource)),
detail: nls.localize('irreversible', "A file or folder with the same name already exists in the folder {0}. Replacing it will overwrite its current contents.", basename(dirname(resource))),
primaryButton: nls.localize({ key: 'replaceButtonLabel', comment: ['&& denotes a mnemonic'] }, "&&Replace"),
type: 'warning'
};
return (await this.dialogService.confirm(confirm)).confirmed;
}
saveAll(includeUntitled?: boolean, options?: ISaveOptions): Promise<ITextFileOperationResult>;
saveAll(resources: URI[], options?: ISaveOptions): Promise<ITextFileOperationResult>;
saveAll(arg1?: boolean | URI[], options?: ISaveOptions): Promise<ITextFileOperationResult> {
// get all dirty
let toSave: URI[] = [];
if (Array.isArray(arg1)) {
toSave = this.getDirty(arg1);
} else {
toSave = this.getDirty();
}
// split up between files and untitled
const filesToSave: URI[] = [];
const untitledToSave: URI[] = [];
toSave.forEach(s => {
if ((Array.isArray(arg1) || arg1 === true /* includeUntitled */) && s.scheme === Schemas.untitled) {
untitledToSave.push(s);
} else {
filesToSave.push(s);
}
});
return this.doSaveAll(filesToSave, untitledToSave, options);
}
private async doSaveAll(fileResources: URI[], untitledResources: URI[], options?: ISaveOptions): Promise<ITextFileOperationResult> {
// Handle files first that can just be saved
const result = await this.doSaveAllFiles(fileResources, options);
// Preflight for untitled to handle cancellation from the dialog
const targetsForUntitled: URI[] = [];
for (const untitled of untitledResources) {
if (this.untitledEditorService.exists(untitled)) {
let targetUri: URI;
// Untitled with associated file path don't need to prompt
if (this.untitledEditorService.hasAssociatedFilePath(untitled)) {
targetUri = toLocalResource(untitled, this.environmentService.configuration.remoteAuthority);
}
// Otherwise ask user
else {
const targetPath = await this.promptForPath(untitled, this.suggestFileName(untitled));
if (!targetPath) {
return { results: [...fileResources, ...untitledResources].map(r => ({ source: r })) };
}
targetUri = targetPath;
}
targetsForUntitled.push(targetUri);
}
}
// Handle untitled
await Promise.all(targetsForUntitled.map(async (target, index) => {
const uri = await this.saveAs(untitledResources[index], target);
result.results.push({
source: untitledResources[index],
target: uri,
success: !!uri
});
}));
return result;
}
protected async promptForPath(resource: URI, defaultUri: URI): Promise<URI | undefined> {
// Help user to find a name for the file by opening it first
await this.editorService.openEditor({ resource, options: { revealIfOpened: true, preserveFocus: true, } });
return this.fileDialogService.pickFileToSave(this.getSaveDialogOptions(defaultUri));
}
private getSaveDialogOptions(defaultUri: URI): ISaveDialogOptions {
const options: ISaveDialogOptions = {
defaultUri,
title: nls.localize('saveAsTitle', "Save As")
};
// Filters are only enabled on Windows where they work properly
if (!platform.isWindows) {
return options;
}
interface IFilter { name: string; extensions: string[]; }
// Build the file filter by using our known languages
const ext: string | undefined = defaultUri ? extname(defaultUri) : undefined;
let matchingFilter: IFilter | undefined;
const filters: IFilter[] = coalesce(this.modeService.getRegisteredLanguageNames().map(languageName => {
const extensions = this.modeService.getExtensions(languageName);
if (!extensions || !extensions.length) {
return null;
}
const filter: IFilter = { name: languageName, extensions: extensions.slice(0, 10).map(e => trim(e, '.')) };
if (ext && extensions.indexOf(ext) >= 0) {
matchingFilter = filter;
return null; // matching filter will be added last to the top
}
return filter;
}));
// Filters are a bit weird on Windows, based on having a match or not:
// Match: we put the matching filter first so that it shows up selected and the all files last
// No match: we put the all files filter first
const allFilesFilter = { name: nls.localize('allFiles', "All Files"), extensions: ['*'] };
if (matchingFilter) {
filters.unshift(matchingFilter);
filters.unshift(allFilesFilter);
} else {
filters.unshift(allFilesFilter);
}
// Allow to save file without extension
filters.push({ name: nls.localize('noExt', "No Extension"), extensions: [''] });
options.filters = filters;
return options;
}
private async doSaveAllFiles(resources?: URI[], options: ISaveOptions = Object.create(null)): Promise<ITextFileOperationResult> {
const dirtyFileModels = this.getDirtyFileModels(Array.isArray(resources) ? resources : undefined /* Save All */)
.filter(model => {
if ((model.hasState(ModelState.CONFLICT) || model.hasState(ModelState.ERROR)) && (options.reason === SaveReason.AUTO || options.reason === SaveReason.FOCUS_CHANGE || options.reason === SaveReason.WINDOW_CHANGE)) {
return false; // if model is in save conflict or error, do not save unless save reason is explicit or not provided at all
}
return true;
});
const mapResourceToResult = new ResourceMap<IResult>();
dirtyFileModels.forEach(m => {
mapResourceToResult.set(m.getResource(), {
source: m.getResource()
});
});
await Promise.all(dirtyFileModels.map(async model => {
await model.save(options);
if (!model.isDirty()) {
const result = mapResourceToResult.get(model.getResource());
if (result) {
result.success = true;
}
}
}));
return { results: mapResourceToResult.values() };
}
private getFileModels(arg1?: URI | URI[]): ITextFileEditorModel[] {
if (Array.isArray(arg1)) {
const models: ITextFileEditorModel[] = [];
arg1.forEach(resource => {
models.push(...this.getFileModels(resource));
});
return models;
}
return this._models.getAll(arg1);
}
private getDirtyFileModels(resources?: URI | URI[]): ITextFileEditorModel[] {
return this.getFileModels(resources).filter(model => model.isDirty());
}
async saveAs(resource: URI, targetResource?: URI, options?: ISaveOptions): Promise<URI | undefined> {
// Get to target resource
if (!targetResource) {
let dialogPath = resource;
if (resource.scheme === Schemas.untitled) {
dialogPath = this.suggestFileName(resource);
}
targetResource = await this.promptForPath(resource, dialogPath);
}
if (!targetResource) {
return; // user canceled
}
// Just save if target is same as models own resource
if (resource.toString() === targetResource.toString()) {
await this.save(resource, options);
return resource;
}
// Do it
return this.doSaveAs(resource, targetResource, options);
}
private async doSaveAs(resource: URI, target: URI, options?: ISaveOptions): Promise<URI> {
// Retrieve text model from provided resource if any
let model: ITextFileEditorModel | UntitledEditorModel | undefined;
if (this.fileService.canHandleResource(resource)) {
model = this._models.get(resource);
} else if (resource.scheme === Schemas.untitled && this.untitledEditorService.exists(resource)) {
model = await this.untitledEditorService.loadOrCreate({ resource });
}
// We have a model: Use it (can be null e.g. if this file is binary and not a text file or was never opened before)
let result: boolean;
if (model) {
result = await this.doSaveTextFileAs(model, resource, target, options);
}
// Otherwise we can only copy
else {
await this.fileService.copy(resource, target);
result = true;
}
// Return early if the operation was not running
if (!result) {
return target;
}
// Revert the source
await this.revert(resource);
return target;
}
private async doSaveTextFileAs(sourceModel: ITextFileEditorModel | UntitledEditorModel, resource: URI, target: URI, options?: ISaveOptions): Promise<boolean> {
// Prefer an existing model if it is already loaded for the given target resource
let targetExists: boolean = false;
let targetModel = this.models.get(target);
if (targetModel && targetModel.isResolved()) {
targetExists = true;
}
// Otherwise create the target file empty if it does not exist already and resolve it from there
else {
targetExists = await this.fileService.exists(target);
// create target model adhoc if file does not exist yet
if (!targetExists) {
await this.create(target, '');
}
targetModel = await this.models.loadOrCreate(target);
}
try {
// Confirm to overwrite if we have an untitled file with associated file where
// the file actually exists on disk and we are instructed to save to that file
// path. This can happen if the file was created after the untitled file was opened.
// See https://github.com/Microsoft/vscode/issues/67946
let write: boolean;
if (sourceModel instanceof UntitledEditorModel && sourceModel.hasAssociatedFilePath && targetExists && isEqual(target, toLocalResource(sourceModel.getResource(), this.environmentService.configuration.remoteAuthority))) {
write = await this.confirmOverwrite(target);
} else {
write = true;
}
if (!write) {
return false;
}
// take over encoding, mode and model value from source model
targetModel.updatePreferredEncoding(sourceModel.getEncoding());
if (sourceModel.isResolved() && targetModel.isResolved()) {
this.modelService.updateModel(targetModel.textEditorModel, createTextBufferFactoryFromSnapshot(sourceModel.createSnapshot()));
const mode = sourceModel.textEditorModel.getLanguageIdentifier();
if (mode.language !== PLAINTEXT_MODE_ID) {
targetModel.textEditorModel.setMode(mode); // only use if more specific than plain/text
}
}
// save model
await targetModel.save(options);
return true;
} catch (error) {
// binary model: delete the file and run the operation again
if (
(<TextFileOperationError>error).textFileOperationResult === TextFileOperationResult.FILE_IS_BINARY ||
(<FileOperationError>error).fileOperationResult === FileOperationResult.FILE_TOO_LARGE
) {
await this.fileService.del(target);
return this.doSaveTextFileAs(sourceModel, resource, target, options);
}
throw error;
}
}
private suggestFileName(untitledResource: URI): URI {
const untitledFileName = this.untitledEditorService.suggestFileName(untitledResource);
const remoteAuthority = this.environmentService.configuration.remoteAuthority;
const schemeFilter = remoteAuthority ? Schemas.vscodeRemote : Schemas.file;
const lastActiveFile = this.historyService.getLastActiveFile(schemeFilter);
if (lastActiveFile) {
const lastDir = dirname(lastActiveFile);
return joinPath(lastDir, untitledFileName);
}
const lastActiveFolder = this.historyService.getLastActiveWorkspaceRoot(schemeFilter);
if (lastActiveFolder) {
return joinPath(lastActiveFolder, untitledFileName);
}
return schemeFilter === Schemas.file ? URI.file(untitledFileName) : URI.from({ scheme: schemeFilter, authority: remoteAuthority, path: posix.sep + untitledFileName });
}
async revert(resource: URI, options?: IRevertOptions): Promise<boolean> {
const result = await this.revertAll([resource], options);
return result.results.length === 1 && !!result.results[0].success;
}
async revertAll(resources?: URI[], options?: IRevertOptions): Promise<ITextFileOperationResult> {
// Revert files first
const revertOperationResult = await this.doRevertAllFiles(resources, options);
// Revert untitled
const untitledReverted = this.untitledEditorService.revertAll(resources);
untitledReverted.forEach(untitled => revertOperationResult.results.push({ source: untitled, success: true }));
return revertOperationResult;
}
private async doRevertAllFiles(resources?: URI[], options?: IRevertOptions): Promise<ITextFileOperationResult> {
const fileModels = options && options.force ? this.getFileModels(resources) : this.getDirtyFileModels(resources);
const mapResourceToResult = new ResourceMap<IResult>();
fileModels.forEach(m => {
mapResourceToResult.set(m.getResource(), {
source: m.getResource()
});
});
await Promise.all(fileModels.map(async model => {
try {
await model.revert(options && options.soft);
if (!model.isDirty()) {
const result = mapResourceToResult.get(model.getResource());
if (result) {
result.success = true;
}
}
} catch (error) {
// FileNotFound means the file got deleted meanwhile, so still record as successful revert
if ((<FileOperationError>error).fileOperationResult === FileOperationResult.FILE_NOT_FOUND) {
const result = mapResourceToResult.get(model.getResource());
if (result) {
result.success = true;
}
}
// Otherwise bubble up the error
else {
throw error;
}
}
}));
return { results: mapResourceToResult.values() };
}
getDirty(resources?: URI[]): URI[] {
// Collect files
const dirty = this.getDirtyFileModels(resources).map(m => m.getResource());
// Add untitled ones
dirty.push(...this.untitledEditorService.getDirty(resources));
return dirty;
}
isDirty(resource?: URI): boolean {
// Check for dirty file
if (this._models.getAll(resource).some(model => model.isDirty())) {
return true;
}
// Check for dirty untitled
return this.untitledEditorService.getDirty().some(dirty => !resource || dirty.toString() === resource.toString());
}
//#endregion
//#region config
getAutoSaveMode(): AutoSaveMode {
if (this.configuredAutoSaveOnFocusChange) {
return AutoSaveMode.ON_FOCUS_CHANGE;
}
if (this.configuredAutoSaveOnWindowChange) {
return AutoSaveMode.ON_WINDOW_CHANGE;
}
if (this.configuredAutoSaveDelay && this.configuredAutoSaveDelay > 0) {
return this.configuredAutoSaveDelay <= 1000 ? AutoSaveMode.AFTER_SHORT_DELAY : AutoSaveMode.AFTER_LONG_DELAY;
}
return AutoSaveMode.OFF;
}
getAutoSaveConfiguration(): IAutoSaveConfiguration {
return {
autoSaveDelay: this.configuredAutoSaveDelay && this.configuredAutoSaveDelay > 0 ? this.configuredAutoSaveDelay : undefined,
autoSaveFocusChange: this.configuredAutoSaveOnFocusChange,
autoSaveApplicationChange: this.configuredAutoSaveOnWindowChange
};
}
get isHotExitEnabled(): boolean {
return !this.environmentService.isExtensionDevelopment && this.configuredHotExit !== HotExitConfiguration.OFF;
}
//#endregion
dispose(): void {
// Clear all caches
this._models.clear();
super.dispose();
}
} | src/vs/workbench/services/textfile/common/textFileService.ts | 1 | https://github.com/microsoft/vscode/commit/985de26b3446636f86e2bb2b14dbeb9ec1e33207 | [
0.004500763490796089,
0.0002837943029589951,
0.00015993037959560752,
0.00016987693379633129,
0.0005825388943776488
] |
{
"id": 7,
"code_window": [
"\t\t\t\tisAcceptHandled = true;\n",
"\t\t\t\tisResolving++;\n",
"\t\t\t\tif (this.options.availableFileSystems && (this.options.availableFileSystems.length > 1)) {\n",
"\t\t\t\t\tthis.options.availableFileSystems.shift();\n",
"\t\t\t\t}\n",
"\t\t\t\tthis.options.defaultUri = undefined;\n",
"\t\t\t\tthis.filePickBox.hide();\n",
"\t\t\t\tif (isSave) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/services/dialogs/browser/remoteFileDialog.ts",
"type": "replace",
"edit_start_line_idx": 256
} | /*---------------------------------------------------------------------------------------------
* 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 { templateToSnippet } from '../features/jsDocCompletions';
const joinLines = (...args: string[]) => args.join('\n');
suite('typescript.jsDocSnippet', () => {
test('Should do nothing for single line input', async () => {
const input = `/** */`;
assert.strictEqual(templateToSnippet(input).value, input);
});
test('Should put cursor inside multiline line input', async () => {
assert.strictEqual(
templateToSnippet(joinLines(
'/**',
' * ',
' */'
)).value,
joinLines(
'/**',
' * $0',
' */'
));
});
test('Should add placeholders after each parameter', async () => {
assert.strictEqual(
templateToSnippet(joinLines(
'/**',
' * @param a',
' * @param b',
' */'
)).value,
joinLines(
'/**',
' * @param a ${1}',
' * @param b ${2}',
' */'
));
});
test('Should add placeholders for types', async () => {
assert.strictEqual(
templateToSnippet(joinLines(
'/**',
' * @param {*} a',
' * @param {*} b',
' */'
)).value,
joinLines(
'/**',
' * @param {${1:*}} a ${2}',
' * @param {${3:*}} b ${4}',
' */'
));
});
test('Should properly escape dollars in parameter names', async () => {
assert.strictEqual(
templateToSnippet(joinLines(
'/**',
' * ',
' * @param $arg',
' */'
)).value,
joinLines(
'/**',
' * $0',
' * @param \\$arg ${1}',
' */'
));
});
});
| extensions/typescript-language-features/src/test/jsdocSnippet.test.ts | 0 | https://github.com/microsoft/vscode/commit/985de26b3446636f86e2bb2b14dbeb9ec1e33207 | [
0.00017560152627993375,
0.00017174056847579777,
0.00016708970360923558,
0.00017171412764582783,
0.0000024214402856159722
] |
{
"id": 7,
"code_window": [
"\t\t\t\tisAcceptHandled = true;\n",
"\t\t\t\tisResolving++;\n",
"\t\t\t\tif (this.options.availableFileSystems && (this.options.availableFileSystems.length > 1)) {\n",
"\t\t\t\t\tthis.options.availableFileSystems.shift();\n",
"\t\t\t\t}\n",
"\t\t\t\tthis.options.defaultUri = undefined;\n",
"\t\t\t\tthis.filePickBox.hide();\n",
"\t\t\t\tif (isSave) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/services/dialogs/browser/remoteFileDialog.ts",
"type": "replace",
"edit_start_line_idx": 256
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
.monaco-sash {
position: absolute;
z-index: 35;
touch-action: none;
}
.monaco-sash.disabled {
pointer-events: none;
}
.monaco-sash.vertical {
cursor: ew-resize;
top: 0;
width: 4px;
height: 100%;
}
.monaco-sash.mac.vertical {
cursor: col-resize;
}
.monaco-sash.vertical.minimum {
cursor: e-resize;
}
.monaco-sash.vertical.maximum {
cursor: w-resize;
}
.monaco-sash.horizontal {
cursor: ns-resize;
left: 0;
width: 100%;
height: 4px;
}
.monaco-sash.mac.horizontal {
cursor: row-resize;
}
.monaco-sash.horizontal.minimum {
cursor: s-resize;
}
.monaco-sash.horizontal.maximum {
cursor: n-resize;
}
.monaco-sash:not(.disabled).orthogonal-start::before,
.monaco-sash:not(.disabled).orthogonal-end::after {
content: ' ';
height: 8px;
width: 8px;
z-index: 100;
display: block;
cursor: all-scroll;
position: absolute;
}
.monaco-sash.orthogonal-start.vertical::before {
left: -2px;
top: -4px;
}
.monaco-sash.orthogonal-end.vertical::after {
left: -2px;
bottom: -4px;
}
.monaco-sash.orthogonal-start.horizontal::before {
top: -2px;
left: -4px;
}
.monaco-sash.orthogonal-end.horizontal::after {
top: -2px;
right: -4px;
}
.monaco-sash.disabled {
cursor: default !important;
pointer-events: none !important;
}
/** Touch **/
.monaco-sash.touch.vertical {
width: 20px;
}
.monaco-sash.touch.horizontal {
height: 20px;
}
/** Debug **/
.monaco-sash.debug {
background: cyan;
}
.monaco-sash.debug.disabled {
background: rgba(0, 255, 255, 0.2);
}
.monaco-sash.debug:not(.disabled).orthogonal-start::before,
.monaco-sash.debug:not(.disabled).orthogonal-end::after {
background: red;
} | src/vs/base/browser/ui/sash/sash.css | 0 | https://github.com/microsoft/vscode/commit/985de26b3446636f86e2bb2b14dbeb9ec1e33207 | [
0.0001766661152942106,
0.00017421609663870186,
0.00017236944404430687,
0.0001743350876495242,
0.0000011945743381147622
] |
{
"id": 7,
"code_window": [
"\t\t\t\tisAcceptHandled = true;\n",
"\t\t\t\tisResolving++;\n",
"\t\t\t\tif (this.options.availableFileSystems && (this.options.availableFileSystems.length > 1)) {\n",
"\t\t\t\t\tthis.options.availableFileSystems.shift();\n",
"\t\t\t\t}\n",
"\t\t\t\tthis.options.defaultUri = undefined;\n",
"\t\t\t\tthis.filePickBox.hide();\n",
"\t\t\t\tif (isSave) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/services/dialogs/browser/remoteFileDialog.ts",
"type": "replace",
"edit_start_line_idx": 256
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import {
createConnection, IConnection, TextDocuments, InitializeParams, InitializeResult, ServerCapabilities, ConfigurationRequest, WorkspaceFolder, TextDocumentSyncKind
} from 'vscode-languageserver';
import URI from 'vscode-uri';
import { TextDocument, CompletionList, Position } from 'vscode-languageserver-types';
import { getCSSLanguageService, getSCSSLanguageService, getLESSLanguageService, LanguageSettings, LanguageService, Stylesheet } from 'vscode-css-languageservice';
import { getLanguageModelCache } from './languageModelCache';
import { getPathCompletionParticipant } from './pathCompletion';
import { formatError, runSafe } from './utils/runner';
import { getDocumentContext } from './utils/documentContext';
import { getDataProviders } from './customData';
export interface Settings {
css: LanguageSettings;
less: LanguageSettings;
scss: LanguageSettings;
}
// Create a connection for the server.
const connection: IConnection = createConnection();
console.log = connection.console.log.bind(connection.console);
console.error = connection.console.error.bind(connection.console);
process.on('unhandledRejection', (e: any) => {
connection.console.error(formatError(`Unhandled exception`, e));
});
// Create a text document manager.
const documents: TextDocuments = new TextDocuments(TextDocumentSyncKind.Incremental);
// Make the text document manager listen on the connection
// for open, change and close text document events
documents.listen(connection);
const stylesheets = getLanguageModelCache<Stylesheet>(10, 60, document => getLanguageService(document).parseStylesheet(document));
documents.onDidClose(e => {
stylesheets.onDocumentRemoved(e.document);
});
connection.onShutdown(() => {
stylesheets.dispose();
});
let scopedSettingsSupport = false;
let foldingRangeLimit = Number.MAX_VALUE;
let workspaceFolders: WorkspaceFolder[];
const languageServices: { [id: string]: LanguageService } = {};
// After the server has started the client sends an initialize request. The server receives
// in the passed params the rootPath of the workspace plus the client capabilities.
connection.onInitialize((params: InitializeParams): InitializeResult => {
workspaceFolders = (<any>params).workspaceFolders;
if (!Array.isArray(workspaceFolders)) {
workspaceFolders = [];
if (params.rootPath) {
workspaceFolders.push({ name: '', uri: URI.file(params.rootPath).toString() });
}
}
const dataPaths: string[] = params.initializationOptions.dataPaths;
const customDataProviders = getDataProviders(dataPaths);
function getClientCapability<T>(name: string, def: T) {
const keys = name.split('.');
let c: any = params.capabilities;
for (let i = 0; c && i < keys.length; i++) {
if (!c.hasOwnProperty(keys[i])) {
return def;
}
c = c[keys[i]];
}
return c;
}
const snippetSupport = !!getClientCapability('textDocument.completion.completionItem.snippetSupport', false);
scopedSettingsSupport = !!getClientCapability('workspace.configuration', false);
foldingRangeLimit = getClientCapability('textDocument.foldingRange.rangeLimit', Number.MAX_VALUE);
languageServices.css = getCSSLanguageService({ customDataProviders });
languageServices.scss = getSCSSLanguageService({ customDataProviders });
languageServices.less = getLESSLanguageService({ customDataProviders });
const capabilities: ServerCapabilities = {
// Tell the client that the server works in FULL text document sync mode
textDocumentSync: documents.syncKind,
completionProvider: snippetSupport ? { resolveProvider: false, triggerCharacters: ['/'] } : undefined,
hoverProvider: true,
documentSymbolProvider: true,
referencesProvider: true,
definitionProvider: true,
documentHighlightProvider: true,
documentLinkProvider: {
resolveProvider: false
},
codeActionProvider: true,
renameProvider: true,
colorProvider: {},
foldingRangeProvider: true
};
return { capabilities };
});
function getLanguageService(document: TextDocument) {
let service = languageServices[document.languageId];
if (!service) {
connection.console.log('Document type is ' + document.languageId + ', using css instead.');
service = languageServices['css'];
}
return service;
}
let documentSettings: { [key: string]: Thenable<LanguageSettings | undefined> } = {};
// remove document settings on close
documents.onDidClose(e => {
delete documentSettings[e.document.uri];
});
function getDocumentSettings(textDocument: TextDocument): Thenable<LanguageSettings | undefined> {
if (scopedSettingsSupport) {
let promise = documentSettings[textDocument.uri];
if (!promise) {
const configRequestParam = { items: [{ scopeUri: textDocument.uri, section: textDocument.languageId }] };
promise = connection.sendRequest(ConfigurationRequest.type, configRequestParam).then(s => s[0]);
documentSettings[textDocument.uri] = promise;
}
return promise;
}
return Promise.resolve(undefined);
}
// The settings have changed. Is send on server activation as well.
connection.onDidChangeConfiguration(change => {
updateConfiguration(<Settings>change.settings);
});
function updateConfiguration(settings: Settings) {
for (const languageId in languageServices) {
languageServices[languageId].configure((settings as any)[languageId]);
}
// reset all document settings
documentSettings = {};
// Revalidate any open text documents
documents.all().forEach(triggerValidation);
}
const pendingValidationRequests: { [uri: string]: NodeJS.Timer } = {};
const validationDelayMs = 500;
// The content of a text document has changed. This event is emitted
// when the text document first opened or when its content has changed.
documents.onDidChangeContent(change => {
triggerValidation(change.document);
});
// a document has closed: clear all diagnostics
documents.onDidClose(event => {
cleanPendingValidation(event.document);
connection.sendDiagnostics({ uri: event.document.uri, diagnostics: [] });
});
function cleanPendingValidation(textDocument: TextDocument): void {
const request = pendingValidationRequests[textDocument.uri];
if (request) {
clearTimeout(request);
delete pendingValidationRequests[textDocument.uri];
}
}
function triggerValidation(textDocument: TextDocument): void {
cleanPendingValidation(textDocument);
pendingValidationRequests[textDocument.uri] = setTimeout(() => {
delete pendingValidationRequests[textDocument.uri];
validateTextDocument(textDocument);
}, validationDelayMs);
}
function validateTextDocument(textDocument: TextDocument): void {
const settingsPromise = getDocumentSettings(textDocument);
settingsPromise.then(settings => {
const stylesheet = stylesheets.get(textDocument);
const diagnostics = getLanguageService(textDocument).doValidation(textDocument, stylesheet, settings);
// Send the computed diagnostics to VSCode.
connection.sendDiagnostics({ uri: textDocument.uri, diagnostics });
}, e => {
connection.console.error(formatError(`Error while validating ${textDocument.uri}`, e));
});
}
connection.onCompletion((textDocumentPosition, token) => {
return runSafe(() => {
const document = documents.get(textDocumentPosition.textDocument.uri);
if (!document) {
return null;
}
const cssLS = getLanguageService(document);
const pathCompletionList: CompletionList = {
isIncomplete: false,
items: []
};
cssLS.setCompletionParticipants([getPathCompletionParticipant(document, workspaceFolders, pathCompletionList)]);
const result = cssLS.doComplete(document, textDocumentPosition.position, stylesheets.get(document));
return {
isIncomplete: pathCompletionList.isIncomplete,
items: [...pathCompletionList.items, ...result.items]
};
}, null, `Error while computing completions for ${textDocumentPosition.textDocument.uri}`, token);
});
connection.onHover((textDocumentPosition, token) => {
return runSafe(() => {
const document = documents.get(textDocumentPosition.textDocument.uri);
if (document) {
const styleSheet = stylesheets.get(document);
return getLanguageService(document).doHover(document, textDocumentPosition.position, styleSheet);
}
return null;
}, null, `Error while computing hover for ${textDocumentPosition.textDocument.uri}`, token);
});
connection.onDocumentSymbol((documentSymbolParams, token) => {
return runSafe(() => {
const document = documents.get(documentSymbolParams.textDocument.uri);
if (document) {
const stylesheet = stylesheets.get(document);
return getLanguageService(document).findDocumentSymbols(document, stylesheet);
}
return [];
}, [], `Error while computing document symbols for ${documentSymbolParams.textDocument.uri}`, token);
});
connection.onDefinition((documentDefinitionParams, token) => {
return runSafe(() => {
const document = documents.get(documentDefinitionParams.textDocument.uri);
if (document) {
const stylesheet = stylesheets.get(document);
return getLanguageService(document).findDefinition(document, documentDefinitionParams.position, stylesheet);
}
return null;
}, null, `Error while computing definitions for ${documentDefinitionParams.textDocument.uri}`, token);
});
connection.onDocumentHighlight((documentHighlightParams, token) => {
return runSafe(() => {
const document = documents.get(documentHighlightParams.textDocument.uri);
if (document) {
const stylesheet = stylesheets.get(document);
return getLanguageService(document).findDocumentHighlights(document, documentHighlightParams.position, stylesheet);
}
return [];
}, [], `Error while computing document highlights for ${documentHighlightParams.textDocument.uri}`, token);
});
connection.onDocumentLinks((documentLinkParams, token) => {
return runSafe(() => {
const document = documents.get(documentLinkParams.textDocument.uri);
if (document) {
const documentContext = getDocumentContext(document.uri, workspaceFolders);
const stylesheet = stylesheets.get(document);
return getLanguageService(document).findDocumentLinks(document, stylesheet, documentContext);
}
return [];
}, [], `Error while computing document links for ${documentLinkParams.textDocument.uri}`, token);
});
connection.onReferences((referenceParams, token) => {
return runSafe(() => {
const document = documents.get(referenceParams.textDocument.uri);
if (document) {
const stylesheet = stylesheets.get(document);
return getLanguageService(document).findReferences(document, referenceParams.position, stylesheet);
}
return [];
}, [], `Error while computing references for ${referenceParams.textDocument.uri}`, token);
});
connection.onCodeAction((codeActionParams, token) => {
return runSafe(() => {
const document = documents.get(codeActionParams.textDocument.uri);
if (document) {
const stylesheet = stylesheets.get(document);
return getLanguageService(document).doCodeActions(document, codeActionParams.range, codeActionParams.context, stylesheet);
}
return [];
}, [], `Error while computing code actions for ${codeActionParams.textDocument.uri}`, token);
});
connection.onDocumentColor((params, token) => {
return runSafe(() => {
const document = documents.get(params.textDocument.uri);
if (document) {
const stylesheet = stylesheets.get(document);
return getLanguageService(document).findDocumentColors(document, stylesheet);
}
return [];
}, [], `Error while computing document colors for ${params.textDocument.uri}`, token);
});
connection.onColorPresentation((params, token) => {
return runSafe(() => {
const document = documents.get(params.textDocument.uri);
if (document) {
const stylesheet = stylesheets.get(document);
return getLanguageService(document).getColorPresentations(document, stylesheet, params.color, params.range);
}
return [];
}, [], `Error while computing color presentations for ${params.textDocument.uri}`, token);
});
connection.onRenameRequest((renameParameters, token) => {
return runSafe(() => {
const document = documents.get(renameParameters.textDocument.uri);
if (document) {
const stylesheet = stylesheets.get(document);
return getLanguageService(document).doRename(document, renameParameters.position, renameParameters.newName, stylesheet);
}
return null;
}, null, `Error while computing renames for ${renameParameters.textDocument.uri}`, token);
});
connection.onFoldingRanges((params, token) => {
return runSafe(() => {
const document = documents.get(params.textDocument.uri);
if (document) {
return getLanguageService(document).getFoldingRanges(document, { rangeLimit: foldingRangeLimit });
}
return null;
}, null, `Error while computing folding ranges for ${params.textDocument.uri}`, token);
});
connection.onRequest('$/textDocument/selectionRanges', async (params, token) => {
return runSafe(() => {
const document = documents.get(params.textDocument.uri);
const positions: Position[] = params.positions;
if (document) {
const stylesheet = stylesheets.get(document);
return getLanguageService(document).getSelectionRanges(document, positions, stylesheet);
}
return Promise.resolve(null);
}, null, `Error while computing selection ranges for ${params.textDocument.uri}`, token);
});
// Listen on the connection
connection.listen(); | extensions/css-language-features/server/src/cssServerMain.ts | 0 | https://github.com/microsoft/vscode/commit/985de26b3446636f86e2bb2b14dbeb9ec1e33207 | [
0.00017634214600548148,
0.0001722995948512107,
0.00016486598178744316,
0.00017319007019978017,
0.0000027614978534984402
] |
{
"id": 8,
"code_window": [
"\t\t\t\tthis.filePickBox.hide();\n",
"\t\t\t\tif (isSave) {\n",
"\t\t\t\t\t// Remove defaultUri and filters to get a consistant experience with the keybinding.\n",
"\t\t\t\t\tthis.options.defaultUri = undefined;\n",
"\t\t\t\t\tthis.options.filters = undefined;\n",
"\t\t\t\t\treturn this.fileDialogService.showSaveDialog(this.options).then(result => {\n",
"\t\t\t\t\t\tdoResolve(this, result);\n",
"\t\t\t\t\t});\n",
"\t\t\t\t} else {\n",
"\t\t\t\t\treturn this.fileDialogService.showOpenDialog(this.options).then(result => {\n"
],
"labels": [
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/services/dialogs/browser/remoteFileDialog.ts",
"type": "replace",
"edit_start_line_idx": 259
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Action } from 'vs/base/common/actions';
import * as nls from 'vs/nls';
import { IWindowService } from 'vs/platform/windows/common/windows';
import { ITelemetryData } from 'vs/platform/telemetry/common/telemetry';
import { IWorkspaceContextService, WorkbenchState, IWorkspaceFolder } from 'vs/platform/workspace/common/workspace';
import { IWorkspaceEditingService } from 'vs/workbench/services/workspace/common/workspaceEditing';
import { IWorkspacesService } from 'vs/platform/workspaces/common/workspaces';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { ICommandService } from 'vs/platform/commands/common/commands';
import { ADD_ROOT_FOLDER_COMMAND_ID, ADD_ROOT_FOLDER_LABEL, PICK_WORKSPACE_FOLDER_COMMAND_ID } from 'vs/workbench/browser/actions/workspaceCommands';
import { IFileDialogService } from 'vs/platform/dialogs/common/dialogs';
import { INotificationService } from 'vs/platform/notification/common/notification';
import { Schemas } from 'vs/base/common/network';
import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService';
export class OpenFileAction extends Action {
static readonly ID = 'workbench.action.files.openFile';
static LABEL = nls.localize('openFile', "Open File...");
constructor(
id: string,
label: string,
@IFileDialogService private readonly dialogService: IFileDialogService
) {
super(id, label);
}
run(event?: any, data?: ITelemetryData): Promise<any> {
return this.dialogService.pickFileAndOpen({ forceNewWindow: false, telemetryExtraData: data });
}
}
export class OpenLocalFileAction extends Action {
static readonly ID = 'workbench.action.files.openLocalFile';
static LABEL = nls.localize('openLocalFile', "Open Local File...");
constructor(
id: string,
label: string,
@IFileDialogService private readonly dialogService: IFileDialogService
) {
super(id, label);
}
run(event?: any, data?: ITelemetryData): Promise<any> {
return this.dialogService.pickFileAndOpen({ forceNewWindow: false, telemetryExtraData: data, availableFileSystems: [Schemas.file] });
}
}
export class SaveLocalFileAction extends Action {
static readonly ID = 'workbench.action.files.saveLocalFile';
static LABEL = nls.localize('saveLocalFile', "Save Local File...");
constructor(
id: string,
label: string,
@IFileDialogService private readonly dialogService: IFileDialogService
) {
super(id, label);
}
run(event?: any, data?: ITelemetryData): Promise<any> {
return this.dialogService.pickFileToSave({ availableFileSystems: [Schemas.file] });
}
}
export class OpenFolderAction extends Action {
static readonly ID = 'workbench.action.files.openFolder';
static LABEL = nls.localize('openFolder', "Open Folder...");
constructor(
id: string,
label: string,
@IFileDialogService private readonly dialogService: IFileDialogService
) {
super(id, label);
}
run(event?: any, data?: ITelemetryData): Promise<any> {
return this.dialogService.pickFolderAndOpen({ forceNewWindow: false, telemetryExtraData: data });
}
}
export class OpenLocalFolderAction extends Action {
static readonly ID = 'workbench.action.files.openLocalFolder';
static LABEL = nls.localize('openLocalFolder', "Open Local Folder...");
constructor(
id: string,
label: string,
@IFileDialogService private readonly dialogService: IFileDialogService
) {
super(id, label);
}
run(event?: any, data?: ITelemetryData): Promise<any> {
return this.dialogService.pickFolderAndOpen({ forceNewWindow: false, telemetryExtraData: data, availableFileSystems: [Schemas.file] });
}
}
export class OpenFileFolderAction extends Action {
static readonly ID = 'workbench.action.files.openFileFolder';
static LABEL = nls.localize('openFileFolder', "Open...");
constructor(
id: string,
label: string,
@IFileDialogService private readonly dialogService: IFileDialogService
) {
super(id, label);
}
run(event?: any, data?: ITelemetryData): Promise<any> {
return this.dialogService.pickFileFolderAndOpen({ forceNewWindow: false, telemetryExtraData: data });
}
}
export class OpenLocalFileFolderAction extends Action {
static readonly ID = 'workbench.action.files.openLocalFileFolder';
static LABEL = nls.localize('openLocalFileFolder', "Open Local...");
constructor(
id: string,
label: string,
@IFileDialogService private readonly dialogService: IFileDialogService
) {
super(id, label);
}
run(event?: any, data?: ITelemetryData): Promise<any> {
return this.dialogService.pickFileFolderAndOpen({ forceNewWindow: false, telemetryExtraData: data, availableFileSystems: [Schemas.file] });
}
}
export class AddRootFolderAction extends Action {
static readonly ID = 'workbench.action.addRootFolder';
static LABEL = ADD_ROOT_FOLDER_LABEL;
constructor(
id: string,
label: string,
@ICommandService private readonly commandService: ICommandService
) {
super(id, label);
}
run(): Promise<any> {
return this.commandService.executeCommand(ADD_ROOT_FOLDER_COMMAND_ID);
}
}
export class GlobalRemoveRootFolderAction extends Action {
static readonly ID = 'workbench.action.removeRootFolder';
static LABEL = nls.localize('globalRemoveFolderFromWorkspace', "Remove Folder from Workspace...");
constructor(
id: string,
label: string,
@IWorkspaceEditingService private readonly workspaceEditingService: IWorkspaceEditingService,
@IWorkspaceContextService private readonly contextService: IWorkspaceContextService,
@ICommandService private readonly commandService: ICommandService
) {
super(id, label);
}
async run(): Promise<any> {
const state = this.contextService.getWorkbenchState();
// Workspace / Folder
if (state === WorkbenchState.WORKSPACE || state === WorkbenchState.FOLDER) {
const folder = await this.commandService.executeCommand<IWorkspaceFolder>(PICK_WORKSPACE_FOLDER_COMMAND_ID);
if (folder) {
await this.workspaceEditingService.removeFolders([folder.uri]);
}
}
return true;
}
}
export class SaveWorkspaceAsAction extends Action {
static readonly ID = 'workbench.action.saveWorkspaceAs';
static LABEL = nls.localize('saveWorkspaceAsAction', "Save Workspace As...");
constructor(
id: string,
label: string,
@IWorkspaceContextService private readonly contextService: IWorkspaceContextService,
@IWorkspaceEditingService private readonly workspaceEditingService: IWorkspaceEditingService
) {
super(id, label);
}
async run(): Promise<any> {
const configPathUri = await this.workspaceEditingService.pickNewWorkspacePath();
if (configPathUri) {
switch (this.contextService.getWorkbenchState()) {
case WorkbenchState.EMPTY:
case WorkbenchState.FOLDER:
const folders = this.contextService.getWorkspace().folders.map(folder => ({ uri: folder.uri }));
return this.workspaceEditingService.createAndEnterWorkspace(folders, configPathUri);
case WorkbenchState.WORKSPACE:
return this.workspaceEditingService.saveAndEnterWorkspace(configPathUri);
}
}
}
}
export class OpenWorkspaceAction extends Action {
static readonly ID = 'workbench.action.openWorkspace';
static LABEL = nls.localize('openWorkspaceAction', "Open Workspace...");
constructor(
id: string,
label: string,
@IFileDialogService private readonly dialogService: IFileDialogService
) {
super(id, label);
}
run(event?: any, data?: ITelemetryData): Promise<any> {
return this.dialogService.pickWorkspaceAndOpen({ telemetryExtraData: data });
}
}
export class CloseWorkspaceAction extends Action {
static readonly ID = 'workbench.action.closeFolder';
static LABEL = nls.localize('closeWorkspace', "Close Workspace");
constructor(
id: string,
label: string,
@IWorkspaceContextService private readonly contextService: IWorkspaceContextService,
@INotificationService private readonly notificationService: INotificationService,
@IWindowService private readonly windowService: IWindowService
) {
super(id, label);
}
run(): Promise<void> {
if (this.contextService.getWorkbenchState() === WorkbenchState.EMPTY) {
this.notificationService.info(nls.localize('noWorkspaceOpened', "There is currently no workspace opened in this instance to close."));
return Promise.resolve(undefined);
}
return this.windowService.closeWorkspace();
}
}
export class OpenWorkspaceConfigFileAction extends Action {
static readonly ID = 'workbench.action.openWorkspaceConfigFile';
static readonly LABEL = nls.localize('openWorkspaceConfigFile', "Open Workspace Configuration File");
constructor(
id: string,
label: string,
@IWorkspaceContextService private readonly workspaceContextService: IWorkspaceContextService,
@IEditorService private readonly editorService: IEditorService
) {
super(id, label);
this.enabled = !!this.workspaceContextService.getWorkspace().configuration;
}
run(): Promise<any> {
const configuration = this.workspaceContextService.getWorkspace().configuration;
if (configuration) {
return this.editorService.openEditor({ resource: configuration });
}
return Promise.resolve();
}
}
export class DuplicateWorkspaceInNewWindowAction extends Action {
static readonly ID = 'workbench.action.duplicateWorkspaceInNewWindow';
static readonly LABEL = nls.localize('duplicateWorkspaceInNewWindow', "Duplicate Workspace in New Window");
constructor(
id: string,
label: string,
@IWorkspaceContextService private readonly workspaceContextService: IWorkspaceContextService,
@IWorkspaceEditingService private readonly workspaceEditingService: IWorkspaceEditingService,
@IWindowService private readonly windowService: IWindowService,
@IWorkspacesService private readonly workspacesService: IWorkspacesService,
@IWorkbenchEnvironmentService private readonly environmentService: IWorkbenchEnvironmentService
) {
super(id, label);
}
async run(): Promise<any> {
const folders = this.workspaceContextService.getWorkspace().folders;
const remoteAuthority = this.environmentService.configuration.remoteAuthority;
const newWorkspace = await this.workspacesService.createUntitledWorkspace(folders, remoteAuthority);
await this.workspaceEditingService.copyWorkspaceSettings(newWorkspace);
return this.windowService.openWindow([{ workspaceUri: newWorkspace.configPath }], { forceNewWindow: true });
}
}
| src/vs/workbench/browser/actions/workspaceActions.ts | 1 | https://github.com/microsoft/vscode/commit/985de26b3446636f86e2bb2b14dbeb9ec1e33207 | [
0.00022418241132982075,
0.00017272052355110645,
0.00016267559840343893,
0.00016945581592153758,
0.000011746456948458217
] |
{
"id": 8,
"code_window": [
"\t\t\t\tthis.filePickBox.hide();\n",
"\t\t\t\tif (isSave) {\n",
"\t\t\t\t\t// Remove defaultUri and filters to get a consistant experience with the keybinding.\n",
"\t\t\t\t\tthis.options.defaultUri = undefined;\n",
"\t\t\t\t\tthis.options.filters = undefined;\n",
"\t\t\t\t\treturn this.fileDialogService.showSaveDialog(this.options).then(result => {\n",
"\t\t\t\t\t\tdoResolve(this, result);\n",
"\t\t\t\t\t});\n",
"\t\t\t\t} else {\n",
"\t\t\t\t\treturn this.fileDialogService.showOpenDialog(this.options).then(result => {\n"
],
"labels": [
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/services/dialogs/browser/remoteFileDialog.ts",
"type": "replace",
"edit_start_line_idx": 259
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as assert from 'assert';
import 'mocha';
import * as vscode from 'vscode';
import { CURSOR, withRandomFileEditor } from './testUtils';
const onDocumentChange = (doc: vscode.TextDocument): Promise<vscode.TextDocument> => {
return new Promise<vscode.TextDocument>(resolve => {
const sub = vscode.workspace.onDidChangeTextDocument(e => {
if (e.document !== doc) {
return;
}
sub.dispose();
resolve(e.document);
});
});
};
const type = async (document: vscode.TextDocument, text: string): Promise<vscode.TextDocument> => {
const onChange = onDocumentChange(document);
await vscode.commands.executeCommand('type', { text });
await onChange;
return document;
};
suite('OnEnter', () => {
test('should indent after if block with braces', () => {
return withRandomFileEditor(`if (true) {${CURSOR}`, 'js', async (_editor, document) => {
await type(document, '\nx');
assert.strictEqual(document.getText(), `if (true) {\n x`);
});
});
test('should indent within empty object literal', () => {
return withRandomFileEditor(`({${CURSOR}})`, 'js', async (_editor, document) => {
await type(document, '\nx');
assert.strictEqual(document.getText(), `({\n x\n})`);
});
});
test('should indent after simple jsx tag with attributes', () => {
return withRandomFileEditor(`const a = <div onclick={bla}>${CURSOR}`, 'jsx', async (_editor, document) => {
await type(document, '\nx');
assert.strictEqual(document.getText(), `const a = <div onclick={bla}>\n x`);
});
});
test('should indent after simple jsx tag with attributes', () => {
return withRandomFileEditor(`const a = <div onclick={bla}>${CURSOR}`, 'jsx', async (_editor, document) => {
await type(document, '\nx');
assert.strictEqual(document.getText(), `const a = <div onclick={bla}>\n x`);
});
});
}); | extensions/typescript-language-features/src/test/onEnter.test.ts | 0 | https://github.com/microsoft/vscode/commit/985de26b3446636f86e2bb2b14dbeb9ec1e33207 | [
0.00017517824016977102,
0.00017371586000081152,
0.00017222750466316938,
0.00017377399490214884,
8.973406693257857e-7
] |
{
"id": 8,
"code_window": [
"\t\t\t\tthis.filePickBox.hide();\n",
"\t\t\t\tif (isSave) {\n",
"\t\t\t\t\t// Remove defaultUri and filters to get a consistant experience with the keybinding.\n",
"\t\t\t\t\tthis.options.defaultUri = undefined;\n",
"\t\t\t\t\tthis.options.filters = undefined;\n",
"\t\t\t\t\treturn this.fileDialogService.showSaveDialog(this.options).then(result => {\n",
"\t\t\t\t\t\tdoResolve(this, result);\n",
"\t\t\t\t\t});\n",
"\t\t\t\t} else {\n",
"\t\t\t\t\treturn this.fileDialogService.showOpenDialog(this.options).then(result => {\n"
],
"labels": [
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/services/dialogs/browser/remoteFileDialog.ts",
"type": "replace",
"edit_start_line_idx": 259
} | <svg width="16" height="16" xmlns="http://www.w3.org/2000/svg"><title>Layer 1</title><rect height="3" width="11" y="7" x="3" fill="#424242"/></svg> | src/vs/editor/browser/widget/media/deletion.svg | 0 | https://github.com/microsoft/vscode/commit/985de26b3446636f86e2bb2b14dbeb9ec1e33207 | [
0.0001709315984044224,
0.0001709315984044224,
0.0001709315984044224,
0.0001709315984044224,
0
] |
{
"id": 8,
"code_window": [
"\t\t\t\tthis.filePickBox.hide();\n",
"\t\t\t\tif (isSave) {\n",
"\t\t\t\t\t// Remove defaultUri and filters to get a consistant experience with the keybinding.\n",
"\t\t\t\t\tthis.options.defaultUri = undefined;\n",
"\t\t\t\t\tthis.options.filters = undefined;\n",
"\t\t\t\t\treturn this.fileDialogService.showSaveDialog(this.options).then(result => {\n",
"\t\t\t\t\t\tdoResolve(this, result);\n",
"\t\t\t\t\t});\n",
"\t\t\t\t} else {\n",
"\t\t\t\t\treturn this.fileDialogService.showOpenDialog(this.options).then(result => {\n"
],
"labels": [
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/services/dialogs/browser/remoteFileDialog.ts",
"type": "replace",
"edit_start_line_idx": 259
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as nls from 'vs/nls';
import { IJSONSchema } from 'vs/base/common/jsonSchema';
import { Schemas } from 'vs/workbench/contrib/tasks/common/problemMatcher';
const schema: IJSONSchema = {
definitions: {
showOutputType: {
type: 'string',
enum: ['always', 'silent', 'never']
},
options: {
type: 'object',
description: nls.localize('JsonSchema.options', 'Additional command options'),
properties: {
cwd: {
type: 'string',
description: nls.localize('JsonSchema.options.cwd', 'The current working directory of the executed program or script. If omitted Code\'s current workspace root is used.')
},
env: {
type: 'object',
additionalProperties: {
type: 'string'
},
description: nls.localize('JsonSchema.options.env', 'The environment of the executed program or shell. If omitted the parent process\' environment is used.')
}
},
additionalProperties: {
type: ['string', 'array', 'object']
}
},
problemMatcherType: {
oneOf: [
{
type: 'string',
},
Schemas.LegacyProblemMatcher,
{
type: 'array',
items: {
anyOf: [
Schemas.LegacyProblemMatcher,
{
type: 'string',
}
]
}
}
]
},
shellConfiguration: {
type: 'object',
additionalProperties: false,
description: nls.localize('JsonSchema.shellConfiguration', 'Configures the shell to be used.'),
properties: {
executable: {
type: 'string',
description: nls.localize('JsonSchema.shell.executable', 'The shell to be used.')
},
args: {
type: 'array',
description: nls.localize('JsonSchema.shell.args', 'The shell arguments.'),
items: {
type: 'string'
}
}
}
},
commandConfiguration: {
type: 'object',
additionalProperties: false,
properties: {
command: {
type: 'string',
description: nls.localize('JsonSchema.command', 'The command to be executed. Can be an external program or a shell command.')
},
args: {
type: 'array',
description: nls.localize('JsonSchema.tasks.args', 'Arguments passed to the command when this task is invoked.'),
items: {
type: 'string'
}
},
options: {
$ref: '#/definitions/options'
}
}
},
taskDescription: {
type: 'object',
required: ['taskName'],
additionalProperties: false,
properties: {
taskName: {
type: 'string',
description: nls.localize('JsonSchema.tasks.taskName', "The task's name")
},
command: {
type: 'string',
description: nls.localize('JsonSchema.command', 'The command to be executed. Can be an external program or a shell command.')
},
args: {
type: 'array',
description: nls.localize('JsonSchema.tasks.args', 'Arguments passed to the command when this task is invoked.'),
items: {
type: 'string'
}
},
options: {
$ref: '#/definitions/options'
},
windows: {
$ref: '#/definitions/commandConfiguration',
description: nls.localize('JsonSchema.tasks.windows', 'Windows specific command configuration')
},
osx: {
$ref: '#/definitions/commandConfiguration',
description: nls.localize('JsonSchema.tasks.mac', 'Mac specific command configuration')
},
linux: {
$ref: '#/definitions/commandConfiguration',
description: nls.localize('JsonSchema.tasks.linux', 'Linux specific command configuration')
},
suppressTaskName: {
type: 'boolean',
description: nls.localize('JsonSchema.tasks.suppressTaskName', 'Controls whether the task name is added as an argument to the command. If omitted the globally defined value is used.'),
default: true
},
showOutput: {
$ref: '#/definitions/showOutputType',
description: nls.localize('JsonSchema.tasks.showOutput', 'Controls whether the output of the running task is shown or not. If omitted the globally defined value is used.')
},
echoCommand: {
type: 'boolean',
description: nls.localize('JsonSchema.echoCommand', 'Controls whether the executed command is echoed to the output. Default is false.'),
default: true
},
isWatching: {
type: 'boolean',
deprecationMessage: nls.localize('JsonSchema.tasks.watching.deprecation', 'Deprecated. Use isBackground instead.'),
description: nls.localize('JsonSchema.tasks.watching', 'Whether the executed task is kept alive and is watching the file system.'),
default: true
},
isBackground: {
type: 'boolean',
description: nls.localize('JsonSchema.tasks.background', 'Whether the executed task is kept alive and is running in the background.'),
default: true
},
promptOnClose: {
type: 'boolean',
description: nls.localize('JsonSchema.tasks.promptOnClose', 'Whether the user is prompted when VS Code closes with a running task.'),
default: false
},
isBuildCommand: {
type: 'boolean',
description: nls.localize('JsonSchema.tasks.build', 'Maps this task to Code\'s default build command.'),
default: true
},
isTestCommand: {
type: 'boolean',
description: nls.localize('JsonSchema.tasks.test', 'Maps this task to Code\'s default test command.'),
default: true
},
problemMatcher: {
$ref: '#/definitions/problemMatcherType',
description: nls.localize('JsonSchema.tasks.matchers', 'The problem matcher(s) to use. Can either be a string or a problem matcher definition or an array of strings and problem matchers.')
}
}
},
taskRunnerConfiguration: {
type: 'object',
required: [],
properties: {
command: {
type: 'string',
description: nls.localize('JsonSchema.command', 'The command to be executed. Can be an external program or a shell command.')
},
args: {
type: 'array',
description: nls.localize('JsonSchema.args', 'Additional arguments passed to the command.'),
items: {
type: 'string'
}
},
options: {
$ref: '#/definitions/options'
},
showOutput: {
$ref: '#/definitions/showOutputType',
description: nls.localize('JsonSchema.showOutput', 'Controls whether the output of the running task is shown or not. If omitted \'always\' is used.')
},
isWatching: {
type: 'boolean',
deprecationMessage: nls.localize('JsonSchema.watching.deprecation', 'Deprecated. Use isBackground instead.'),
description: nls.localize('JsonSchema.watching', 'Whether the executed task is kept alive and is watching the file system.'),
default: true
},
isBackground: {
type: 'boolean',
description: nls.localize('JsonSchema.background', 'Whether the executed task is kept alive and is running in the background.'),
default: true
},
promptOnClose: {
type: 'boolean',
description: nls.localize('JsonSchema.promptOnClose', 'Whether the user is prompted when VS Code closes with a running background task.'),
default: false
},
echoCommand: {
type: 'boolean',
description: nls.localize('JsonSchema.echoCommand', 'Controls whether the executed command is echoed to the output. Default is false.'),
default: true
},
suppressTaskName: {
type: 'boolean',
description: nls.localize('JsonSchema.suppressTaskName', 'Controls whether the task name is added as an argument to the command. Default is false.'),
default: true
},
taskSelector: {
type: 'string',
description: nls.localize('JsonSchema.taskSelector', 'Prefix to indicate that an argument is task.')
},
problemMatcher: {
$ref: '#/definitions/problemMatcherType',
description: nls.localize('JsonSchema.matchers', 'The problem matcher(s) to use. Can either be a string or a problem matcher definition or an array of strings and problem matchers.')
},
tasks: {
type: 'array',
description: nls.localize('JsonSchema.tasks', 'The task configurations. Usually these are enrichments of task already defined in the external task runner.'),
items: {
type: 'object',
$ref: '#/definitions/taskDescription'
}
}
}
}
}
};
export default schema; | src/vs/workbench/contrib/tasks/common/jsonSchemaCommon.ts | 0 | https://github.com/microsoft/vscode/commit/985de26b3446636f86e2bb2b14dbeb9ec1e33207 | [
0.000176133107743226,
0.00017205292533617467,
0.00016364778275601566,
0.00017209502402693033,
0.000002339931597816758
] |
{
"id": 9,
"code_window": [
"\t\treturn result;\n",
"\t}\n",
"\n",
"\tprotected async promptForPath(resource: URI, defaultUri: URI): Promise<URI | undefined> {\n",
"\n",
"\t\t// Help user to find a name for the file by opening it first\n",
"\t\tawait this.editorService.openEditor({ resource, options: { revealIfOpened: true, preserveFocus: true, } });\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tprotected async promptForPath(resource: URI, defaultUri: URI, availableFileSystems?: string[]): Promise<URI | undefined> {\n"
],
"file_path": "src/vs/workbench/services/textfile/common/textFileService.ts",
"type": "replace",
"edit_start_line_idx": 650
} | /*---------------------------------------------------------------------------------------------
* 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 resources from 'vs/base/common/resources';
import * as objects from 'vs/base/common/objects';
import { IFileService, IFileStat, FileKind } from 'vs/platform/files/common/files';
import { IQuickInputService, IQuickPickItem, IQuickPick } from 'vs/platform/quickinput/common/quickInput';
import { URI } from 'vs/base/common/uri';
import { isWindows, OperatingSystem } from 'vs/base/common/platform';
import { ISaveDialogOptions, IOpenDialogOptions, IFileDialogService } from 'vs/platform/dialogs/common/dialogs';
import { REMOTE_HOST_SCHEME } from 'vs/platform/remote/common/remoteHosts';
import { ILabelService } from 'vs/platform/label/common/label';
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
import { INotificationService } from 'vs/platform/notification/common/notification';
import { IModelService } from 'vs/editor/common/services/modelService';
import { IModeService } from 'vs/editor/common/services/modeService';
import { getIconClasses } from 'vs/editor/common/services/getIconClasses';
import { Schemas } from 'vs/base/common/network';
import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService';
import { IRemoteAgentService } from 'vs/workbench/services/remote/common/remoteAgentService';
import { IContextKeyService, IContextKey } from 'vs/platform/contextkey/common/contextkey';
import { equalsIgnoreCase, format, startsWithIgnoreCase } from 'vs/base/common/strings';
import { OpenLocalFileAction, OpenLocalFileFolderAction, OpenLocalFolderAction, SaveLocalFileAction } from 'vs/workbench/browser/actions/workspaceActions';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { IRemoteAgentEnvironment } from 'vs/platform/remote/common/remoteAgentEnvironment';
import { isValidBasename } from 'vs/base/common/extpath';
import { RemoteFileDialogContext } from 'vs/workbench/browser/contextkeys';
import { Emitter } from 'vs/base/common/event';
import { IDisposable, dispose } from 'vs/base/common/lifecycle';
interface FileQuickPickItem extends IQuickPickItem {
uri: URI;
isFolder: boolean;
}
enum UpdateResult {
Updated,
Updating,
NotUpdated,
InvalidPath
}
export class RemoteFileDialog {
private options: IOpenDialogOptions;
private currentFolder: URI;
private filePickBox: IQuickPick<FileQuickPickItem>;
private hidden: boolean;
private allowFileSelection: boolean;
private allowFolderSelection: boolean;
private remoteAuthority: string | undefined;
private requiresTrailing: boolean;
private trailing: string | undefined;
private scheme: string = REMOTE_HOST_SCHEME;
private contextKey: IContextKey<boolean>;
private userEnteredPathSegment: string;
private autoCompletePathSegment: string;
private activeItem: FileQuickPickItem;
private userHome: URI;
private badPath: string | undefined;
private remoteAgentEnvironment: IRemoteAgentEnvironment | null;
private separator: string;
private onBusyChangeEmitter = new Emitter<boolean>();
protected disposables: IDisposable[] = [
this.onBusyChangeEmitter
];
constructor(
@IFileService private readonly fileService: IFileService,
@IQuickInputService private readonly quickInputService: IQuickInputService,
@ILabelService private readonly labelService: ILabelService,
@IWorkspaceContextService private readonly workspaceContextService: IWorkspaceContextService,
@INotificationService private readonly notificationService: INotificationService,
@IFileDialogService private readonly fileDialogService: IFileDialogService,
@IModelService private readonly modelService: IModelService,
@IModeService private readonly modeService: IModeService,
@IWorkbenchEnvironmentService private readonly environmentService: IWorkbenchEnvironmentService,
@IRemoteAgentService private readonly remoteAgentService: IRemoteAgentService,
@IKeybindingService private readonly keybindingService: IKeybindingService,
@IContextKeyService contextKeyService: IContextKeyService,
) {
this.remoteAuthority = this.environmentService.configuration.remoteAuthority;
this.contextKey = RemoteFileDialogContext.bindTo(contextKeyService);
}
set busy(busy: boolean) {
if (this.filePickBox.busy !== busy) {
this.filePickBox.busy = busy;
this.onBusyChangeEmitter.fire(busy);
}
}
get busy(): boolean {
return this.filePickBox.busy;
}
public async showOpenDialog(options: IOpenDialogOptions = {}): Promise<URI | undefined> {
this.scheme = this.getScheme(options.defaultUri, options.availableFileSystems);
this.userHome = await this.getUserHome();
const newOptions = await this.getOptions(options);
if (!newOptions) {
return Promise.resolve(undefined);
}
this.options = newOptions;
return this.pickResource();
}
public async showSaveDialog(options: ISaveDialogOptions): Promise<URI | undefined> {
this.scheme = this.getScheme(options.defaultUri, options.availableFileSystems);
this.userHome = await this.getUserHome();
this.requiresTrailing = true;
const newOptions = await this.getOptions(options, true);
if (!newOptions) {
return Promise.resolve(undefined);
}
this.options = newOptions;
this.options.canSelectFolders = true;
this.options.canSelectFiles = true;
return new Promise<URI | undefined>((resolve) => {
this.pickResource(true).then(folderUri => {
resolve(folderUri);
});
});
}
private getOptions(options: ISaveDialogOptions | IOpenDialogOptions, isSave: boolean = false): IOpenDialogOptions | undefined {
let defaultUri = options.defaultUri;
const filename = (defaultUri && isSave && (resources.dirname(defaultUri).path === '/')) ? resources.basename(defaultUri) : undefined;
if (!defaultUri || filename) {
defaultUri = this.userHome;
if (filename) {
defaultUri = resources.joinPath(defaultUri, filename);
}
}
if ((this.scheme !== Schemas.file) && !this.fileService.canHandleResource(defaultUri)) {
this.notificationService.info(nls.localize('remoteFileDialog.notConnectedToRemote', 'File system provider for {0} is not available.', defaultUri.toString()));
return undefined;
}
const newOptions: IOpenDialogOptions = objects.deepClone(options);
newOptions.defaultUri = defaultUri;
return newOptions;
}
private remoteUriFrom(path: string): URI {
path = path.replace(/\\/g, '/');
return resources.toLocalResource(URI.from({ scheme: this.scheme, path }), this.scheme === Schemas.file ? undefined : this.remoteAuthority);
}
private getScheme(defaultUri: URI | undefined, available: string[] | undefined): string {
return defaultUri ? defaultUri.scheme : (available ? available[0] : Schemas.file);
}
private async getRemoteAgentEnvironment(): Promise<IRemoteAgentEnvironment | null> {
if (this.remoteAgentEnvironment === undefined) {
this.remoteAgentEnvironment = await this.remoteAgentService.getEnvironment();
}
return this.remoteAgentEnvironment;
}
private async getUserHome(): Promise<URI> {
if (this.scheme !== Schemas.file) {
const env = await this.getRemoteAgentEnvironment();
if (env) {
return env.userHome;
}
}
return URI.from({ scheme: this.scheme, path: this.environmentService.userHome });
}
private async pickResource(isSave: boolean = false): Promise<URI | undefined> {
this.allowFolderSelection = !!this.options.canSelectFolders;
this.allowFileSelection = !!this.options.canSelectFiles;
this.separator = this.labelService.getSeparator(this.scheme, this.remoteAuthority);
this.hidden = false;
let homedir: URI = this.options.defaultUri ? this.options.defaultUri : this.workspaceContextService.getWorkspace().folders[0].uri;
let stat: IFileStat | undefined;
let ext: string = resources.extname(homedir);
if (this.options.defaultUri) {
try {
stat = await this.fileService.resolve(this.options.defaultUri);
} catch (e) {
// The file or folder doesn't exist
}
if (!stat || !stat.isDirectory) {
homedir = resources.dirname(this.options.defaultUri);
this.trailing = resources.basename(this.options.defaultUri);
}
// append extension
if (isSave && !ext && this.options.filters) {
for (let i = 0; i < this.options.filters.length; i++) {
if (this.options.filters[i].extensions[0] !== '*') {
ext = '.' + this.options.filters[i].extensions[0];
this.trailing = this.trailing ? this.trailing + ext : ext;
break;
}
}
}
}
return new Promise<URI | undefined>(async (resolve) => {
this.filePickBox = this.quickInputService.createQuickPick<FileQuickPickItem>();
this.busy = true;
this.filePickBox.matchOnLabel = false;
this.filePickBox.autoFocusOnList = false;
this.filePickBox.ignoreFocusOut = true;
this.filePickBox.ok = true;
if (this.options && this.options.availableFileSystems && (this.options.availableFileSystems.length > 1)) {
this.filePickBox.customButton = true;
this.filePickBox.customLabel = nls.localize('remoteFileDialog.local', 'Show Local');
let action;
if (isSave) {
action = SaveLocalFileAction;
} else {
action = this.allowFileSelection ? (this.allowFolderSelection ? OpenLocalFileFolderAction : OpenLocalFileAction) : OpenLocalFolderAction;
}
const keybinding = this.keybindingService.lookupKeybinding(action.ID);
if (keybinding) {
const label = keybinding.getLabel();
if (label) {
this.filePickBox.customHover = format('{0} ({1})', action.LABEL, label);
}
}
}
let isResolving: number = 0;
let isAcceptHandled = false;
this.currentFolder = homedir;
this.userEnteredPathSegment = '';
this.autoCompletePathSegment = '';
this.filePickBox.title = this.options.title;
this.filePickBox.value = this.pathFromUri(this.currentFolder, true);
this.filePickBox.valueSelection = [this.filePickBox.value.length, this.filePickBox.value.length];
this.filePickBox.items = [];
function doResolve(dialog: RemoteFileDialog, uri: URI | undefined) {
resolve(uri);
dialog.contextKey.set(false);
dialog.filePickBox.dispose();
dispose(dialog.disposables);
}
this.filePickBox.onDidCustom(() => {
if (isAcceptHandled || this.busy) {
return;
}
isAcceptHandled = true;
isResolving++;
if (this.options.availableFileSystems && (this.options.availableFileSystems.length > 1)) {
this.options.availableFileSystems.shift();
}
this.options.defaultUri = undefined;
this.filePickBox.hide();
if (isSave) {
// Remove defaultUri and filters to get a consistant experience with the keybinding.
this.options.defaultUri = undefined;
this.options.filters = undefined;
return this.fileDialogService.showSaveDialog(this.options).then(result => {
doResolve(this, result);
});
} else {
return this.fileDialogService.showOpenDialog(this.options).then(result => {
doResolve(this, result ? result[0] : undefined);
});
}
});
function handleAccept(dialog: RemoteFileDialog) {
if (dialog.busy) {
// Save the accept until the file picker is not busy.
dialog.onBusyChangeEmitter.event((busy: boolean) => {
if (!busy) {
handleAccept(dialog);
}
});
return;
} else if (isAcceptHandled) {
return;
}
isAcceptHandled = true;
isResolving++;
dialog.onDidAccept().then(resolveValue => {
if (resolveValue) {
dialog.filePickBox.hide();
doResolve(dialog, resolveValue);
} else if (dialog.hidden) {
doResolve(dialog, undefined);
} else {
isResolving--;
isAcceptHandled = false;
}
});
}
this.filePickBox.onDidAccept(_ => {
handleAccept(this);
});
this.filePickBox.onDidChangeActive(i => {
isAcceptHandled = false;
// update input box to match the first selected item
if ((i.length === 1) && this.isChangeFromUser()) {
this.filePickBox.validationMessage = undefined;
this.setAutoComplete(this.constructFullUserPath(), this.userEnteredPathSegment, i[0], true);
}
});
this.filePickBox.onDidChangeValue(async value => {
try {
// onDidChangeValue can also be triggered by the auto complete, so if it looks like the auto complete, don't do anything
if (this.isChangeFromUser()) {
// If the user has just entered more bad path, don't change anything
if (!equalsIgnoreCase(value, this.constructFullUserPath()) && !this.isBadSubpath(value)) {
this.filePickBox.validationMessage = undefined;
const filePickBoxUri = this.filePickBoxValue();
let updated: UpdateResult = UpdateResult.NotUpdated;
if (!resources.isEqual(this.currentFolder, filePickBoxUri, true)) {
updated = await this.tryUpdateItems(value, filePickBoxUri);
}
if (updated === UpdateResult.NotUpdated) {
this.setActiveItems(value);
}
} else {
this.filePickBox.activeItems = [];
}
}
} catch {
// Since any text can be entered in the input box, there is potential for error causing input. If this happens, do nothing.
}
});
this.filePickBox.onDidHide(() => {
this.hidden = true;
if (isResolving === 0) {
doResolve(this, undefined);
}
});
this.filePickBox.show();
this.contextKey.set(true);
await this.updateItems(homedir, true, this.trailing);
if (this.trailing) {
this.filePickBox.valueSelection = [this.filePickBox.value.length - this.trailing.length, this.filePickBox.value.length - ext.length];
} else {
this.filePickBox.valueSelection = [this.filePickBox.value.length, this.filePickBox.value.length];
}
this.busy = false;
});
}
private isBadSubpath(value: string) {
return this.badPath && (value.length > this.badPath.length) && equalsIgnoreCase(value.substring(0, this.badPath.length), this.badPath);
}
private isChangeFromUser(): boolean {
if (equalsIgnoreCase(this.filePickBox.value, this.pathAppend(this.currentFolder, this.userEnteredPathSegment + this.autoCompletePathSegment))
&& (this.activeItem === (this.filePickBox.activeItems ? this.filePickBox.activeItems[0] : undefined))) {
return false;
}
return true;
}
private constructFullUserPath(): string {
return this.pathAppend(this.currentFolder, this.userEnteredPathSegment);
}
private filePickBoxValue(): URI {
// The file pick box can't render everything, so we use the current folder to create the uri so that it is an existing path.
const directUri = this.remoteUriFrom(this.filePickBox.value);
const currentPath = this.pathFromUri(this.currentFolder);
if (equalsIgnoreCase(this.filePickBox.value, currentPath)) {
return this.currentFolder;
}
const currentDisplayUri = this.remoteUriFrom(currentPath);
const relativePath = resources.relativePath(currentDisplayUri, directUri);
const isSameRoot = (this.filePickBox.value.length > 1 && currentPath.length > 1) ? equalsIgnoreCase(this.filePickBox.value.substr(0, 2), currentPath.substr(0, 2)) : false;
if (relativePath && isSameRoot) {
const path = resources.joinPath(this.currentFolder, relativePath);
return resources.hasTrailingPathSeparator(directUri) ? resources.addTrailingPathSeparator(path) : path;
} else {
return directUri;
}
}
private async onDidAccept(): Promise<URI | undefined> {
this.busy = true;
if (this.filePickBox.activeItems.length === 1) {
const item = this.filePickBox.selectedItems[0];
if (item.isFolder) {
if (this.trailing) {
await this.updateItems(item.uri, true, this.trailing);
} else {
// When possible, cause the update to happen by modifying the input box.
// This allows all input box updates to happen first, and uses the same code path as the user typing.
const newPath = this.pathFromUri(item.uri);
if (startsWithIgnoreCase(newPath, this.filePickBox.value) && (equalsIgnoreCase(item.label, resources.basename(item.uri)))) {
this.filePickBox.valueSelection = [this.pathFromUri(this.currentFolder).length, this.filePickBox.value.length];
this.insertText(newPath, item.label);
} else if ((item.label === '..') && startsWithIgnoreCase(this.filePickBox.value, newPath)) {
this.filePickBox.valueSelection = [newPath.length, this.filePickBox.value.length];
this.insertText(newPath, '');
} else {
await this.updateItems(item.uri, true);
}
}
this.filePickBox.busy = false;
return;
}
} else {
// If the items have updated, don't try to resolve
if ((await this.tryUpdateItems(this.filePickBox.value, this.filePickBoxValue())) !== UpdateResult.NotUpdated) {
this.filePickBox.busy = false;
return;
}
}
let resolveValue: URI | undefined;
// Find resolve value
if (this.filePickBox.activeItems.length === 0) {
resolveValue = this.filePickBoxValue();
} else if (this.filePickBox.activeItems.length === 1) {
resolveValue = this.filePickBox.selectedItems[0].uri;
}
if (resolveValue) {
resolveValue = this.addPostfix(resolveValue);
}
if (await this.validate(resolveValue)) {
this.busy = false;
return resolveValue;
}
this.busy = false;
return undefined;
}
private async tryUpdateItems(value: string, valueUri: URI): Promise<UpdateResult> {
if ((value.length > 0) && ((value[value.length - 1] === '~') || (value[0] === '~'))) {
let newDir = this.userHome;
if ((value[0] === '~') && (value.length > 1)) {
newDir = resources.joinPath(newDir, value.substring(1));
}
await this.updateItems(newDir, true);
return UpdateResult.Updated;
} else if (!resources.isEqual(this.currentFolder, valueUri, true) && (this.endsWithSlash(value) || (!resources.isEqual(this.currentFolder, resources.dirname(valueUri), true) && resources.isEqualOrParent(this.currentFolder, resources.dirname(valueUri), true)))) {
let stat: IFileStat | undefined;
try {
stat = await this.fileService.resolve(valueUri);
} catch (e) {
// do nothing
}
if (stat && stat.isDirectory && (resources.basename(valueUri) !== '.') && this.endsWithSlash(value)) {
await this.updateItems(valueUri);
return UpdateResult.Updated;
} else if (this.endsWithSlash(value)) {
// The input box contains a path that doesn't exist on the system.
this.filePickBox.validationMessage = nls.localize('remoteFileDialog.badPath', 'The path does not exist.');
// Save this bad path. It can take too long to to a stat on every user entered character, but once a user enters a bad path they are likely
// to keep typing more bad path. We can compare against this bad path and see if the user entered path starts with it.
this.badPath = value;
return UpdateResult.InvalidPath;
} else {
const inputUriDirname = resources.dirname(valueUri);
if (!resources.isEqual(resources.removeTrailingPathSeparator(this.currentFolder), inputUriDirname, true)) {
let statWithoutTrailing: IFileStat | undefined;
try {
statWithoutTrailing = await this.fileService.resolve(inputUriDirname);
} catch (e) {
// do nothing
}
if (statWithoutTrailing && statWithoutTrailing.isDirectory && (resources.basename(valueUri) !== '.')) {
await this.updateItems(inputUriDirname, false, resources.basename(valueUri));
this.badPath = undefined;
return UpdateResult.Updated;
}
}
}
}
this.badPath = undefined;
return UpdateResult.NotUpdated;
}
private setActiveItems(value: string) {
const inputBasename = resources.basename(this.remoteUriFrom(value));
// Make sure that the folder whose children we are currently viewing matches the path in the input
const userPath = this.constructFullUserPath();
if (equalsIgnoreCase(userPath, value.substring(0, userPath.length))) {
let hasMatch = false;
for (let i = 0; i < this.filePickBox.items.length; i++) {
const item = <FileQuickPickItem>this.filePickBox.items[i];
if (this.setAutoComplete(value, inputBasename, item)) {
hasMatch = true;
break;
}
}
if (!hasMatch) {
this.userEnteredPathSegment = inputBasename;
this.autoCompletePathSegment = '';
this.filePickBox.activeItems = [];
}
} else {
if (!equalsIgnoreCase(inputBasename, resources.basename(this.currentFolder))) {
this.userEnteredPathSegment = inputBasename;
} else {
this.userEnteredPathSegment = '';
}
this.autoCompletePathSegment = '';
}
}
private setAutoComplete(startingValue: string, startingBasename: string, quickPickItem: FileQuickPickItem, force: boolean = false): boolean {
if (this.busy) {
// We're in the middle of something else. Doing an auto complete now can result jumbled or incorrect autocompletes.
this.userEnteredPathSegment = startingBasename;
this.autoCompletePathSegment = '';
return false;
}
const itemBasename = this.trimTrailingSlash(quickPickItem.label);
// Either force the autocomplete, or the old value should be one smaller than the new value and match the new value.
if (itemBasename === '..') {
// Don't match on the up directory item ever.
this.userEnteredPathSegment = startingValue;
this.autoCompletePathSegment = '';
this.activeItem = quickPickItem;
if (force) {
// clear any selected text
this.insertText(this.userEnteredPathSegment, '');
}
return false;
} else if (!force && (itemBasename.length >= startingBasename.length) && equalsIgnoreCase(itemBasename.substr(0, startingBasename.length), startingBasename)) {
this.userEnteredPathSegment = startingBasename;
this.activeItem = quickPickItem;
// Changing the active items will trigger the onDidActiveItemsChanged. Clear the autocomplete first, then set it after.
this.autoCompletePathSegment = '';
this.filePickBox.activeItems = [quickPickItem];
return true;
} else if (force && (!equalsIgnoreCase(quickPickItem.label, (this.userEnteredPathSegment + this.autoCompletePathSegment)))) {
this.userEnteredPathSegment = '';
this.autoCompletePathSegment = this.trimTrailingSlash(itemBasename);
this.activeItem = quickPickItem;
this.filePickBox.valueSelection = [this.pathFromUri(this.currentFolder, true).length, this.filePickBox.value.length];
// use insert text to preserve undo buffer
this.insertText(this.pathAppend(this.currentFolder, this.autoCompletePathSegment), this.autoCompletePathSegment);
this.filePickBox.valueSelection = [this.filePickBox.value.length - this.autoCompletePathSegment.length, this.filePickBox.value.length];
return true;
} else {
this.userEnteredPathSegment = startingBasename;
this.autoCompletePathSegment = '';
return false;
}
}
private insertText(wholeValue: string, insertText: string) {
if (this.filePickBox.inputHasFocus()) {
document.execCommand('insertText', false, insertText);
} else {
this.filePickBox.value = wholeValue;
}
}
private addPostfix(uri: URI): URI {
let result = uri;
if (this.requiresTrailing && this.options.filters && this.options.filters.length > 0) {
// Make sure that the suffix is added. If the user deleted it, we automatically add it here
let hasExt: boolean = false;
const currentExt = resources.extname(uri).substr(1);
for (let i = 0; i < this.options.filters.length; i++) {
for (let j = 0; j < this.options.filters[i].extensions.length; j++) {
if ((this.options.filters[i].extensions[j] === '*') || (this.options.filters[i].extensions[j] === currentExt)) {
hasExt = true;
break;
}
}
if (hasExt) {
break;
}
}
if (!hasExt) {
result = resources.joinPath(resources.dirname(uri), resources.basename(uri) + '.' + this.options.filters[0].extensions[0]);
}
}
return result;
}
private trimTrailingSlash(path: string): string {
return ((path.length > 1) && this.endsWithSlash(path)) ? path.substr(0, path.length - 1) : path;
}
private yesNoPrompt(uri: URI, message: string): Promise<boolean> {
interface YesNoItem extends IQuickPickItem {
value: boolean;
}
const prompt = this.quickInputService.createQuickPick<YesNoItem>();
prompt.title = message;
prompt.ignoreFocusOut = true;
prompt.ok = true;
prompt.customButton = true;
prompt.customLabel = nls.localize('remoteFileDialog.cancel', 'Cancel');
prompt.value = this.pathFromUri(uri);
let isResolving = false;
return new Promise<boolean>(resolve => {
prompt.onDidAccept(() => {
isResolving = true;
prompt.hide();
resolve(true);
});
prompt.onDidHide(() => {
if (!isResolving) {
resolve(false);
}
this.filePickBox.show();
this.hidden = false;
this.filePickBox.items = this.filePickBox.items;
prompt.dispose();
});
prompt.onDidChangeValue(() => {
prompt.hide();
});
prompt.onDidCustom(() => {
prompt.hide();
});
prompt.show();
});
}
private async validate(uri: URI | undefined): Promise<boolean> {
if (uri === undefined) {
this.filePickBox.validationMessage = nls.localize('remoteFileDialog.invalidPath', 'Please enter a valid path.');
return Promise.resolve(false);
}
let stat: IFileStat | undefined;
let statDirname: IFileStat | undefined;
try {
statDirname = await this.fileService.resolve(resources.dirname(uri));
stat = await this.fileService.resolve(uri);
} catch (e) {
// do nothing
}
if (this.requiresTrailing) { // save
if (stat && stat.isDirectory) {
// Can't do this
this.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateFolder', 'The folder already exists. Please use a new file name.');
return Promise.resolve(false);
} else if (stat) {
// Replacing a file.
// Show a yes/no prompt
const message = nls.localize('remoteFileDialog.validateExisting', '{0} already exists. Are you sure you want to overwrite it?', resources.basename(uri));
return this.yesNoPrompt(uri, message);
} else if (!(isValidBasename(resources.basename(uri), await this.isWindowsOS()))) {
// Filename not allowed
this.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateBadFilename', 'Please enter a valid file name.');
return Promise.resolve(false);
} else if (!statDirname || !statDirname.isDirectory) {
// Folder to save in doesn't exist
this.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateNonexistentDir', 'Please enter a path that exists.');
return Promise.resolve(false);
}
} else { // open
if (!stat) {
// File or folder doesn't exist
this.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateNonexistentDir', 'Please enter a path that exists.');
return Promise.resolve(false);
} else if (stat.isDirectory && !this.allowFolderSelection) {
// Folder selected when folder selection not permitted
this.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateFileOnly', 'Please select a file.');
return Promise.resolve(false);
} else if (!stat.isDirectory && !this.allowFileSelection) {
// File selected when file selection not permitted
this.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateFolderOnly', 'Please select a folder.');
return Promise.resolve(false);
}
}
return Promise.resolve(true);
}
private async updateItems(newFolder: URI, force: boolean = false, trailing?: string) {
this.busy = true;
this.userEnteredPathSegment = trailing ? trailing : '';
this.autoCompletePathSegment = '';
const newValue = trailing ? this.pathFromUri(resources.joinPath(newFolder, trailing)) : this.pathFromUri(newFolder, true);
this.currentFolder = resources.addTrailingPathSeparator(newFolder, this.separator);
return this.createItems(this.currentFolder).then(items => {
this.filePickBox.items = items;
if (this.allowFolderSelection) {
this.filePickBox.activeItems = [];
}
// the user might have continued typing while we were updating. Only update the input box if it doesn't match the directory.
if (!equalsIgnoreCase(this.filePickBox.value, newValue) && force) {
this.filePickBox.valueSelection = [0, this.filePickBox.value.length];
this.insertText(newValue, newValue);
}
if (force && trailing) {
// Keep the cursor position in front of the save as name.
this.filePickBox.valueSelection = [this.filePickBox.value.length - trailing.length, this.filePickBox.value.length - trailing.length];
} else if (!trailing) {
// If there is trailing, we don't move the cursor. If there is no trailing, cursor goes at the end.
this.filePickBox.valueSelection = [this.filePickBox.value.length, this.filePickBox.value.length];
}
this.busy = false;
});
}
private pathFromUri(uri: URI, endWithSeparator: boolean = false): string {
let result: string = uri.fsPath.replace(/\n/g, '');
if (this.separator === '/') {
result = result.replace(/\\/g, this.separator);
} else {
result = result.replace(/\//g, this.separator);
}
if (endWithSeparator && !this.endsWithSlash(result)) {
result = result + this.separator;
}
return result;
}
private pathAppend(uri: URI, additional: string): string {
if ((additional === '..') || (additional === '.')) {
const basePath = this.pathFromUri(uri);
return basePath + (this.endsWithSlash(basePath) ? '' : this.separator) + additional;
} else {
return this.pathFromUri(resources.joinPath(uri, additional));
}
}
private async isWindowsOS(): Promise<boolean> {
let isWindowsOS = isWindows;
const env = await this.getRemoteAgentEnvironment();
if (env) {
isWindowsOS = env.os === OperatingSystem.Windows;
}
return isWindowsOS;
}
private endsWithSlash(s: string) {
return /[\/\\]$/.test(s);
}
private basenameWithTrailingSlash(fullPath: URI): string {
const child = this.pathFromUri(fullPath, true);
const parent = this.pathFromUri(resources.dirname(fullPath), true);
return child.substring(parent.length);
}
private createBackItem(currFolder: URI): FileQuickPickItem | null {
const parentFolder = resources.dirname(currFolder)!;
if (!resources.isEqual(currFolder, parentFolder, true)) {
return { label: '..', uri: resources.addTrailingPathSeparator(parentFolder, this.separator), isFolder: true };
}
return null;
}
private async createItems(currentFolder: URI): Promise<FileQuickPickItem[]> {
const result: FileQuickPickItem[] = [];
const backDir = this.createBackItem(currentFolder);
try {
const folder = await this.fileService.resolve(currentFolder);
const fileNames = folder.children ? folder.children.map(child => child.name) : [];
const items = await Promise.all(fileNames.map(fileName => this.createItem(fileName, currentFolder)));
for (let item of items) {
if (item) {
result.push(item);
}
}
} catch (e) {
// ignore
console.log(e);
}
const sorted = result.sort((i1, i2) => {
if (i1.isFolder !== i2.isFolder) {
return i1.isFolder ? -1 : 1;
}
const trimmed1 = this.endsWithSlash(i1.label) ? i1.label.substr(0, i1.label.length - 1) : i1.label;
const trimmed2 = this.endsWithSlash(i2.label) ? i2.label.substr(0, i2.label.length - 1) : i2.label;
return trimmed1.localeCompare(trimmed2);
});
if (backDir) {
sorted.unshift(backDir);
}
return sorted;
}
private filterFile(file: URI): boolean {
if (this.options.filters) {
const ext = resources.extname(file);
for (let i = 0; i < this.options.filters.length; i++) {
for (let j = 0; j < this.options.filters[i].extensions.length; j++) {
if (ext === ('.' + this.options.filters[i].extensions[j])) {
return true;
}
}
}
return false;
}
return true;
}
private async createItem(filename: string, parent: URI): Promise<FileQuickPickItem | undefined> {
let fullPath = resources.joinPath(parent, filename);
try {
const stat = await this.fileService.resolve(fullPath);
if (stat.isDirectory) {
filename = this.basenameWithTrailingSlash(fullPath);
fullPath = resources.addTrailingPathSeparator(fullPath, this.separator);
return { label: filename, uri: fullPath, isFolder: true, iconClasses: getIconClasses(this.modelService, this.modeService, fullPath || undefined, FileKind.FOLDER) };
} else if (!stat.isDirectory && this.allowFileSelection && this.filterFile(fullPath)) {
return { label: filename, uri: fullPath, isFolder: false, iconClasses: getIconClasses(this.modelService, this.modeService, fullPath || undefined) };
}
return undefined;
} catch (e) {
return undefined;
}
}
} | src/vs/workbench/services/dialogs/browser/remoteFileDialog.ts | 1 | https://github.com/microsoft/vscode/commit/985de26b3446636f86e2bb2b14dbeb9ec1e33207 | [
0.9832756519317627,
0.012129767797887325,
0.0001618220703676343,
0.00017020881932694465,
0.10724584758281708
] |
{
"id": 9,
"code_window": [
"\t\treturn result;\n",
"\t}\n",
"\n",
"\tprotected async promptForPath(resource: URI, defaultUri: URI): Promise<URI | undefined> {\n",
"\n",
"\t\t// Help user to find a name for the file by opening it first\n",
"\t\tawait this.editorService.openEditor({ resource, options: { revealIfOpened: true, preserveFocus: true, } });\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tprotected async promptForPath(resource: URI, defaultUri: URI, availableFileSystems?: string[]): Promise<URI | undefined> {\n"
],
"file_path": "src/vs/workbench/services/textfile/common/textFileService.ts",
"type": "replace",
"edit_start_line_idx": 650
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { ITextModel, ITextBufferFactory, ITextSnapshot } from 'vs/editor/common/model';
import { EditorModel, IModeSupport } from 'vs/workbench/common/editor';
import { URI } from 'vs/base/common/uri';
import { ITextEditorModel, IResolvedTextEditorModel } from 'vs/editor/common/services/resolverService';
import { IModeService, ILanguageSelection } from 'vs/editor/common/services/modeService';
import { IModelService } from 'vs/editor/common/services/modelService';
import { MutableDisposable } from 'vs/base/common/lifecycle';
import { PLAINTEXT_MODE_ID } from 'vs/editor/common/modes/modesRegistry';
import { withUndefinedAsNull } from 'vs/base/common/types';
/**
* The base text editor model leverages the code editor model. This class is only intended to be subclassed and not instantiated.
*/
export abstract class BaseTextEditorModel extends EditorModel implements ITextEditorModel, IModeSupport {
protected textEditorModelHandle: URI | null;
private createdEditorModel: boolean;
private readonly modelDisposeListener = this._register(new MutableDisposable());
constructor(
@IModelService protected modelService: IModelService,
@IModeService protected modeService: IModeService,
textEditorModelHandle?: URI
) {
super();
if (textEditorModelHandle) {
this.handleExistingModel(textEditorModelHandle);
}
}
private handleExistingModel(textEditorModelHandle: URI): void {
// We need the resource to point to an existing model
const model = this.modelService.getModel(textEditorModelHandle);
if (!model) {
throw new Error(`Document with resource ${textEditorModelHandle.toString()} does not exist`);
}
this.textEditorModelHandle = textEditorModelHandle;
// Make sure we clean up when this model gets disposed
this.registerModelDisposeListener(model);
}
private registerModelDisposeListener(model: ITextModel): void {
this.modelDisposeListener.value = model.onWillDispose(() => {
this.textEditorModelHandle = null; // make sure we do not dispose code editor model again
this.dispose();
});
}
get textEditorModel(): ITextModel | null {
return this.textEditorModelHandle ? this.modelService.getModel(this.textEditorModelHandle) : null;
}
abstract isReadonly(): boolean;
setMode(mode: string): void {
if (!this.isResolved()) {
return;
}
if (!mode || mode === this.textEditorModel.getModeId()) {
return;
}
this.modelService.setMode(this.textEditorModel, this.modeService.create(mode));
}
/**
* Creates the text editor model with the provided value, optional preferred mode
* (can be comma separated for multiple values) and optional resource URL.
*/
protected createTextEditorModel(value: ITextBufferFactory, resource: URI | undefined, preferredMode?: string): EditorModel {
const firstLineText = this.getFirstLineText(value);
const languageSelection = this.getOrCreateMode(resource, this.modeService, preferredMode, firstLineText);
return this.doCreateTextEditorModel(value, languageSelection, resource);
}
private doCreateTextEditorModel(value: ITextBufferFactory, languageSelection: ILanguageSelection, resource: URI | undefined): EditorModel {
let model = resource && this.modelService.getModel(resource);
if (!model) {
model = this.modelService.createModel(value, languageSelection, resource);
this.createdEditorModel = true;
// Make sure we clean up when this model gets disposed
this.registerModelDisposeListener(model);
} else {
this.updateTextEditorModel(value, languageSelection.languageIdentifier.language);
}
this.textEditorModelHandle = model.uri;
return this;
}
protected getFirstLineText(value: ITextBufferFactory | ITextModel): string {
// text buffer factory
const textBufferFactory = value as ITextBufferFactory;
if (typeof textBufferFactory.getFirstLineText === 'function') {
return textBufferFactory.getFirstLineText(100);
}
// text model
const textSnapshot = value as ITextModel;
return textSnapshot.getLineContent(1).substr(0, 100);
}
/**
* Gets the mode for the given identifier. Subclasses can override to provide their own implementation of this lookup.
*
* @param firstLineText optional first line of the text buffer to set the mode on. This can be used to guess a mode from content.
*/
protected getOrCreateMode(resource: URI | undefined, modeService: IModeService, preferredMode: string | undefined, firstLineText?: string): ILanguageSelection {
// lookup mode via resource path if the provided mode is unspecific
if (!preferredMode || preferredMode === PLAINTEXT_MODE_ID) {
return modeService.createByFilepathOrFirstLine(withUndefinedAsNull(resource), firstLineText);
}
// otherwise take the preferred mode for granted
return modeService.create(preferredMode);
}
/**
* Updates the text editor model with the provided value. If the value is the same as the model has, this is a no-op.
*/
protected updateTextEditorModel(newValue: ITextBufferFactory, preferredMode?: string): void {
if (!this.isResolved()) {
return;
}
// contents
this.modelService.updateModel(this.textEditorModel, newValue);
// mode (only if specific and changed)
if (preferredMode && preferredMode !== PLAINTEXT_MODE_ID && this.textEditorModel.getModeId() !== preferredMode) {
this.modelService.setMode(this.textEditorModel, this.modeService.create(preferredMode));
}
}
createSnapshot(this: IResolvedTextEditorModel): ITextSnapshot;
createSnapshot(this: ITextEditorModel): ITextSnapshot | null;
createSnapshot(): ITextSnapshot | null {
if (!this.textEditorModel) {
return null;
}
return this.textEditorModel.createSnapshot(true /* preserve BOM */);
}
isResolved(): this is IResolvedTextEditorModel {
return !!this.textEditorModelHandle;
}
dispose(): void {
this.modelDisposeListener.dispose(); // dispose this first because it will trigger another dispose() otherwise
if (this.textEditorModelHandle && this.createdEditorModel) {
this.modelService.destroyModel(this.textEditorModelHandle);
}
this.textEditorModelHandle = null;
this.createdEditorModel = false;
super.dispose();
}
}
| src/vs/workbench/common/editor/textEditorModel.ts | 0 | https://github.com/microsoft/vscode/commit/985de26b3446636f86e2bb2b14dbeb9ec1e33207 | [
0.0003360788687132299,
0.00020560117263812572,
0.0001638181129237637,
0.00017420685617253184,
0.00005914804933127016
] |
{
"id": 9,
"code_window": [
"\t\treturn result;\n",
"\t}\n",
"\n",
"\tprotected async promptForPath(resource: URI, defaultUri: URI): Promise<URI | undefined> {\n",
"\n",
"\t\t// Help user to find a name for the file by opening it first\n",
"\t\tawait this.editorService.openEditor({ resource, options: { revealIfOpened: true, preserveFocus: true, } });\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tprotected async promptForPath(resource: URI, defaultUri: URI, availableFileSystems?: string[]): Promise<URI | undefined> {\n"
],
"file_path": "src/vs/workbench/services/textfile/common/textFileService.ts",
"type": "replace",
"edit_start_line_idx": 650
} | /*---------------------------------------------------------------------------------------------
* 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 { Emitter, Event } from 'vs/base/common/event';
import { IView, GridNode, isGridBranchNode, } from 'vs/base/browser/ui/grid/gridview';
export class TestView implements IView {
private _onDidChange = new Emitter<{ width: number; height: number; } | undefined>();
readonly onDidChange = this._onDidChange.event;
get minimumWidth(): number { return this._minimumWidth; }
set minimumWidth(size: number) { this._minimumWidth = size; this._onDidChange.fire(undefined); }
get maximumWidth(): number { return this._maximumWidth; }
set maximumWidth(size: number) { this._maximumWidth = size; this._onDidChange.fire(undefined); }
get minimumHeight(): number { return this._minimumHeight; }
set minimumHeight(size: number) { this._minimumHeight = size; this._onDidChange.fire(undefined); }
get maximumHeight(): number { return this._maximumHeight; }
set maximumHeight(size: number) { this._maximumHeight = size; this._onDidChange.fire(undefined); }
private _element: HTMLElement = document.createElement('div');
get element(): HTMLElement { this._onDidGetElement.fire(); return this._element; }
private _onDidGetElement = new Emitter<void>();
readonly onDidGetElement = this._onDidGetElement.event;
private _width = 0;
get width(): number { return this._width; }
private _height = 0;
get height(): number { return this._height; }
get size(): [number, number] { return [this.width, this.height]; }
private _onDidLayout = new Emitter<{ width: number; height: number; }>();
readonly onDidLayout: Event<{ width: number; height: number; }> = this._onDidLayout.event;
private _onDidFocus = new Emitter<void>();
readonly onDidFocus: Event<void> = this._onDidFocus.event;
constructor(
private _minimumWidth: number,
private _maximumWidth: number,
private _minimumHeight: number,
private _maximumHeight: number
) {
assert(_minimumWidth <= _maximumWidth, 'gridview view minimum width must be <= maximum width');
assert(_minimumHeight <= _maximumHeight, 'gridview view minimum height must be <= maximum height');
}
layout(width: number, height: number): void {
this._width = width;
this._height = height;
this._onDidLayout.fire({ width, height });
}
focus(): void {
this._onDidFocus.fire();
}
dispose(): void {
this._onDidChange.dispose();
this._onDidGetElement.dispose();
this._onDidLayout.dispose();
this._onDidFocus.dispose();
}
}
export function nodesToArrays(node: GridNode): any {
if (isGridBranchNode(node)) {
return node.children.map(nodesToArrays);
} else {
return node.view;
}
} | src/vs/base/test/browser/ui/grid/util.ts | 0 | https://github.com/microsoft/vscode/commit/985de26b3446636f86e2bb2b14dbeb9ec1e33207 | [
0.00017875862249638885,
0.00017574917001184076,
0.00017300073523074389,
0.00017648864013608545,
0.0000018255744862472056
] |
{
"id": 9,
"code_window": [
"\t\treturn result;\n",
"\t}\n",
"\n",
"\tprotected async promptForPath(resource: URI, defaultUri: URI): Promise<URI | undefined> {\n",
"\n",
"\t\t// Help user to find a name for the file by opening it first\n",
"\t\tawait this.editorService.openEditor({ resource, options: { revealIfOpened: true, preserveFocus: true, } });\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tprotected async promptForPath(resource: URI, defaultUri: URI, availableFileSystems?: string[]): Promise<URI | undefined> {\n"
],
"file_path": "src/vs/workbench/services/textfile/common/textFileService.ts",
"type": "replace",
"edit_start_line_idx": 650
} | /*---------------------------------------------------------------------------------------------
* 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 { CancellationToken } from 'vs/base/common/cancellation';
import { Counter } from 'vs/base/common/numbers';
import { basename } from 'vs/base/common/path';
import { URI, UriComponents } from 'vs/base/common/uri';
import { ExtensionIdentifier, IExtensionDescription } from 'vs/platform/extensions/common/extensions';
import { ILogService, NullLogService } from 'vs/platform/log/common/log';
import { IWorkspaceFolderData } from 'vs/platform/workspace/common/workspace';
import { MainThreadWorkspace } from 'vs/workbench/api/browser/mainThreadWorkspace';
import { IMainContext, IWorkspaceData, MainContext } from 'vs/workbench/api/common/extHost.protocol';
import { RelativePattern } from 'vs/workbench/api/common/extHostTypes';
import { ExtHostWorkspace } from 'vs/workbench/api/common/extHostWorkspace';
import { mock } from 'vs/workbench/test/electron-browser/api/mock';
import { TestRPCProtocol } from './testRPCProtocol';
function createExtHostWorkspace(mainContext: IMainContext, data: IWorkspaceData, logService: ILogService, requestIdProvider: Counter): ExtHostWorkspace {
const result = new ExtHostWorkspace(mainContext, logService, requestIdProvider);
result.$initializeWorkspace(data);
return result;
}
suite('ExtHostWorkspace', function () {
const extensionDescriptor: IExtensionDescription = {
identifier: new ExtensionIdentifier('nullExtensionDescription'),
name: 'ext',
publisher: 'vscode',
enableProposedApi: false,
engines: undefined!,
extensionLocation: undefined!,
isBuiltin: false,
isUnderDevelopment: false,
version: undefined!
};
function assertAsRelativePath(workspace: ExtHostWorkspace, input: string, expected: string, includeWorkspace?: boolean) {
const actual = workspace.getRelativePath(input, includeWorkspace);
assert.equal(actual, expected);
}
test('asRelativePath', () => {
const ws = createExtHostWorkspace(new TestRPCProtocol(), { id: 'foo', folders: [aWorkspaceFolderData(URI.file('/Coding/Applications/NewsWoWBot'), 0)], name: 'Test' }, new NullLogService(), new Counter());
assertAsRelativePath(ws, '/Coding/Applications/NewsWoWBot/bernd/das/brot', 'bernd/das/brot');
assertAsRelativePath(ws, '/Apps/DartPubCache/hosted/pub.dartlang.org/convert-2.0.1/lib/src/hex.dart',
'/Apps/DartPubCache/hosted/pub.dartlang.org/convert-2.0.1/lib/src/hex.dart');
assertAsRelativePath(ws, '', '');
assertAsRelativePath(ws, '/foo/bar', '/foo/bar');
assertAsRelativePath(ws, 'in/out', 'in/out');
});
test('asRelativePath, same paths, #11402', function () {
const root = '/home/aeschli/workspaces/samples/docker';
const input = '/home/aeschli/workspaces/samples/docker';
const ws = createExtHostWorkspace(new TestRPCProtocol(), { id: 'foo', folders: [aWorkspaceFolderData(URI.file(root), 0)], name: 'Test' }, new NullLogService(), new Counter());
assertAsRelativePath(ws, input, input);
const input2 = '/home/aeschli/workspaces/samples/docker/a.file';
assertAsRelativePath(ws, input2, 'a.file');
});
test('asRelativePath, no workspace', function () {
const ws = createExtHostWorkspace(new TestRPCProtocol(), null!, new NullLogService(), new Counter());
assertAsRelativePath(ws, '', '');
assertAsRelativePath(ws, '/foo/bar', '/foo/bar');
});
test('asRelativePath, multiple folders', function () {
const ws = createExtHostWorkspace(new TestRPCProtocol(), { id: 'foo', folders: [aWorkspaceFolderData(URI.file('/Coding/One'), 0), aWorkspaceFolderData(URI.file('/Coding/Two'), 1)], name: 'Test' }, new NullLogService(), new Counter());
assertAsRelativePath(ws, '/Coding/One/file.txt', 'One/file.txt');
assertAsRelativePath(ws, '/Coding/Two/files/out.txt', 'Two/files/out.txt');
assertAsRelativePath(ws, '/Coding/Two2/files/out.txt', '/Coding/Two2/files/out.txt');
});
test('slightly inconsistent behaviour of asRelativePath and getWorkspaceFolder, #31553', function () {
const mrws = createExtHostWorkspace(new TestRPCProtocol(), { id: 'foo', folders: [aWorkspaceFolderData(URI.file('/Coding/One'), 0), aWorkspaceFolderData(URI.file('/Coding/Two'), 1)], name: 'Test' }, new NullLogService(), new Counter());
assertAsRelativePath(mrws, '/Coding/One/file.txt', 'One/file.txt');
assertAsRelativePath(mrws, '/Coding/One/file.txt', 'One/file.txt', true);
assertAsRelativePath(mrws, '/Coding/One/file.txt', 'file.txt', false);
assertAsRelativePath(mrws, '/Coding/Two/files/out.txt', 'Two/files/out.txt');
assertAsRelativePath(mrws, '/Coding/Two/files/out.txt', 'Two/files/out.txt', true);
assertAsRelativePath(mrws, '/Coding/Two/files/out.txt', 'files/out.txt', false);
assertAsRelativePath(mrws, '/Coding/Two2/files/out.txt', '/Coding/Two2/files/out.txt');
assertAsRelativePath(mrws, '/Coding/Two2/files/out.txt', '/Coding/Two2/files/out.txt', true);
assertAsRelativePath(mrws, '/Coding/Two2/files/out.txt', '/Coding/Two2/files/out.txt', false);
const srws = createExtHostWorkspace(new TestRPCProtocol(), { id: 'foo', folders: [aWorkspaceFolderData(URI.file('/Coding/One'), 0)], name: 'Test' }, new NullLogService(), new Counter());
assertAsRelativePath(srws, '/Coding/One/file.txt', 'file.txt');
assertAsRelativePath(srws, '/Coding/One/file.txt', 'file.txt', false);
assertAsRelativePath(srws, '/Coding/One/file.txt', 'One/file.txt', true);
assertAsRelativePath(srws, '/Coding/Two2/files/out.txt', '/Coding/Two2/files/out.txt');
assertAsRelativePath(srws, '/Coding/Two2/files/out.txt', '/Coding/Two2/files/out.txt', true);
assertAsRelativePath(srws, '/Coding/Two2/files/out.txt', '/Coding/Two2/files/out.txt', false);
});
test('getPath, legacy', function () {
let ws = createExtHostWorkspace(new TestRPCProtocol(), { id: 'foo', name: 'Test', folders: [] }, new NullLogService(), new Counter());
assert.equal(ws.getPath(), undefined);
ws = createExtHostWorkspace(new TestRPCProtocol(), null!, new NullLogService(), new Counter());
assert.equal(ws.getPath(), undefined);
ws = createExtHostWorkspace(new TestRPCProtocol(), undefined!, new NullLogService(), new Counter());
assert.equal(ws.getPath(), undefined);
ws = createExtHostWorkspace(new TestRPCProtocol(), { id: 'foo', name: 'Test', folders: [aWorkspaceFolderData(URI.file('Folder'), 0), aWorkspaceFolderData(URI.file('Another/Folder'), 1)] }, new NullLogService(), new Counter());
assert.equal(ws.getPath()!.replace(/\\/g, '/'), '/Folder');
ws = createExtHostWorkspace(new TestRPCProtocol(), { id: 'foo', name: 'Test', folders: [aWorkspaceFolderData(URI.file('/Folder'), 0)] }, new NullLogService(), new Counter());
assert.equal(ws.getPath()!.replace(/\\/g, '/'), '/Folder');
});
test('WorkspaceFolder has name and index', function () {
const ws = createExtHostWorkspace(new TestRPCProtocol(), { id: 'foo', folders: [aWorkspaceFolderData(URI.file('/Coding/One'), 0), aWorkspaceFolderData(URI.file('/Coding/Two'), 1)], name: 'Test' }, new NullLogService(), new Counter());
const [one, two] = ws.getWorkspaceFolders()!;
assert.equal(one.name, 'One');
assert.equal(one.index, 0);
assert.equal(two.name, 'Two');
assert.equal(two.index, 1);
});
test('getContainingWorkspaceFolder', () => {
const ws = createExtHostWorkspace(new TestRPCProtocol(), {
id: 'foo',
name: 'Test',
folders: [
aWorkspaceFolderData(URI.file('/Coding/One'), 0),
aWorkspaceFolderData(URI.file('/Coding/Two'), 1),
aWorkspaceFolderData(URI.file('/Coding/Two/Nested'), 2)
]
}, new NullLogService(), new Counter());
let folder = ws.getWorkspaceFolder(URI.file('/foo/bar'));
assert.equal(folder, undefined);
folder = ws.getWorkspaceFolder(URI.file('/Coding/One/file/path.txt'))!;
assert.equal(folder.name, 'One');
folder = ws.getWorkspaceFolder(URI.file('/Coding/Two/file/path.txt'))!;
assert.equal(folder.name, 'Two');
folder = ws.getWorkspaceFolder(URI.file('/Coding/Two/Nest'))!;
assert.equal(folder.name, 'Two');
folder = ws.getWorkspaceFolder(URI.file('/Coding/Two/Nested/file'))!;
assert.equal(folder.name, 'Nested');
folder = ws.getWorkspaceFolder(URI.file('/Coding/Two/Nested/f'))!;
assert.equal(folder.name, 'Nested');
folder = ws.getWorkspaceFolder(URI.file('/Coding/Two/Nested'), true)!;
assert.equal(folder.name, 'Two');
folder = ws.getWorkspaceFolder(URI.file('/Coding/Two/Nested/'), true)!;
assert.equal(folder.name, 'Two');
folder = ws.getWorkspaceFolder(URI.file('/Coding/Two/Nested'))!;
assert.equal(folder.name, 'Nested');
folder = ws.getWorkspaceFolder(URI.file('/Coding/Two/Nested/'))!;
assert.equal(folder.name, 'Nested');
folder = ws.getWorkspaceFolder(URI.file('/Coding/Two'), true)!;
assert.equal(folder, undefined);
folder = ws.getWorkspaceFolder(URI.file('/Coding/Two'), false)!;
assert.equal(folder.name, 'Two');
});
test('Multiroot change event should have a delta, #29641', function (done) {
let ws = createExtHostWorkspace(new TestRPCProtocol(), { id: 'foo', name: 'Test', folders: [] }, new NullLogService(), new Counter());
let finished = false;
const finish = (error?: any) => {
if (!finished) {
finished = true;
done(error);
}
};
let sub = ws.onDidChangeWorkspace(e => {
try {
assert.deepEqual(e.added, []);
assert.deepEqual(e.removed, []);
} catch (error) {
finish(error);
}
});
ws.$acceptWorkspaceData({ id: 'foo', name: 'Test', folders: [] });
sub.dispose();
sub = ws.onDidChangeWorkspace(e => {
try {
assert.deepEqual(e.removed, []);
assert.equal(e.added.length, 1);
assert.equal(e.added[0].uri.toString(), 'foo:bar');
} catch (error) {
finish(error);
}
});
ws.$acceptWorkspaceData({ id: 'foo', name: 'Test', folders: [aWorkspaceFolderData(URI.parse('foo:bar'), 0)] });
sub.dispose();
sub = ws.onDidChangeWorkspace(e => {
try {
assert.deepEqual(e.removed, []);
assert.equal(e.added.length, 1);
assert.equal(e.added[0].uri.toString(), 'foo:bar2');
} catch (error) {
finish(error);
}
});
ws.$acceptWorkspaceData({ id: 'foo', name: 'Test', folders: [aWorkspaceFolderData(URI.parse('foo:bar'), 0), aWorkspaceFolderData(URI.parse('foo:bar2'), 1)] });
sub.dispose();
sub = ws.onDidChangeWorkspace(e => {
try {
assert.equal(e.removed.length, 2);
assert.equal(e.removed[0].uri.toString(), 'foo:bar');
assert.equal(e.removed[1].uri.toString(), 'foo:bar2');
assert.equal(e.added.length, 1);
assert.equal(e.added[0].uri.toString(), 'foo:bar3');
} catch (error) {
finish(error);
}
});
ws.$acceptWorkspaceData({ id: 'foo', name: 'Test', folders: [aWorkspaceFolderData(URI.parse('foo:bar3'), 0)] });
sub.dispose();
finish();
});
test('Multiroot change keeps existing workspaces live', function () {
let ws = createExtHostWorkspace(new TestRPCProtocol(), { id: 'foo', name: 'Test', folders: [aWorkspaceFolderData(URI.parse('foo:bar'), 0)] }, new NullLogService(), new Counter());
let firstFolder = ws.getWorkspaceFolders()![0];
ws.$acceptWorkspaceData({ id: 'foo', name: 'Test', folders: [aWorkspaceFolderData(URI.parse('foo:bar2'), 0), aWorkspaceFolderData(URI.parse('foo:bar'), 1, 'renamed')] });
assert.equal(ws.getWorkspaceFolders()![1], firstFolder);
assert.equal(firstFolder.index, 1);
assert.equal(firstFolder.name, 'renamed');
ws.$acceptWorkspaceData({ id: 'foo', name: 'Test', folders: [aWorkspaceFolderData(URI.parse('foo:bar3'), 0), aWorkspaceFolderData(URI.parse('foo:bar2'), 1), aWorkspaceFolderData(URI.parse('foo:bar'), 2)] });
assert.equal(ws.getWorkspaceFolders()![2], firstFolder);
assert.equal(firstFolder.index, 2);
ws.$acceptWorkspaceData({ id: 'foo', name: 'Test', folders: [aWorkspaceFolderData(URI.parse('foo:bar3'), 0)] });
ws.$acceptWorkspaceData({ id: 'foo', name: 'Test', folders: [aWorkspaceFolderData(URI.parse('foo:bar3'), 0), aWorkspaceFolderData(URI.parse('foo:bar'), 1)] });
assert.notEqual(firstFolder, ws.workspace!.folders[0]);
});
test('updateWorkspaceFolders - invalid arguments', function () {
let ws = createExtHostWorkspace(new TestRPCProtocol(), { id: 'foo', name: 'Test', folders: [] }, new NullLogService(), new Counter());
assert.equal(false, ws.updateWorkspaceFolders(extensionDescriptor, null!, null!));
assert.equal(false, ws.updateWorkspaceFolders(extensionDescriptor, 0, 0));
assert.equal(false, ws.updateWorkspaceFolders(extensionDescriptor, 0, 1));
assert.equal(false, ws.updateWorkspaceFolders(extensionDescriptor, 1, 0));
assert.equal(false, ws.updateWorkspaceFolders(extensionDescriptor, -1, 0));
assert.equal(false, ws.updateWorkspaceFolders(extensionDescriptor, -1, -1));
ws = createExtHostWorkspace(new TestRPCProtocol(), { id: 'foo', name: 'Test', folders: [aWorkspaceFolderData(URI.parse('foo:bar'), 0)] }, new NullLogService(), new Counter());
assert.equal(false, ws.updateWorkspaceFolders(extensionDescriptor, 1, 1));
assert.equal(false, ws.updateWorkspaceFolders(extensionDescriptor, 0, 2));
assert.equal(false, ws.updateWorkspaceFolders(extensionDescriptor, 0, 1, asUpdateWorkspaceFolderData(URI.parse('foo:bar'))));
});
test('updateWorkspaceFolders - valid arguments', function (done) {
let finished = false;
const finish = (error?: any) => {
if (!finished) {
finished = true;
done(error);
}
};
const protocol: IMainContext = {
getProxy: () => { return undefined!; },
set: undefined!,
assertRegistered: undefined!
};
const ws = createExtHostWorkspace(protocol, { id: 'foo', name: 'Test', folders: [] }, new NullLogService(), new Counter());
//
// Add one folder
//
assert.equal(true, ws.updateWorkspaceFolders(extensionDescriptor, 0, 0, asUpdateWorkspaceFolderData(URI.parse('foo:bar'))));
assert.equal(1, ws.workspace!.folders.length);
assert.equal(ws.workspace!.folders[0].uri.toString(), URI.parse('foo:bar').toString());
const firstAddedFolder = ws.getWorkspaceFolders()![0];
let gotEvent = false;
let sub = ws.onDidChangeWorkspace(e => {
try {
assert.deepEqual(e.removed, []);
assert.equal(e.added.length, 1);
assert.equal(e.added[0].uri.toString(), 'foo:bar');
assert.equal(e.added[0], firstAddedFolder); // verify object is still live
gotEvent = true;
} catch (error) {
finish(error);
}
});
ws.$acceptWorkspaceData({ id: 'foo', name: 'Test', folders: [aWorkspaceFolderData(URI.parse('foo:bar'), 0)] }); // simulate acknowledgement from main side
assert.equal(gotEvent, true);
sub.dispose();
assert.equal(ws.getWorkspaceFolders()![0], firstAddedFolder); // verify object is still live
//
// Add two more folders
//
assert.equal(true, ws.updateWorkspaceFolders(extensionDescriptor, 1, 0, asUpdateWorkspaceFolderData(URI.parse('foo:bar1')), asUpdateWorkspaceFolderData(URI.parse('foo:bar2'))));
assert.equal(3, ws.workspace!.folders.length);
assert.equal(ws.workspace!.folders[0].uri.toString(), URI.parse('foo:bar').toString());
assert.equal(ws.workspace!.folders[1].uri.toString(), URI.parse('foo:bar1').toString());
assert.equal(ws.workspace!.folders[2].uri.toString(), URI.parse('foo:bar2').toString());
const secondAddedFolder = ws.getWorkspaceFolders()![1];
const thirdAddedFolder = ws.getWorkspaceFolders()![2];
gotEvent = false;
sub = ws.onDidChangeWorkspace(e => {
try {
assert.deepEqual(e.removed, []);
assert.equal(e.added.length, 2);
assert.equal(e.added[0].uri.toString(), 'foo:bar1');
assert.equal(e.added[1].uri.toString(), 'foo:bar2');
assert.equal(e.added[0], secondAddedFolder);
assert.equal(e.added[1], thirdAddedFolder);
gotEvent = true;
} catch (error) {
finish(error);
}
});
ws.$acceptWorkspaceData({ id: 'foo', name: 'Test', folders: [aWorkspaceFolderData(URI.parse('foo:bar'), 0), aWorkspaceFolderData(URI.parse('foo:bar1'), 1), aWorkspaceFolderData(URI.parse('foo:bar2'), 2)] }); // simulate acknowledgement from main side
assert.equal(gotEvent, true);
sub.dispose();
assert.equal(ws.getWorkspaceFolders()![0], firstAddedFolder); // verify object is still live
assert.equal(ws.getWorkspaceFolders()![1], secondAddedFolder); // verify object is still live
assert.equal(ws.getWorkspaceFolders()![2], thirdAddedFolder); // verify object is still live
//
// Remove one folder
//
assert.equal(true, ws.updateWorkspaceFolders(extensionDescriptor, 2, 1));
assert.equal(2, ws.workspace!.folders.length);
assert.equal(ws.workspace!.folders[0].uri.toString(), URI.parse('foo:bar').toString());
assert.equal(ws.workspace!.folders[1].uri.toString(), URI.parse('foo:bar1').toString());
gotEvent = false;
sub = ws.onDidChangeWorkspace(e => {
try {
assert.deepEqual(e.added, []);
assert.equal(e.removed.length, 1);
assert.equal(e.removed[0], thirdAddedFolder);
gotEvent = true;
} catch (error) {
finish(error);
}
});
ws.$acceptWorkspaceData({ id: 'foo', name: 'Test', folders: [aWorkspaceFolderData(URI.parse('foo:bar'), 0), aWorkspaceFolderData(URI.parse('foo:bar1'), 1)] }); // simulate acknowledgement from main side
assert.equal(gotEvent, true);
sub.dispose();
assert.equal(ws.getWorkspaceFolders()![0], firstAddedFolder); // verify object is still live
assert.equal(ws.getWorkspaceFolders()![1], secondAddedFolder); // verify object is still live
//
// Rename folder
//
assert.equal(true, ws.updateWorkspaceFolders(extensionDescriptor, 0, 2, asUpdateWorkspaceFolderData(URI.parse('foo:bar'), 'renamed 1'), asUpdateWorkspaceFolderData(URI.parse('foo:bar1'), 'renamed 2')));
assert.equal(2, ws.workspace!.folders.length);
assert.equal(ws.workspace!.folders[0].uri.toString(), URI.parse('foo:bar').toString());
assert.equal(ws.workspace!.folders[1].uri.toString(), URI.parse('foo:bar1').toString());
assert.equal(ws.workspace!.folders[0].name, 'renamed 1');
assert.equal(ws.workspace!.folders[1].name, 'renamed 2');
assert.equal(ws.getWorkspaceFolders()![0].name, 'renamed 1');
assert.equal(ws.getWorkspaceFolders()![1].name, 'renamed 2');
gotEvent = false;
sub = ws.onDidChangeWorkspace(e => {
try {
assert.deepEqual(e.added, []);
assert.equal(e.removed.length, []);
gotEvent = true;
} catch (error) {
finish(error);
}
});
ws.$acceptWorkspaceData({ id: 'foo', name: 'Test', folders: [aWorkspaceFolderData(URI.parse('foo:bar'), 0, 'renamed 1'), aWorkspaceFolderData(URI.parse('foo:bar1'), 1, 'renamed 2')] }); // simulate acknowledgement from main side
assert.equal(gotEvent, true);
sub.dispose();
assert.equal(ws.getWorkspaceFolders()![0], firstAddedFolder); // verify object is still live
assert.equal(ws.getWorkspaceFolders()![1], secondAddedFolder); // verify object is still live
assert.equal(ws.workspace!.folders[0].name, 'renamed 1');
assert.equal(ws.workspace!.folders[1].name, 'renamed 2');
assert.equal(ws.getWorkspaceFolders()![0].name, 'renamed 1');
assert.equal(ws.getWorkspaceFolders()![1].name, 'renamed 2');
//
// Add and remove folders
//
assert.equal(true, ws.updateWorkspaceFolders(extensionDescriptor, 0, 2, asUpdateWorkspaceFolderData(URI.parse('foo:bar3')), asUpdateWorkspaceFolderData(URI.parse('foo:bar4'))));
assert.equal(2, ws.workspace!.folders.length);
assert.equal(ws.workspace!.folders[0].uri.toString(), URI.parse('foo:bar3').toString());
assert.equal(ws.workspace!.folders[1].uri.toString(), URI.parse('foo:bar4').toString());
const fourthAddedFolder = ws.getWorkspaceFolders()![0];
const fifthAddedFolder = ws.getWorkspaceFolders()![1];
gotEvent = false;
sub = ws.onDidChangeWorkspace(e => {
try {
assert.equal(e.added.length, 2);
assert.equal(e.added[0], fourthAddedFolder);
assert.equal(e.added[1], fifthAddedFolder);
assert.equal(e.removed.length, 2);
assert.equal(e.removed[0], firstAddedFolder);
assert.equal(e.removed[1], secondAddedFolder);
gotEvent = true;
} catch (error) {
finish(error);
}
});
ws.$acceptWorkspaceData({ id: 'foo', name: 'Test', folders: [aWorkspaceFolderData(URI.parse('foo:bar3'), 0), aWorkspaceFolderData(URI.parse('foo:bar4'), 1)] }); // simulate acknowledgement from main side
assert.equal(gotEvent, true);
sub.dispose();
assert.equal(ws.getWorkspaceFolders()![0], fourthAddedFolder); // verify object is still live
assert.equal(ws.getWorkspaceFolders()![1], fifthAddedFolder); // verify object is still live
//
// Swap folders
//
assert.equal(true, ws.updateWorkspaceFolders(extensionDescriptor, 0, 2, asUpdateWorkspaceFolderData(URI.parse('foo:bar4')), asUpdateWorkspaceFolderData(URI.parse('foo:bar3'))));
assert.equal(2, ws.workspace!.folders.length);
assert.equal(ws.workspace!.folders[0].uri.toString(), URI.parse('foo:bar4').toString());
assert.equal(ws.workspace!.folders[1].uri.toString(), URI.parse('foo:bar3').toString());
assert.equal(ws.getWorkspaceFolders()![0], fifthAddedFolder); // verify object is still live
assert.equal(ws.getWorkspaceFolders()![1], fourthAddedFolder); // verify object is still live
gotEvent = false;
sub = ws.onDidChangeWorkspace(e => {
try {
assert.equal(e.added.length, 0);
assert.equal(e.removed.length, 0);
gotEvent = true;
} catch (error) {
finish(error);
}
});
ws.$acceptWorkspaceData({ id: 'foo', name: 'Test', folders: [aWorkspaceFolderData(URI.parse('foo:bar4'), 0), aWorkspaceFolderData(URI.parse('foo:bar3'), 1)] }); // simulate acknowledgement from main side
assert.equal(gotEvent, true);
sub.dispose();
assert.equal(ws.getWorkspaceFolders()![0], fifthAddedFolder); // verify object is still live
assert.equal(ws.getWorkspaceFolders()![1], fourthAddedFolder); // verify object is still live
assert.equal(fifthAddedFolder.index, 0);
assert.equal(fourthAddedFolder.index, 1);
//
// Add one folder after the other without waiting for confirmation (not supported currently)
//
assert.equal(true, ws.updateWorkspaceFolders(extensionDescriptor, 2, 0, asUpdateWorkspaceFolderData(URI.parse('foo:bar5'))));
assert.equal(3, ws.workspace!.folders.length);
assert.equal(ws.workspace!.folders[0].uri.toString(), URI.parse('foo:bar4').toString());
assert.equal(ws.workspace!.folders[1].uri.toString(), URI.parse('foo:bar3').toString());
assert.equal(ws.workspace!.folders[2].uri.toString(), URI.parse('foo:bar5').toString());
const sixthAddedFolder = ws.getWorkspaceFolders()![2];
gotEvent = false;
sub = ws.onDidChangeWorkspace(e => {
try {
assert.equal(e.added.length, 1);
assert.equal(e.added[0], sixthAddedFolder);
gotEvent = true;
} catch (error) {
finish(error);
}
});
ws.$acceptWorkspaceData({
id: 'foo', name: 'Test', folders: [
aWorkspaceFolderData(URI.parse('foo:bar4'), 0),
aWorkspaceFolderData(URI.parse('foo:bar3'), 1),
aWorkspaceFolderData(URI.parse('foo:bar5'), 2)
]
}); // simulate acknowledgement from main side
assert.equal(gotEvent, true);
sub.dispose();
assert.equal(ws.getWorkspaceFolders()![0], fifthAddedFolder); // verify object is still live
assert.equal(ws.getWorkspaceFolders()![1], fourthAddedFolder); // verify object is still live
assert.equal(ws.getWorkspaceFolders()![2], sixthAddedFolder); // verify object is still live
finish();
});
test('Multiroot change event is immutable', function (done) {
let finished = false;
const finish = (error?: any) => {
if (!finished) {
finished = true;
done(error);
}
};
let ws = createExtHostWorkspace(new TestRPCProtocol(), { id: 'foo', name: 'Test', folders: [] }, new NullLogService(), new Counter());
let sub = ws.onDidChangeWorkspace(e => {
try {
assert.throws(() => {
(<any>e).added = [];
});
// assert.throws(() => {
// (<any>e.added)[0] = null;
// });
} catch (error) {
finish(error);
}
});
ws.$acceptWorkspaceData({ id: 'foo', name: 'Test', folders: [] });
sub.dispose();
finish();
});
test('`vscode.workspace.getWorkspaceFolder(file)` don\'t return workspace folder when file open from command line. #36221', function () {
let ws = createExtHostWorkspace(new TestRPCProtocol(), {
id: 'foo', name: 'Test', folders: [
aWorkspaceFolderData(URI.file('c:/Users/marek/Desktop/vsc_test/'), 0)
]
}, new NullLogService(), new Counter());
assert.ok(ws.getWorkspaceFolder(URI.file('c:/Users/marek/Desktop/vsc_test/a.txt')));
assert.ok(ws.getWorkspaceFolder(URI.file('C:/Users/marek/Desktop/vsc_test/b.txt')));
});
function aWorkspaceFolderData(uri: URI, index: number, name: string = ''): IWorkspaceFolderData {
return {
uri,
index,
name: name || basename(uri.path)
};
}
function asUpdateWorkspaceFolderData(uri: URI, name?: string): { uri: URI, name?: string } {
return { uri, name };
}
test('findFiles - string include', () => {
const root = '/project/foo';
const rpcProtocol = new TestRPCProtocol();
let mainThreadCalled = false;
rpcProtocol.set(MainContext.MainThreadWorkspace, new class extends mock<MainThreadWorkspace>() {
$startFileSearch(includePattern: string, _includeFolder: UriComponents | undefined, excludePatternOrDisregardExcludes: string | false, maxResults: number, token: CancellationToken): Promise<URI[] | undefined> {
mainThreadCalled = true;
assert.equal(includePattern, 'foo');
assert.equal(_includeFolder, undefined);
assert.equal(excludePatternOrDisregardExcludes, undefined);
assert.equal(maxResults, 10);
return Promise.resolve(undefined);
}
});
const ws = createExtHostWorkspace(rpcProtocol, { id: 'foo', folders: [aWorkspaceFolderData(URI.file(root), 0)], name: 'Test' }, new NullLogService(), new Counter());
return ws.findFiles('foo', undefined!, 10, new ExtensionIdentifier('test')).then(() => {
assert(mainThreadCalled, 'mainThreadCalled');
});
});
test('findFiles - RelativePattern include', () => {
const root = '/project/foo';
const rpcProtocol = new TestRPCProtocol();
let mainThreadCalled = false;
rpcProtocol.set(MainContext.MainThreadWorkspace, new class extends mock<MainThreadWorkspace>() {
$startFileSearch(includePattern: string, _includeFolder: UriComponents | undefined, excludePatternOrDisregardExcludes: string | false, maxResults: number, token: CancellationToken): Promise<URI[] | undefined> {
mainThreadCalled = true;
assert.equal(includePattern, 'glob/**');
assert.deepEqual(_includeFolder, URI.file('/other/folder').toJSON());
assert.equal(excludePatternOrDisregardExcludes, undefined);
return Promise.resolve(undefined);
}
});
const ws = createExtHostWorkspace(rpcProtocol, { id: 'foo', folders: [aWorkspaceFolderData(URI.file(root), 0)], name: 'Test' }, new NullLogService(), new Counter());
return ws.findFiles(new RelativePattern('/other/folder', 'glob/**'), undefined!, 10, new ExtensionIdentifier('test')).then(() => {
assert(mainThreadCalled, 'mainThreadCalled');
});
});
test('findFiles - no excludes', () => {
const root = '/project/foo';
const rpcProtocol = new TestRPCProtocol();
let mainThreadCalled = false;
rpcProtocol.set(MainContext.MainThreadWorkspace, new class extends mock<MainThreadWorkspace>() {
$startFileSearch(includePattern: string, _includeFolder: UriComponents | undefined, excludePatternOrDisregardExcludes: string | false, maxResults: number, token: CancellationToken): Promise<URI[] | undefined> {
mainThreadCalled = true;
assert.equal(includePattern, 'glob/**');
assert.deepEqual(_includeFolder, URI.file('/other/folder').toJSON());
assert.equal(excludePatternOrDisregardExcludes, false);
return Promise.resolve(undefined);
}
});
const ws = createExtHostWorkspace(rpcProtocol, { id: 'foo', folders: [aWorkspaceFolderData(URI.file(root), 0)], name: 'Test' }, new NullLogService(), new Counter());
return ws.findFiles(new RelativePattern('/other/folder', 'glob/**'), null!, 10, new ExtensionIdentifier('test')).then(() => {
assert(mainThreadCalled, 'mainThreadCalled');
});
});
test('findFiles - with cancelled token', () => {
const root = '/project/foo';
const rpcProtocol = new TestRPCProtocol();
let mainThreadCalled = false;
rpcProtocol.set(MainContext.MainThreadWorkspace, new class extends mock<MainThreadWorkspace>() {
$startFileSearch(includePattern: string, _includeFolder: UriComponents | undefined, excludePatternOrDisregardExcludes: string | false, maxResults: number, token: CancellationToken): Promise<URI[] | undefined> {
mainThreadCalled = true;
return Promise.resolve(undefined);
}
});
const ws = createExtHostWorkspace(rpcProtocol, { id: 'foo', folders: [aWorkspaceFolderData(URI.file(root), 0)], name: 'Test' }, new NullLogService(), new Counter());
const token = CancellationToken.Cancelled;
return ws.findFiles(new RelativePattern('/other/folder', 'glob/**'), null!, 10, new ExtensionIdentifier('test'), token).then(() => {
assert(!mainThreadCalled, '!mainThreadCalled');
});
});
test('findFiles - RelativePattern exclude', () => {
const root = '/project/foo';
const rpcProtocol = new TestRPCProtocol();
let mainThreadCalled = false;
rpcProtocol.set(MainContext.MainThreadWorkspace, new class extends mock<MainThreadWorkspace>() {
$startFileSearch(includePattern: string, _includeFolder: UriComponents | undefined, excludePatternOrDisregardExcludes: string | false, maxResults: number, token: CancellationToken): Promise<URI[] | undefined> {
mainThreadCalled = true;
assert(excludePatternOrDisregardExcludes, 'glob/**'); // Note that the base portion is ignored, see #52651
return Promise.resolve(undefined);
}
});
const ws = createExtHostWorkspace(rpcProtocol, { id: 'foo', folders: [aWorkspaceFolderData(URI.file(root), 0)], name: 'Test' }, new NullLogService(), new Counter());
return ws.findFiles('', new RelativePattern(root, 'glob/**'), 10, new ExtensionIdentifier('test')).then(() => {
assert(mainThreadCalled, 'mainThreadCalled');
});
});
});
| src/vs/workbench/test/electron-browser/api/extHostWorkspace.test.ts | 0 | https://github.com/microsoft/vscode/commit/985de26b3446636f86e2bb2b14dbeb9ec1e33207 | [
0.00031144017702899873,
0.00017914081399794668,
0.00016526576655451208,
0.00017309603572357446,
0.000026406545657664537
] |
{
"id": 10,
"code_window": [
"\t\t// Help user to find a name for the file by opening it first\n",
"\t\tawait this.editorService.openEditor({ resource, options: { revealIfOpened: true, preserveFocus: true, } });\n",
"\n",
"\t\treturn this.fileDialogService.pickFileToSave(this.getSaveDialogOptions(defaultUri));\n",
"\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
"\t\treturn this.fileDialogService.pickFileToSave(this.getSaveDialogOptions(defaultUri, availableFileSystems));\n"
],
"file_path": "src/vs/workbench/services/textfile/common/textFileService.ts",
"type": "replace",
"edit_start_line_idx": 655
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as nls from 'vs/nls';
import { URI } from 'vs/base/common/uri';
import * as errors from 'vs/base/common/errors';
import * as objects from 'vs/base/common/objects';
import { Event, Emitter } from 'vs/base/common/event';
import * as platform from 'vs/base/common/platform';
import { IWindowsService } from 'vs/platform/windows/common/windows';
import { IBackupFileService } from 'vs/workbench/services/backup/common/backup';
import { IResult, ITextFileOperationResult, ITextFileService, ITextFileStreamContent, IAutoSaveConfiguration, AutoSaveMode, SaveReason, ITextFileEditorModelManager, ITextFileEditorModel, ModelState, ISaveOptions, AutoSaveContext, IWillMoveEvent, ITextFileContent, IResourceEncodings, IReadTextFileOptions, IWriteTextFileOptions, toBufferOrReadable, TextFileOperationError, TextFileOperationResult } from 'vs/workbench/services/textfile/common/textfiles';
import { ConfirmResult, IRevertOptions } from 'vs/workbench/common/editor';
import { ILifecycleService, ShutdownReason, LifecyclePhase } from 'vs/platform/lifecycle/common/lifecycle';
import { IWorkspaceContextService, WorkbenchState } from 'vs/platform/workspace/common/workspace';
import { IFileService, IFilesConfiguration, FileOperationError, FileOperationResult, AutoSaveConfiguration, HotExitConfiguration, IFileStatWithMetadata, ICreateFileOptions } from 'vs/platform/files/common/files';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { Disposable } from 'vs/base/common/lifecycle';
import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService';
import { IUntitledEditorService } from 'vs/workbench/services/untitled/common/untitledEditorService';
import { UntitledEditorModel } from 'vs/workbench/common/editor/untitledEditorModel';
import { TextFileEditorModelManager } from 'vs/workbench/services/textfile/common/textFileEditorModelManager';
import { IInstantiationService, ServiceIdentifier } from 'vs/platform/instantiation/common/instantiation';
import { ResourceMap } from 'vs/base/common/map';
import { Schemas } from 'vs/base/common/network';
import { IHistoryService } from 'vs/workbench/services/history/common/history';
import { IContextKey, IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { createTextBufferFactoryFromSnapshot, createTextBufferFactoryFromStream } from 'vs/editor/common/model/textModel';
import { IModelService } from 'vs/editor/common/services/modelService';
import { INotificationService, Severity } from 'vs/platform/notification/common/notification';
import { isEqualOrParent, isEqual, joinPath, dirname, extname, basename, toLocalResource } from 'vs/base/common/resources';
import { posix } from 'vs/base/common/path';
import { getConfirmMessage, IDialogService, IFileDialogService, ISaveDialogOptions, IConfirmation } from 'vs/platform/dialogs/common/dialogs';
import { IModeService } from 'vs/editor/common/services/modeService';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { coalesce } from 'vs/base/common/arrays';
import { trim } from 'vs/base/common/strings';
import { VSBuffer } from 'vs/base/common/buffer';
import { ITextSnapshot } from 'vs/editor/common/model';
import { ITextResourceConfigurationService } from 'vs/editor/common/services/resourceConfiguration';
import { PLAINTEXT_MODE_ID } from 'vs/editor/common/modes/modesRegistry';
/**
* The workbench file service implementation implements the raw file service spec and adds additional methods on top.
*/
export abstract class TextFileService extends Disposable implements ITextFileService {
_serviceBrand: ServiceIdentifier<any>;
private readonly _onAutoSaveConfigurationChange: Emitter<IAutoSaveConfiguration> = this._register(new Emitter<IAutoSaveConfiguration>());
get onAutoSaveConfigurationChange(): Event<IAutoSaveConfiguration> { return this._onAutoSaveConfigurationChange.event; }
private readonly _onFilesAssociationChange: Emitter<void> = this._register(new Emitter<void>());
get onFilesAssociationChange(): Event<void> { return this._onFilesAssociationChange.event; }
private readonly _onWillMove = this._register(new Emitter<IWillMoveEvent>());
get onWillMove(): Event<IWillMoveEvent> { return this._onWillMove.event; }
private _models: TextFileEditorModelManager;
get models(): ITextFileEditorModelManager { return this._models; }
abstract get encoding(): IResourceEncodings;
private currentFilesAssociationConfig: { [key: string]: string; };
private configuredAutoSaveDelay?: number;
private configuredAutoSaveOnFocusChange: boolean;
private configuredAutoSaveOnWindowChange: boolean;
private configuredHotExit: string;
private autoSaveContext: IContextKey<string>;
constructor(
@IWorkspaceContextService private readonly contextService: IWorkspaceContextService,
@IFileService protected readonly fileService: IFileService,
@IUntitledEditorService private readonly untitledEditorService: IUntitledEditorService,
@ILifecycleService private readonly lifecycleService: ILifecycleService,
@IInstantiationService protected instantiationService: IInstantiationService,
@IConfigurationService private readonly configurationService: IConfigurationService,
@IModeService private readonly modeService: IModeService,
@IModelService private readonly modelService: IModelService,
@IWorkbenchEnvironmentService protected readonly environmentService: IWorkbenchEnvironmentService,
@INotificationService private readonly notificationService: INotificationService,
@IBackupFileService private readonly backupFileService: IBackupFileService,
@IWindowsService private readonly windowsService: IWindowsService,
@IHistoryService private readonly historyService: IHistoryService,
@IContextKeyService contextKeyService: IContextKeyService,
@IDialogService private readonly dialogService: IDialogService,
@IFileDialogService private readonly fileDialogService: IFileDialogService,
@IEditorService private readonly editorService: IEditorService,
@ITextResourceConfigurationService protected readonly textResourceConfigurationService: ITextResourceConfigurationService
) {
super();
this._models = this._register(instantiationService.createInstance(TextFileEditorModelManager));
this.autoSaveContext = AutoSaveContext.bindTo(contextKeyService);
const configuration = configurationService.getValue<IFilesConfiguration>();
this.currentFilesAssociationConfig = configuration && configuration.files && configuration.files.associations;
this.onFilesConfigurationChange(configuration);
this.registerListeners();
}
//#region event handling
private registerListeners(): void {
// Lifecycle
this.lifecycleService.onBeforeShutdown(event => event.veto(this.beforeShutdown(event.reason)));
this.lifecycleService.onShutdown(this.dispose, this);
// Files configuration changes
this._register(this.configurationService.onDidChangeConfiguration(e => {
if (e.affectsConfiguration('files')) {
this.onFilesConfigurationChange(this.configurationService.getValue<IFilesConfiguration>());
}
}));
}
private beforeShutdown(reason: ShutdownReason): boolean | Promise<boolean> {
// Dirty files need treatment on shutdown
const dirty = this.getDirty();
if (dirty.length) {
// If auto save is enabled, save all files and then check again for dirty files
// We DO NOT run any save participant if we are in the shutdown phase for performance reasons
if (this.getAutoSaveMode() !== AutoSaveMode.OFF) {
return this.saveAll(false /* files only */, { skipSaveParticipants: true }).then(() => {
// If we still have dirty files, we either have untitled ones or files that cannot be saved
const remainingDirty = this.getDirty();
if (remainingDirty.length) {
return this.handleDirtyBeforeShutdown(remainingDirty, reason);
}
return false;
});
}
// Auto save is not enabled
return this.handleDirtyBeforeShutdown(dirty, reason);
}
// No dirty files: no veto
return this.noVeto({ cleanUpBackups: true });
}
private handleDirtyBeforeShutdown(dirty: URI[], reason: ShutdownReason): boolean | Promise<boolean> {
// If hot exit is enabled, backup dirty files and allow to exit without confirmation
if (this.isHotExitEnabled) {
return this.backupBeforeShutdown(dirty, this.models, reason).then(didBackup => {
if (didBackup) {
return this.noVeto({ cleanUpBackups: false }); // no veto and no backup cleanup (since backup was successful)
}
// since a backup did not happen, we have to confirm for the dirty files now
return this.confirmBeforeShutdown();
}, errors => {
const firstError = errors[0];
this.notificationService.error(nls.localize('files.backup.failSave', "Files that are dirty could not be written to the backup location (Error: {0}). Try saving your files first and then exit.", firstError.message));
return true; // veto, the backups failed
});
}
// Otherwise just confirm from the user what to do with the dirty files
return this.confirmBeforeShutdown();
}
private async backupBeforeShutdown(dirtyToBackup: URI[], textFileEditorModelManager: ITextFileEditorModelManager, reason: ShutdownReason): Promise<boolean> {
const windowCount = await this.windowsService.getWindowCount();
// When quit is requested skip the confirm callback and attempt to backup all workspaces.
// When quit is not requested the confirm callback should be shown when the window being
// closed is the only VS Code window open, except for on Mac where hot exit is only
// ever activated when quit is requested.
let doBackup: boolean | undefined;
switch (reason) {
case ShutdownReason.CLOSE:
if (this.contextService.getWorkbenchState() !== WorkbenchState.EMPTY && this.configuredHotExit === HotExitConfiguration.ON_EXIT_AND_WINDOW_CLOSE) {
doBackup = true; // backup if a folder is open and onExitAndWindowClose is configured
} else if (windowCount > 1 || platform.isMacintosh) {
doBackup = false; // do not backup if a window is closed that does not cause quitting of the application
} else {
doBackup = true; // backup if last window is closed on win/linux where the application quits right after
}
break;
case ShutdownReason.QUIT:
doBackup = true; // backup because next start we restore all backups
break;
case ShutdownReason.RELOAD:
doBackup = true; // backup because after window reload, backups restore
break;
case ShutdownReason.LOAD:
if (this.contextService.getWorkbenchState() !== WorkbenchState.EMPTY && this.configuredHotExit === HotExitConfiguration.ON_EXIT_AND_WINDOW_CLOSE) {
doBackup = true; // backup if a folder is open and onExitAndWindowClose is configured
} else {
doBackup = false; // do not backup because we are switching contexts
}
break;
}
if (!doBackup) {
return false;
}
await this.backupAll(dirtyToBackup, textFileEditorModelManager);
return true;
}
private backupAll(dirtyToBackup: URI[], textFileEditorModelManager: ITextFileEditorModelManager): Promise<void> {
// split up between files and untitled
const filesToBackup: ITextFileEditorModel[] = [];
const untitledToBackup: URI[] = [];
dirtyToBackup.forEach(s => {
if (this.fileService.canHandleResource(s)) {
const model = textFileEditorModelManager.get(s);
if (model) {
filesToBackup.push(model);
}
} else if (s.scheme === Schemas.untitled) {
untitledToBackup.push(s);
}
});
return this.doBackupAll(filesToBackup, untitledToBackup);
}
private async doBackupAll(dirtyFileModels: ITextFileEditorModel[], untitledResources: URI[]): Promise<void> {
// Handle file resources first
await Promise.all(dirtyFileModels.map(model => model.backup()));
// Handle untitled resources
await Promise.all(untitledResources
.filter(untitled => this.untitledEditorService.exists(untitled))
.map(async untitled => (await this.untitledEditorService.loadOrCreate({ resource: untitled })).backup()));
}
private async confirmBeforeShutdown(): Promise<boolean> {
const confirm = await this.confirmSave();
// Save
if (confirm === ConfirmResult.SAVE) {
const result = await this.saveAll(true /* includeUntitled */, { skipSaveParticipants: true });
if (result.results.some(r => !r.success)) {
return true; // veto if some saves failed
}
return this.noVeto({ cleanUpBackups: true });
}
// Don't Save
else if (confirm === ConfirmResult.DONT_SAVE) {
// Make sure to revert untitled so that they do not restore
// see https://github.com/Microsoft/vscode/issues/29572
this.untitledEditorService.revertAll();
return this.noVeto({ cleanUpBackups: true });
}
// Cancel
else if (confirm === ConfirmResult.CANCEL) {
return true; // veto
}
return false;
}
private noVeto(options: { cleanUpBackups: boolean }): boolean | Promise<boolean> {
if (!options.cleanUpBackups) {
return false;
}
if (this.lifecycleService.phase < LifecyclePhase.Restored) {
return false; // if editors have not restored, we are not up to speed with backups and thus should not clean them
}
return this.cleanupBackupsBeforeShutdown().then(() => false, () => false);
}
protected async cleanupBackupsBeforeShutdown(): Promise<void> {
if (this.environmentService.isExtensionDevelopment) {
return;
}
await this.backupFileService.discardAllWorkspaceBackups();
}
protected onFilesConfigurationChange(configuration: IFilesConfiguration): void {
const wasAutoSaveEnabled = (this.getAutoSaveMode() !== AutoSaveMode.OFF);
const autoSaveMode = (configuration && configuration.files && configuration.files.autoSave) || AutoSaveConfiguration.OFF;
this.autoSaveContext.set(autoSaveMode);
switch (autoSaveMode) {
case AutoSaveConfiguration.AFTER_DELAY:
this.configuredAutoSaveDelay = configuration && configuration.files && configuration.files.autoSaveDelay;
this.configuredAutoSaveOnFocusChange = false;
this.configuredAutoSaveOnWindowChange = false;
break;
case AutoSaveConfiguration.ON_FOCUS_CHANGE:
this.configuredAutoSaveDelay = undefined;
this.configuredAutoSaveOnFocusChange = true;
this.configuredAutoSaveOnWindowChange = false;
break;
case AutoSaveConfiguration.ON_WINDOW_CHANGE:
this.configuredAutoSaveDelay = undefined;
this.configuredAutoSaveOnFocusChange = false;
this.configuredAutoSaveOnWindowChange = true;
break;
default:
this.configuredAutoSaveDelay = undefined;
this.configuredAutoSaveOnFocusChange = false;
this.configuredAutoSaveOnWindowChange = false;
break;
}
// Emit as event
this._onAutoSaveConfigurationChange.fire(this.getAutoSaveConfiguration());
// save all dirty when enabling auto save
if (!wasAutoSaveEnabled && this.getAutoSaveMode() !== AutoSaveMode.OFF) {
this.saveAll();
}
// Check for change in files associations
const filesAssociation = configuration && configuration.files && configuration.files.associations;
if (!objects.equals(this.currentFilesAssociationConfig, filesAssociation)) {
this.currentFilesAssociationConfig = filesAssociation;
this._onFilesAssociationChange.fire();
}
// Hot exit
const hotExitMode = configuration && configuration.files && configuration.files.hotExit;
if (hotExitMode === HotExitConfiguration.OFF || hotExitMode === HotExitConfiguration.ON_EXIT_AND_WINDOW_CLOSE) {
this.configuredHotExit = hotExitMode;
} else {
this.configuredHotExit = HotExitConfiguration.ON_EXIT;
}
}
//#endregion
//#region primitives (read, create, move, delete, update)
async read(resource: URI, options?: IReadTextFileOptions): Promise<ITextFileContent> {
const content = await this.fileService.readFile(resource, options);
// in case of acceptTextOnly: true, we check the first
// chunk for possibly being binary by looking for 0-bytes
// we limit this check to the first 512 bytes
this.validateBinary(content.value, options);
return {
...content,
encoding: 'utf8',
value: content.value.toString()
};
}
async readStream(resource: URI, options?: IReadTextFileOptions): Promise<ITextFileStreamContent> {
const stream = await this.fileService.readFileStream(resource, options);
// in case of acceptTextOnly: true, we check the first
// chunk for possibly being binary by looking for 0-bytes
// we limit this check to the first 512 bytes
let checkedForBinary = false;
const throwOnBinary = (data: VSBuffer): Error | undefined => {
if (!checkedForBinary) {
checkedForBinary = true;
this.validateBinary(data, options);
}
return undefined;
};
return {
...stream,
encoding: 'utf8',
value: await createTextBufferFactoryFromStream(stream.value, undefined, options && options.acceptTextOnly ? throwOnBinary : undefined)
};
}
private validateBinary(buffer: VSBuffer, options?: IReadTextFileOptions): void {
if (!options || !options.acceptTextOnly) {
return; // no validation needed
}
// in case of acceptTextOnly: true, we check the first
// chunk for possibly being binary by looking for 0-bytes
// we limit this check to the first 512 bytes
for (let i = 0; i < buffer.byteLength && i < 512; i++) {
if (buffer.readUInt8(i) === 0) {
throw new TextFileOperationError(nls.localize('fileBinaryError', "File seems to be binary and cannot be opened as text"), TextFileOperationResult.FILE_IS_BINARY, options);
}
}
}
async create(resource: URI, value?: string | ITextSnapshot, options?: ICreateFileOptions): Promise<IFileStatWithMetadata> {
const stat = await this.doCreate(resource, value, options);
// If we had an existing model for the given resource, load
// it again to make sure it is up to date with the contents
// we just wrote into the underlying resource by calling
// revert()
const existingModel = this.models.get(resource);
if (existingModel && !existingModel.isDisposed()) {
await existingModel.revert();
}
return stat;
}
protected doCreate(resource: URI, value?: string | ITextSnapshot, options?: ICreateFileOptions): Promise<IFileStatWithMetadata> {
return this.fileService.createFile(resource, toBufferOrReadable(value), options);
}
async write(resource: URI, value: string | ITextSnapshot, options?: IWriteTextFileOptions): Promise<IFileStatWithMetadata> {
return this.fileService.writeFile(resource, toBufferOrReadable(value), options);
}
async delete(resource: URI, options?: { useTrash?: boolean, recursive?: boolean }): Promise<void> {
const dirtyFiles = this.getDirty().filter(dirty => isEqualOrParent(dirty, resource, !platform.isLinux /* ignorecase */));
await this.revertAll(dirtyFiles, { soft: true });
return this.fileService.del(resource, options);
}
async move(source: URI, target: URI, overwrite?: boolean): Promise<IFileStatWithMetadata> {
const waitForPromises: Promise<unknown>[] = [];
// Event
this._onWillMove.fire({
oldResource: source,
newResource: target,
waitUntil(promise: Promise<unknown>) {
waitForPromises.push(promise.then(undefined, errors.onUnexpectedError));
}
});
// prevent async waitUntil-calls
Object.freeze(waitForPromises);
await Promise.all(waitForPromises);
// Handle target models if existing (if target URI is a folder, this can be multiple)
const dirtyTargetModels = this.getDirtyFileModels().filter(model => isEqualOrParent(model.getResource(), target, false /* do not ignorecase, see https://github.com/Microsoft/vscode/issues/56384 */));
if (dirtyTargetModels.length) {
await this.revertAll(dirtyTargetModels.map(targetModel => targetModel.getResource()), { soft: true });
}
// Handle dirty source models if existing (if source URI is a folder, this can be multiple)
const dirtySourceModels = this.getDirtyFileModels().filter(model => isEqualOrParent(model.getResource(), source, !platform.isLinux /* ignorecase */));
const dirtyTargetModelUris: URI[] = [];
if (dirtySourceModels.length) {
await Promise.all(dirtySourceModels.map(async sourceModel => {
const sourceModelResource = sourceModel.getResource();
let targetModelResource: URI;
// If the source is the actual model, just use target as new resource
if (isEqual(sourceModelResource, source, !platform.isLinux /* ignorecase */)) {
targetModelResource = target;
}
// Otherwise a parent folder of the source is being moved, so we need
// to compute the target resource based on that
else {
targetModelResource = sourceModelResource.with({ path: joinPath(target, sourceModelResource.path.substr(source.path.length + 1)).path });
}
// Remember as dirty target model to load after the operation
dirtyTargetModelUris.push(targetModelResource);
// Backup dirty source model to the target resource it will become later
await sourceModel.backup(targetModelResource);
}));
}
// Soft revert the dirty source files if any
await this.revertAll(dirtySourceModels.map(dirtySourceModel => dirtySourceModel.getResource()), { soft: true });
// Rename to target
try {
const stat = await this.fileService.move(source, target, overwrite);
// Load models that were dirty before
await Promise.all(dirtyTargetModelUris.map(dirtyTargetModel => this.models.loadOrCreate(dirtyTargetModel)));
return stat;
} catch (error) {
// In case of an error, discard any dirty target backups that were made
await Promise.all(dirtyTargetModelUris.map(dirtyTargetModel => this.backupFileService.discardResourceBackup(dirtyTargetModel)));
throw error;
}
}
//#endregion
//#region save/revert
async save(resource: URI, options?: ISaveOptions): Promise<boolean> {
// Run a forced save if we detect the file is not dirty so that save participants can still run
if (options && options.force && this.fileService.canHandleResource(resource) && !this.isDirty(resource)) {
const model = this._models.get(resource);
if (model) {
options.reason = SaveReason.EXPLICIT;
await model.save(options);
return !model.isDirty();
}
}
const result = await this.saveAll([resource], options);
return result.results.length === 1 && !!result.results[0].success;
}
async confirmSave(resources?: URI[]): Promise<ConfirmResult> {
if (this.environmentService.isExtensionDevelopment) {
return ConfirmResult.DONT_SAVE; // no veto when we are in extension dev mode because we cannot assum we run interactive (e.g. tests)
}
const resourcesToConfirm = this.getDirty(resources);
if (resourcesToConfirm.length === 0) {
return ConfirmResult.DONT_SAVE;
}
const message = resourcesToConfirm.length === 1 ? nls.localize('saveChangesMessage', "Do you want to save the changes you made to {0}?", basename(resourcesToConfirm[0]))
: getConfirmMessage(nls.localize('saveChangesMessages', "Do you want to save the changes to the following {0} files?", resourcesToConfirm.length), resourcesToConfirm);
const buttons: string[] = [
resourcesToConfirm.length > 1 ? nls.localize({ key: 'saveAll', comment: ['&& denotes a mnemonic'] }, "&&Save All") : nls.localize({ key: 'save', comment: ['&& denotes a mnemonic'] }, "&&Save"),
nls.localize({ key: 'dontSave', comment: ['&& denotes a mnemonic'] }, "Do&&n't Save"),
nls.localize('cancel', "Cancel")
];
const index = await this.dialogService.show(Severity.Warning, message, buttons, {
cancelId: 2,
detail: nls.localize('saveChangesDetail', "Your changes will be lost if you don't save them.")
});
switch (index) {
case 0: return ConfirmResult.SAVE;
case 1: return ConfirmResult.DONT_SAVE;
default: return ConfirmResult.CANCEL;
}
}
async confirmOverwrite(resource: URI): Promise<boolean> {
const confirm: IConfirmation = {
message: nls.localize('confirmOverwrite', "'{0}' already exists. Do you want to replace it?", basename(resource)),
detail: nls.localize('irreversible', "A file or folder with the same name already exists in the folder {0}. Replacing it will overwrite its current contents.", basename(dirname(resource))),
primaryButton: nls.localize({ key: 'replaceButtonLabel', comment: ['&& denotes a mnemonic'] }, "&&Replace"),
type: 'warning'
};
return (await this.dialogService.confirm(confirm)).confirmed;
}
saveAll(includeUntitled?: boolean, options?: ISaveOptions): Promise<ITextFileOperationResult>;
saveAll(resources: URI[], options?: ISaveOptions): Promise<ITextFileOperationResult>;
saveAll(arg1?: boolean | URI[], options?: ISaveOptions): Promise<ITextFileOperationResult> {
// get all dirty
let toSave: URI[] = [];
if (Array.isArray(arg1)) {
toSave = this.getDirty(arg1);
} else {
toSave = this.getDirty();
}
// split up between files and untitled
const filesToSave: URI[] = [];
const untitledToSave: URI[] = [];
toSave.forEach(s => {
if ((Array.isArray(arg1) || arg1 === true /* includeUntitled */) && s.scheme === Schemas.untitled) {
untitledToSave.push(s);
} else {
filesToSave.push(s);
}
});
return this.doSaveAll(filesToSave, untitledToSave, options);
}
private async doSaveAll(fileResources: URI[], untitledResources: URI[], options?: ISaveOptions): Promise<ITextFileOperationResult> {
// Handle files first that can just be saved
const result = await this.doSaveAllFiles(fileResources, options);
// Preflight for untitled to handle cancellation from the dialog
const targetsForUntitled: URI[] = [];
for (const untitled of untitledResources) {
if (this.untitledEditorService.exists(untitled)) {
let targetUri: URI;
// Untitled with associated file path don't need to prompt
if (this.untitledEditorService.hasAssociatedFilePath(untitled)) {
targetUri = toLocalResource(untitled, this.environmentService.configuration.remoteAuthority);
}
// Otherwise ask user
else {
const targetPath = await this.promptForPath(untitled, this.suggestFileName(untitled));
if (!targetPath) {
return { results: [...fileResources, ...untitledResources].map(r => ({ source: r })) };
}
targetUri = targetPath;
}
targetsForUntitled.push(targetUri);
}
}
// Handle untitled
await Promise.all(targetsForUntitled.map(async (target, index) => {
const uri = await this.saveAs(untitledResources[index], target);
result.results.push({
source: untitledResources[index],
target: uri,
success: !!uri
});
}));
return result;
}
protected async promptForPath(resource: URI, defaultUri: URI): Promise<URI | undefined> {
// Help user to find a name for the file by opening it first
await this.editorService.openEditor({ resource, options: { revealIfOpened: true, preserveFocus: true, } });
return this.fileDialogService.pickFileToSave(this.getSaveDialogOptions(defaultUri));
}
private getSaveDialogOptions(defaultUri: URI): ISaveDialogOptions {
const options: ISaveDialogOptions = {
defaultUri,
title: nls.localize('saveAsTitle', "Save As")
};
// Filters are only enabled on Windows where they work properly
if (!platform.isWindows) {
return options;
}
interface IFilter { name: string; extensions: string[]; }
// Build the file filter by using our known languages
const ext: string | undefined = defaultUri ? extname(defaultUri) : undefined;
let matchingFilter: IFilter | undefined;
const filters: IFilter[] = coalesce(this.modeService.getRegisteredLanguageNames().map(languageName => {
const extensions = this.modeService.getExtensions(languageName);
if (!extensions || !extensions.length) {
return null;
}
const filter: IFilter = { name: languageName, extensions: extensions.slice(0, 10).map(e => trim(e, '.')) };
if (ext && extensions.indexOf(ext) >= 0) {
matchingFilter = filter;
return null; // matching filter will be added last to the top
}
return filter;
}));
// Filters are a bit weird on Windows, based on having a match or not:
// Match: we put the matching filter first so that it shows up selected and the all files last
// No match: we put the all files filter first
const allFilesFilter = { name: nls.localize('allFiles', "All Files"), extensions: ['*'] };
if (matchingFilter) {
filters.unshift(matchingFilter);
filters.unshift(allFilesFilter);
} else {
filters.unshift(allFilesFilter);
}
// Allow to save file without extension
filters.push({ name: nls.localize('noExt', "No Extension"), extensions: [''] });
options.filters = filters;
return options;
}
private async doSaveAllFiles(resources?: URI[], options: ISaveOptions = Object.create(null)): Promise<ITextFileOperationResult> {
const dirtyFileModels = this.getDirtyFileModels(Array.isArray(resources) ? resources : undefined /* Save All */)
.filter(model => {
if ((model.hasState(ModelState.CONFLICT) || model.hasState(ModelState.ERROR)) && (options.reason === SaveReason.AUTO || options.reason === SaveReason.FOCUS_CHANGE || options.reason === SaveReason.WINDOW_CHANGE)) {
return false; // if model is in save conflict or error, do not save unless save reason is explicit or not provided at all
}
return true;
});
const mapResourceToResult = new ResourceMap<IResult>();
dirtyFileModels.forEach(m => {
mapResourceToResult.set(m.getResource(), {
source: m.getResource()
});
});
await Promise.all(dirtyFileModels.map(async model => {
await model.save(options);
if (!model.isDirty()) {
const result = mapResourceToResult.get(model.getResource());
if (result) {
result.success = true;
}
}
}));
return { results: mapResourceToResult.values() };
}
private getFileModels(arg1?: URI | URI[]): ITextFileEditorModel[] {
if (Array.isArray(arg1)) {
const models: ITextFileEditorModel[] = [];
arg1.forEach(resource => {
models.push(...this.getFileModels(resource));
});
return models;
}
return this._models.getAll(arg1);
}
private getDirtyFileModels(resources?: URI | URI[]): ITextFileEditorModel[] {
return this.getFileModels(resources).filter(model => model.isDirty());
}
async saveAs(resource: URI, targetResource?: URI, options?: ISaveOptions): Promise<URI | undefined> {
// Get to target resource
if (!targetResource) {
let dialogPath = resource;
if (resource.scheme === Schemas.untitled) {
dialogPath = this.suggestFileName(resource);
}
targetResource = await this.promptForPath(resource, dialogPath);
}
if (!targetResource) {
return; // user canceled
}
// Just save if target is same as models own resource
if (resource.toString() === targetResource.toString()) {
await this.save(resource, options);
return resource;
}
// Do it
return this.doSaveAs(resource, targetResource, options);
}
private async doSaveAs(resource: URI, target: URI, options?: ISaveOptions): Promise<URI> {
// Retrieve text model from provided resource if any
let model: ITextFileEditorModel | UntitledEditorModel | undefined;
if (this.fileService.canHandleResource(resource)) {
model = this._models.get(resource);
} else if (resource.scheme === Schemas.untitled && this.untitledEditorService.exists(resource)) {
model = await this.untitledEditorService.loadOrCreate({ resource });
}
// We have a model: Use it (can be null e.g. if this file is binary and not a text file or was never opened before)
let result: boolean;
if (model) {
result = await this.doSaveTextFileAs(model, resource, target, options);
}
// Otherwise we can only copy
else {
await this.fileService.copy(resource, target);
result = true;
}
// Return early if the operation was not running
if (!result) {
return target;
}
// Revert the source
await this.revert(resource);
return target;
}
private async doSaveTextFileAs(sourceModel: ITextFileEditorModel | UntitledEditorModel, resource: URI, target: URI, options?: ISaveOptions): Promise<boolean> {
// Prefer an existing model if it is already loaded for the given target resource
let targetExists: boolean = false;
let targetModel = this.models.get(target);
if (targetModel && targetModel.isResolved()) {
targetExists = true;
}
// Otherwise create the target file empty if it does not exist already and resolve it from there
else {
targetExists = await this.fileService.exists(target);
// create target model adhoc if file does not exist yet
if (!targetExists) {
await this.create(target, '');
}
targetModel = await this.models.loadOrCreate(target);
}
try {
// Confirm to overwrite if we have an untitled file with associated file where
// the file actually exists on disk and we are instructed to save to that file
// path. This can happen if the file was created after the untitled file was opened.
// See https://github.com/Microsoft/vscode/issues/67946
let write: boolean;
if (sourceModel instanceof UntitledEditorModel && sourceModel.hasAssociatedFilePath && targetExists && isEqual(target, toLocalResource(sourceModel.getResource(), this.environmentService.configuration.remoteAuthority))) {
write = await this.confirmOverwrite(target);
} else {
write = true;
}
if (!write) {
return false;
}
// take over encoding, mode and model value from source model
targetModel.updatePreferredEncoding(sourceModel.getEncoding());
if (sourceModel.isResolved() && targetModel.isResolved()) {
this.modelService.updateModel(targetModel.textEditorModel, createTextBufferFactoryFromSnapshot(sourceModel.createSnapshot()));
const mode = sourceModel.textEditorModel.getLanguageIdentifier();
if (mode.language !== PLAINTEXT_MODE_ID) {
targetModel.textEditorModel.setMode(mode); // only use if more specific than plain/text
}
}
// save model
await targetModel.save(options);
return true;
} catch (error) {
// binary model: delete the file and run the operation again
if (
(<TextFileOperationError>error).textFileOperationResult === TextFileOperationResult.FILE_IS_BINARY ||
(<FileOperationError>error).fileOperationResult === FileOperationResult.FILE_TOO_LARGE
) {
await this.fileService.del(target);
return this.doSaveTextFileAs(sourceModel, resource, target, options);
}
throw error;
}
}
private suggestFileName(untitledResource: URI): URI {
const untitledFileName = this.untitledEditorService.suggestFileName(untitledResource);
const remoteAuthority = this.environmentService.configuration.remoteAuthority;
const schemeFilter = remoteAuthority ? Schemas.vscodeRemote : Schemas.file;
const lastActiveFile = this.historyService.getLastActiveFile(schemeFilter);
if (lastActiveFile) {
const lastDir = dirname(lastActiveFile);
return joinPath(lastDir, untitledFileName);
}
const lastActiveFolder = this.historyService.getLastActiveWorkspaceRoot(schemeFilter);
if (lastActiveFolder) {
return joinPath(lastActiveFolder, untitledFileName);
}
return schemeFilter === Schemas.file ? URI.file(untitledFileName) : URI.from({ scheme: schemeFilter, authority: remoteAuthority, path: posix.sep + untitledFileName });
}
async revert(resource: URI, options?: IRevertOptions): Promise<boolean> {
const result = await this.revertAll([resource], options);
return result.results.length === 1 && !!result.results[0].success;
}
async revertAll(resources?: URI[], options?: IRevertOptions): Promise<ITextFileOperationResult> {
// Revert files first
const revertOperationResult = await this.doRevertAllFiles(resources, options);
// Revert untitled
const untitledReverted = this.untitledEditorService.revertAll(resources);
untitledReverted.forEach(untitled => revertOperationResult.results.push({ source: untitled, success: true }));
return revertOperationResult;
}
private async doRevertAllFiles(resources?: URI[], options?: IRevertOptions): Promise<ITextFileOperationResult> {
const fileModels = options && options.force ? this.getFileModels(resources) : this.getDirtyFileModels(resources);
const mapResourceToResult = new ResourceMap<IResult>();
fileModels.forEach(m => {
mapResourceToResult.set(m.getResource(), {
source: m.getResource()
});
});
await Promise.all(fileModels.map(async model => {
try {
await model.revert(options && options.soft);
if (!model.isDirty()) {
const result = mapResourceToResult.get(model.getResource());
if (result) {
result.success = true;
}
}
} catch (error) {
// FileNotFound means the file got deleted meanwhile, so still record as successful revert
if ((<FileOperationError>error).fileOperationResult === FileOperationResult.FILE_NOT_FOUND) {
const result = mapResourceToResult.get(model.getResource());
if (result) {
result.success = true;
}
}
// Otherwise bubble up the error
else {
throw error;
}
}
}));
return { results: mapResourceToResult.values() };
}
getDirty(resources?: URI[]): URI[] {
// Collect files
const dirty = this.getDirtyFileModels(resources).map(m => m.getResource());
// Add untitled ones
dirty.push(...this.untitledEditorService.getDirty(resources));
return dirty;
}
isDirty(resource?: URI): boolean {
// Check for dirty file
if (this._models.getAll(resource).some(model => model.isDirty())) {
return true;
}
// Check for dirty untitled
return this.untitledEditorService.getDirty().some(dirty => !resource || dirty.toString() === resource.toString());
}
//#endregion
//#region config
getAutoSaveMode(): AutoSaveMode {
if (this.configuredAutoSaveOnFocusChange) {
return AutoSaveMode.ON_FOCUS_CHANGE;
}
if (this.configuredAutoSaveOnWindowChange) {
return AutoSaveMode.ON_WINDOW_CHANGE;
}
if (this.configuredAutoSaveDelay && this.configuredAutoSaveDelay > 0) {
return this.configuredAutoSaveDelay <= 1000 ? AutoSaveMode.AFTER_SHORT_DELAY : AutoSaveMode.AFTER_LONG_DELAY;
}
return AutoSaveMode.OFF;
}
getAutoSaveConfiguration(): IAutoSaveConfiguration {
return {
autoSaveDelay: this.configuredAutoSaveDelay && this.configuredAutoSaveDelay > 0 ? this.configuredAutoSaveDelay : undefined,
autoSaveFocusChange: this.configuredAutoSaveOnFocusChange,
autoSaveApplicationChange: this.configuredAutoSaveOnWindowChange
};
}
get isHotExitEnabled(): boolean {
return !this.environmentService.isExtensionDevelopment && this.configuredHotExit !== HotExitConfiguration.OFF;
}
//#endregion
dispose(): void {
// Clear all caches
this._models.clear();
super.dispose();
}
} | src/vs/workbench/services/textfile/common/textFileService.ts | 1 | https://github.com/microsoft/vscode/commit/985de26b3446636f86e2bb2b14dbeb9ec1e33207 | [
0.7110701203346252,
0.007093649357557297,
0.00015999871538951993,
0.00017244491027668118,
0.0697040855884552
] |
{
"id": 10,
"code_window": [
"\t\t// Help user to find a name for the file by opening it first\n",
"\t\tawait this.editorService.openEditor({ resource, options: { revealIfOpened: true, preserveFocus: true, } });\n",
"\n",
"\t\treturn this.fileDialogService.pickFileToSave(this.getSaveDialogOptions(defaultUri));\n",
"\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
"\t\treturn this.fileDialogService.pickFileToSave(this.getSaveDialogOptions(defaultUri, availableFileSystems));\n"
],
"file_path": "src/vs/workbench/services/textfile/common/textFileService.ts",
"type": "replace",
"edit_start_line_idx": 655
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { writeFile } from 'vs/base/node/pfs';
import product from 'vs/platform/product/node/product';
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
import { Registry } from 'vs/platform/registry/common/platform';
import { IConfigurationNode, IConfigurationRegistry, Extensions, IConfigurationPropertySchema } from 'vs/platform/configuration/common/configurationRegistry';
import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions';
import { ICommandService } from 'vs/platform/commands/common/commands';
interface IExportedConfigurationNode {
name: string;
description: string;
default: any;
type?: string | string[];
enum?: any[];
enumDescriptions?: string[];
}
interface IConfigurationExport {
settings: IExportedConfigurationNode[];
buildTime: number;
commit?: string;
buildNumber?: number;
}
export class DefaultConfigurationExportHelper {
constructor(
@IEnvironmentService environmentService: IEnvironmentService,
@IExtensionService private readonly extensionService: IExtensionService,
@ICommandService private readonly commandService: ICommandService) {
if (environmentService.args['export-default-configuration']) {
this.writeConfigModelAndQuit(environmentService.args['export-default-configuration']);
}
}
private writeConfigModelAndQuit(targetPath: string): Promise<void> {
return Promise.resolve(this.extensionService.whenInstalledExtensionsRegistered())
.then(() => this.writeConfigModel(targetPath))
.then(() => this.commandService.executeCommand('workbench.action.quit'))
.then(() => { });
}
private writeConfigModel(targetPath: string): Promise<void> {
const config = this.getConfigModel();
const resultString = JSON.stringify(config, undefined, ' ');
return writeFile(targetPath, resultString);
}
private getConfigModel(): IConfigurationExport {
const configRegistry = Registry.as<IConfigurationRegistry>(Extensions.Configuration);
const configurations = configRegistry.getConfigurations().slice();
const settings: IExportedConfigurationNode[] = [];
const processProperty = (name: string, prop: IConfigurationPropertySchema) => {
const propDetails: IExportedConfigurationNode = {
name,
description: prop.description || prop.markdownDescription || '',
default: prop.default,
type: prop.type
};
if (prop.enum) {
propDetails.enum = prop.enum;
}
if (prop.enumDescriptions || prop.markdownEnumDescriptions) {
propDetails.enumDescriptions = prop.enumDescriptions || prop.markdownEnumDescriptions;
}
settings.push(propDetails);
};
const processConfig = (config: IConfigurationNode) => {
if (config.properties) {
for (let name in config.properties) {
processProperty(name, config.properties[name]);
}
}
if (config.allOf) {
config.allOf.forEach(processConfig);
}
};
configurations.forEach(processConfig);
const excludedProps = configRegistry.getExcludedConfigurationProperties();
for (let name in excludedProps) {
processProperty(name, excludedProps[name]);
}
const result: IConfigurationExport = {
settings: settings.sort((a, b) => a.name.localeCompare(b.name)),
buildTime: Date.now(),
commit: product.commit,
buildNumber: product.settingsSearchBuildId
};
return result;
}
}
| src/vs/workbench/services/configuration/node/configurationExportHelper.ts | 0 | https://github.com/microsoft/vscode/commit/985de26b3446636f86e2bb2b14dbeb9ec1e33207 | [
0.0001837644085753709,
0.00017576578829903156,
0.0001718888815958053,
0.00017578963888809085,
0.0000033039132176782005
] |
{
"id": 10,
"code_window": [
"\t\t// Help user to find a name for the file by opening it first\n",
"\t\tawait this.editorService.openEditor({ resource, options: { revealIfOpened: true, preserveFocus: true, } });\n",
"\n",
"\t\treturn this.fileDialogService.pickFileToSave(this.getSaveDialogOptions(defaultUri));\n",
"\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
"\t\treturn this.fileDialogService.pickFileToSave(this.getSaveDialogOptions(defaultUri, availableFileSystems));\n"
],
"file_path": "src/vs/workbench/services/textfile/common/textFileService.ts",
"type": "replace",
"edit_start_line_idx": 655
} | <!DOCTYPE html>
<html>
<head id='headID'>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>Strada </title>
<link href="site.css" rel="stylesheet" type="text/css" />
<script src="jquery-1.4.1.js"></script>
<script src="../compiler/dtree.js" type="text/javascript"></script>
<script src="../compiler/typescript.js" type="text/javascript"></script>
<script type="text/javascript">
// Compile strada source into resulting javascript
function compile(prog, libText) {
var outfile = {
source: "",
Write: function (s) { this.source += s; },
WriteLine: function (s) { this.source += s + "\r"; },
}
var parseErrors = []
var compiler=new Tools.TypeScriptCompiler(outfile,true);
compiler.setErrorCallback(function(start,len, message) { parseErrors.push({start:start, len:len, message:message}); });
compiler.addUnit(libText,"lib.ts");
compiler.addUnit(prog,"input.ts");
compiler.typeCheck();
compiler.emit();
if(parseErrors.length > 0 ) {
//throw new Error(parseErrors);
}
while(outfile.source[0] == '/' && outfile.source[1] == '/' && outfile.source[2] == ' ') {
outfile.source = outfile.source.slice(outfile.source.indexOf('\r')+1);
}
var errorPrefix = "";
for(var i = 0;i<parseErrors.length;i++) {
errorPrefix += "// Error: (" + parseErrors[i].start + "," + parseErrors[i].len + ") " + parseErrors[i].message + "\r";
}
return errorPrefix + outfile.source;
}
</script>
<script type="text/javascript">
var libText = "";
$.get("../compiler/lib.ts", function(newLibText) {
libText = newLibText;
});
// execute the javascript in the compiledOutput pane
function execute() {
$('#compilation').text("Running...");
var txt = $('#compiledOutput').val();
var res;
try {
var ret = eval(txt);
res = "Ran successfully!";
} catch(e) {
res = "Exception thrown: " + e;
}
$('#compilation').text(String(res));
}
// recompile the stradaSrc and populate the compiledOutput pane
function srcUpdated() {
var newText = $('#stradaSrc').val();
var compiledSource;
try {
compiledSource = compile(newText, libText);
} catch (e) {
compiledSource = "//Parse error"
for(var i in e)
compiledSource += "\r// " + e[i];
}
$('#compiledOutput').val(compiledSource);
}
// Populate the stradaSrc pane with one of the built in samples
function exampleSelectionChanged() {
var examples = document.getElementById('examples');
var selectedExample = examples.options[examples.selectedIndex].value;
if (selectedExample != "") {
$.get('examples/' + selectedExample, function (srcText) {
$('#stradaSrc').val(srcText);
setTimeout(srcUpdated,100);
}, function (err) {
console.log(err);
});
}
}
</script>
</head>
<body>
<h1>TypeScript</h1>
<br />
<select id="examples" onchange='exampleSelectionChanged()'>
<option value="">Select...</option>
<option value="small.ts">Small</option>
<option value="employee.ts">Employees</option>
<option value="conway.ts">Conway Game of Life</option>
<option value="typescript.ts">TypeScript Compiler</option>
</select>
<div>
<textarea id='stradaSrc' rows='40' cols='80' onchange='srcUpdated()' onkeyup='srcUpdated()' spellcheck="false">
//Type your TypeScript here...
</textarea>
<textarea id='compiledOutput' rows='40' cols='80' spellcheck="false">
//Compiled code will show up here...
</textarea>
<br />
<button onclick='execute()'/>Run</button>
<div id='compilation'>Press 'run' to execute code...</div>
<div id='results'>...write your results into #results...</div>
</div>
<div id='bod' style='display:none'></div>
</body>
</html>
| src/vs/workbench/services/files/test/node/fixtures/service/index.html | 0 | https://github.com/microsoft/vscode/commit/985de26b3446636f86e2bb2b14dbeb9ec1e33207 | [
0.00017833504534792155,
0.00017491217295173556,
0.0001701315923128277,
0.00017499610839877278,
0.0000025199026367772603
] |
{
"id": 10,
"code_window": [
"\t\t// Help user to find a name for the file by opening it first\n",
"\t\tawait this.editorService.openEditor({ resource, options: { revealIfOpened: true, preserveFocus: true, } });\n",
"\n",
"\t\treturn this.fileDialogService.pickFileToSave(this.getSaveDialogOptions(defaultUri));\n",
"\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
"\t\treturn this.fileDialogService.pickFileToSave(this.getSaveDialogOptions(defaultUri, availableFileSystems));\n"
],
"file_path": "src/vs/workbench/services/textfile/common/textFileService.ts",
"type": "replace",
"edit_start_line_idx": 655
} | {
"name": "yaml",
"displayName": "%displayName%",
"description": "%description%",
"version": "1.0.0",
"publisher": "vscode",
"license": "MIT",
"engines": {
"vscode": "*"
},
"scripts": {
"update-grammar": "node ../../build/npm/update-grammar.js textmate/yaml.tmbundle Syntaxes/YAML.tmLanguage ./syntaxes/yaml.tmLanguage.json"
},
"contributes": {
"languages": [
{
"id": "yaml",
"aliases": [
"YAML",
"yaml"
],
"extensions": [
".yml",
".eyaml",
".eyml",
".yaml"
],
"firstLine": "^#cloud-config",
"configuration": "./language-configuration.json"
}
],
"grammars": [
{
"language": "yaml",
"scopeName": "source.yaml",
"path": "./syntaxes/yaml.tmLanguage.json"
}
],
"configurationDefaults": {
"[yaml]": {
"editor.insertSpaces": true,
"editor.tabSize": 2,
"editor.autoIndent": false
}
}
}
} | extensions/yaml/package.json | 0 | https://github.com/microsoft/vscode/commit/985de26b3446636f86e2bb2b14dbeb9ec1e33207 | [
0.00017732125706970692,
0.00017514298087917268,
0.00016959758067969233,
0.00017659268632996827,
0.0000028835379453084897
] |
{
"id": 11,
"code_window": [
"\t}\n",
"\n",
"\tprivate getSaveDialogOptions(defaultUri: URI): ISaveDialogOptions {\n",
"\t\tconst options: ISaveDialogOptions = {\n",
"\t\t\tdefaultUri,\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
"\tprivate getSaveDialogOptions(defaultUri: URI, availableFileSystems?: string[]): ISaveDialogOptions {\n"
],
"file_path": "src/vs/workbench/services/textfile/common/textFileService.ts",
"type": "replace",
"edit_start_line_idx": 658
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as nls from 'vs/nls';
import { URI } from 'vs/base/common/uri';
import * as errors from 'vs/base/common/errors';
import * as objects from 'vs/base/common/objects';
import { Event, Emitter } from 'vs/base/common/event';
import * as platform from 'vs/base/common/platform';
import { IWindowsService } from 'vs/platform/windows/common/windows';
import { IBackupFileService } from 'vs/workbench/services/backup/common/backup';
import { IResult, ITextFileOperationResult, ITextFileService, ITextFileStreamContent, IAutoSaveConfiguration, AutoSaveMode, SaveReason, ITextFileEditorModelManager, ITextFileEditorModel, ModelState, ISaveOptions, AutoSaveContext, IWillMoveEvent, ITextFileContent, IResourceEncodings, IReadTextFileOptions, IWriteTextFileOptions, toBufferOrReadable, TextFileOperationError, TextFileOperationResult } from 'vs/workbench/services/textfile/common/textfiles';
import { ConfirmResult, IRevertOptions } from 'vs/workbench/common/editor';
import { ILifecycleService, ShutdownReason, LifecyclePhase } from 'vs/platform/lifecycle/common/lifecycle';
import { IWorkspaceContextService, WorkbenchState } from 'vs/platform/workspace/common/workspace';
import { IFileService, IFilesConfiguration, FileOperationError, FileOperationResult, AutoSaveConfiguration, HotExitConfiguration, IFileStatWithMetadata, ICreateFileOptions } from 'vs/platform/files/common/files';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { Disposable } from 'vs/base/common/lifecycle';
import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService';
import { IUntitledEditorService } from 'vs/workbench/services/untitled/common/untitledEditorService';
import { UntitledEditorModel } from 'vs/workbench/common/editor/untitledEditorModel';
import { TextFileEditorModelManager } from 'vs/workbench/services/textfile/common/textFileEditorModelManager';
import { IInstantiationService, ServiceIdentifier } from 'vs/platform/instantiation/common/instantiation';
import { ResourceMap } from 'vs/base/common/map';
import { Schemas } from 'vs/base/common/network';
import { IHistoryService } from 'vs/workbench/services/history/common/history';
import { IContextKey, IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { createTextBufferFactoryFromSnapshot, createTextBufferFactoryFromStream } from 'vs/editor/common/model/textModel';
import { IModelService } from 'vs/editor/common/services/modelService';
import { INotificationService, Severity } from 'vs/platform/notification/common/notification';
import { isEqualOrParent, isEqual, joinPath, dirname, extname, basename, toLocalResource } from 'vs/base/common/resources';
import { posix } from 'vs/base/common/path';
import { getConfirmMessage, IDialogService, IFileDialogService, ISaveDialogOptions, IConfirmation } from 'vs/platform/dialogs/common/dialogs';
import { IModeService } from 'vs/editor/common/services/modeService';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { coalesce } from 'vs/base/common/arrays';
import { trim } from 'vs/base/common/strings';
import { VSBuffer } from 'vs/base/common/buffer';
import { ITextSnapshot } from 'vs/editor/common/model';
import { ITextResourceConfigurationService } from 'vs/editor/common/services/resourceConfiguration';
import { PLAINTEXT_MODE_ID } from 'vs/editor/common/modes/modesRegistry';
/**
* The workbench file service implementation implements the raw file service spec and adds additional methods on top.
*/
export abstract class TextFileService extends Disposable implements ITextFileService {
_serviceBrand: ServiceIdentifier<any>;
private readonly _onAutoSaveConfigurationChange: Emitter<IAutoSaveConfiguration> = this._register(new Emitter<IAutoSaveConfiguration>());
get onAutoSaveConfigurationChange(): Event<IAutoSaveConfiguration> { return this._onAutoSaveConfigurationChange.event; }
private readonly _onFilesAssociationChange: Emitter<void> = this._register(new Emitter<void>());
get onFilesAssociationChange(): Event<void> { return this._onFilesAssociationChange.event; }
private readonly _onWillMove = this._register(new Emitter<IWillMoveEvent>());
get onWillMove(): Event<IWillMoveEvent> { return this._onWillMove.event; }
private _models: TextFileEditorModelManager;
get models(): ITextFileEditorModelManager { return this._models; }
abstract get encoding(): IResourceEncodings;
private currentFilesAssociationConfig: { [key: string]: string; };
private configuredAutoSaveDelay?: number;
private configuredAutoSaveOnFocusChange: boolean;
private configuredAutoSaveOnWindowChange: boolean;
private configuredHotExit: string;
private autoSaveContext: IContextKey<string>;
constructor(
@IWorkspaceContextService private readonly contextService: IWorkspaceContextService,
@IFileService protected readonly fileService: IFileService,
@IUntitledEditorService private readonly untitledEditorService: IUntitledEditorService,
@ILifecycleService private readonly lifecycleService: ILifecycleService,
@IInstantiationService protected instantiationService: IInstantiationService,
@IConfigurationService private readonly configurationService: IConfigurationService,
@IModeService private readonly modeService: IModeService,
@IModelService private readonly modelService: IModelService,
@IWorkbenchEnvironmentService protected readonly environmentService: IWorkbenchEnvironmentService,
@INotificationService private readonly notificationService: INotificationService,
@IBackupFileService private readonly backupFileService: IBackupFileService,
@IWindowsService private readonly windowsService: IWindowsService,
@IHistoryService private readonly historyService: IHistoryService,
@IContextKeyService contextKeyService: IContextKeyService,
@IDialogService private readonly dialogService: IDialogService,
@IFileDialogService private readonly fileDialogService: IFileDialogService,
@IEditorService private readonly editorService: IEditorService,
@ITextResourceConfigurationService protected readonly textResourceConfigurationService: ITextResourceConfigurationService
) {
super();
this._models = this._register(instantiationService.createInstance(TextFileEditorModelManager));
this.autoSaveContext = AutoSaveContext.bindTo(contextKeyService);
const configuration = configurationService.getValue<IFilesConfiguration>();
this.currentFilesAssociationConfig = configuration && configuration.files && configuration.files.associations;
this.onFilesConfigurationChange(configuration);
this.registerListeners();
}
//#region event handling
private registerListeners(): void {
// Lifecycle
this.lifecycleService.onBeforeShutdown(event => event.veto(this.beforeShutdown(event.reason)));
this.lifecycleService.onShutdown(this.dispose, this);
// Files configuration changes
this._register(this.configurationService.onDidChangeConfiguration(e => {
if (e.affectsConfiguration('files')) {
this.onFilesConfigurationChange(this.configurationService.getValue<IFilesConfiguration>());
}
}));
}
private beforeShutdown(reason: ShutdownReason): boolean | Promise<boolean> {
// Dirty files need treatment on shutdown
const dirty = this.getDirty();
if (dirty.length) {
// If auto save is enabled, save all files and then check again for dirty files
// We DO NOT run any save participant if we are in the shutdown phase for performance reasons
if (this.getAutoSaveMode() !== AutoSaveMode.OFF) {
return this.saveAll(false /* files only */, { skipSaveParticipants: true }).then(() => {
// If we still have dirty files, we either have untitled ones or files that cannot be saved
const remainingDirty = this.getDirty();
if (remainingDirty.length) {
return this.handleDirtyBeforeShutdown(remainingDirty, reason);
}
return false;
});
}
// Auto save is not enabled
return this.handleDirtyBeforeShutdown(dirty, reason);
}
// No dirty files: no veto
return this.noVeto({ cleanUpBackups: true });
}
private handleDirtyBeforeShutdown(dirty: URI[], reason: ShutdownReason): boolean | Promise<boolean> {
// If hot exit is enabled, backup dirty files and allow to exit without confirmation
if (this.isHotExitEnabled) {
return this.backupBeforeShutdown(dirty, this.models, reason).then(didBackup => {
if (didBackup) {
return this.noVeto({ cleanUpBackups: false }); // no veto and no backup cleanup (since backup was successful)
}
// since a backup did not happen, we have to confirm for the dirty files now
return this.confirmBeforeShutdown();
}, errors => {
const firstError = errors[0];
this.notificationService.error(nls.localize('files.backup.failSave', "Files that are dirty could not be written to the backup location (Error: {0}). Try saving your files first and then exit.", firstError.message));
return true; // veto, the backups failed
});
}
// Otherwise just confirm from the user what to do with the dirty files
return this.confirmBeforeShutdown();
}
private async backupBeforeShutdown(dirtyToBackup: URI[], textFileEditorModelManager: ITextFileEditorModelManager, reason: ShutdownReason): Promise<boolean> {
const windowCount = await this.windowsService.getWindowCount();
// When quit is requested skip the confirm callback and attempt to backup all workspaces.
// When quit is not requested the confirm callback should be shown when the window being
// closed is the only VS Code window open, except for on Mac where hot exit is only
// ever activated when quit is requested.
let doBackup: boolean | undefined;
switch (reason) {
case ShutdownReason.CLOSE:
if (this.contextService.getWorkbenchState() !== WorkbenchState.EMPTY && this.configuredHotExit === HotExitConfiguration.ON_EXIT_AND_WINDOW_CLOSE) {
doBackup = true; // backup if a folder is open and onExitAndWindowClose is configured
} else if (windowCount > 1 || platform.isMacintosh) {
doBackup = false; // do not backup if a window is closed that does not cause quitting of the application
} else {
doBackup = true; // backup if last window is closed on win/linux where the application quits right after
}
break;
case ShutdownReason.QUIT:
doBackup = true; // backup because next start we restore all backups
break;
case ShutdownReason.RELOAD:
doBackup = true; // backup because after window reload, backups restore
break;
case ShutdownReason.LOAD:
if (this.contextService.getWorkbenchState() !== WorkbenchState.EMPTY && this.configuredHotExit === HotExitConfiguration.ON_EXIT_AND_WINDOW_CLOSE) {
doBackup = true; // backup if a folder is open and onExitAndWindowClose is configured
} else {
doBackup = false; // do not backup because we are switching contexts
}
break;
}
if (!doBackup) {
return false;
}
await this.backupAll(dirtyToBackup, textFileEditorModelManager);
return true;
}
private backupAll(dirtyToBackup: URI[], textFileEditorModelManager: ITextFileEditorModelManager): Promise<void> {
// split up between files and untitled
const filesToBackup: ITextFileEditorModel[] = [];
const untitledToBackup: URI[] = [];
dirtyToBackup.forEach(s => {
if (this.fileService.canHandleResource(s)) {
const model = textFileEditorModelManager.get(s);
if (model) {
filesToBackup.push(model);
}
} else if (s.scheme === Schemas.untitled) {
untitledToBackup.push(s);
}
});
return this.doBackupAll(filesToBackup, untitledToBackup);
}
private async doBackupAll(dirtyFileModels: ITextFileEditorModel[], untitledResources: URI[]): Promise<void> {
// Handle file resources first
await Promise.all(dirtyFileModels.map(model => model.backup()));
// Handle untitled resources
await Promise.all(untitledResources
.filter(untitled => this.untitledEditorService.exists(untitled))
.map(async untitled => (await this.untitledEditorService.loadOrCreate({ resource: untitled })).backup()));
}
private async confirmBeforeShutdown(): Promise<boolean> {
const confirm = await this.confirmSave();
// Save
if (confirm === ConfirmResult.SAVE) {
const result = await this.saveAll(true /* includeUntitled */, { skipSaveParticipants: true });
if (result.results.some(r => !r.success)) {
return true; // veto if some saves failed
}
return this.noVeto({ cleanUpBackups: true });
}
// Don't Save
else if (confirm === ConfirmResult.DONT_SAVE) {
// Make sure to revert untitled so that they do not restore
// see https://github.com/Microsoft/vscode/issues/29572
this.untitledEditorService.revertAll();
return this.noVeto({ cleanUpBackups: true });
}
// Cancel
else if (confirm === ConfirmResult.CANCEL) {
return true; // veto
}
return false;
}
private noVeto(options: { cleanUpBackups: boolean }): boolean | Promise<boolean> {
if (!options.cleanUpBackups) {
return false;
}
if (this.lifecycleService.phase < LifecyclePhase.Restored) {
return false; // if editors have not restored, we are not up to speed with backups and thus should not clean them
}
return this.cleanupBackupsBeforeShutdown().then(() => false, () => false);
}
protected async cleanupBackupsBeforeShutdown(): Promise<void> {
if (this.environmentService.isExtensionDevelopment) {
return;
}
await this.backupFileService.discardAllWorkspaceBackups();
}
protected onFilesConfigurationChange(configuration: IFilesConfiguration): void {
const wasAutoSaveEnabled = (this.getAutoSaveMode() !== AutoSaveMode.OFF);
const autoSaveMode = (configuration && configuration.files && configuration.files.autoSave) || AutoSaveConfiguration.OFF;
this.autoSaveContext.set(autoSaveMode);
switch (autoSaveMode) {
case AutoSaveConfiguration.AFTER_DELAY:
this.configuredAutoSaveDelay = configuration && configuration.files && configuration.files.autoSaveDelay;
this.configuredAutoSaveOnFocusChange = false;
this.configuredAutoSaveOnWindowChange = false;
break;
case AutoSaveConfiguration.ON_FOCUS_CHANGE:
this.configuredAutoSaveDelay = undefined;
this.configuredAutoSaveOnFocusChange = true;
this.configuredAutoSaveOnWindowChange = false;
break;
case AutoSaveConfiguration.ON_WINDOW_CHANGE:
this.configuredAutoSaveDelay = undefined;
this.configuredAutoSaveOnFocusChange = false;
this.configuredAutoSaveOnWindowChange = true;
break;
default:
this.configuredAutoSaveDelay = undefined;
this.configuredAutoSaveOnFocusChange = false;
this.configuredAutoSaveOnWindowChange = false;
break;
}
// Emit as event
this._onAutoSaveConfigurationChange.fire(this.getAutoSaveConfiguration());
// save all dirty when enabling auto save
if (!wasAutoSaveEnabled && this.getAutoSaveMode() !== AutoSaveMode.OFF) {
this.saveAll();
}
// Check for change in files associations
const filesAssociation = configuration && configuration.files && configuration.files.associations;
if (!objects.equals(this.currentFilesAssociationConfig, filesAssociation)) {
this.currentFilesAssociationConfig = filesAssociation;
this._onFilesAssociationChange.fire();
}
// Hot exit
const hotExitMode = configuration && configuration.files && configuration.files.hotExit;
if (hotExitMode === HotExitConfiguration.OFF || hotExitMode === HotExitConfiguration.ON_EXIT_AND_WINDOW_CLOSE) {
this.configuredHotExit = hotExitMode;
} else {
this.configuredHotExit = HotExitConfiguration.ON_EXIT;
}
}
//#endregion
//#region primitives (read, create, move, delete, update)
async read(resource: URI, options?: IReadTextFileOptions): Promise<ITextFileContent> {
const content = await this.fileService.readFile(resource, options);
// in case of acceptTextOnly: true, we check the first
// chunk for possibly being binary by looking for 0-bytes
// we limit this check to the first 512 bytes
this.validateBinary(content.value, options);
return {
...content,
encoding: 'utf8',
value: content.value.toString()
};
}
async readStream(resource: URI, options?: IReadTextFileOptions): Promise<ITextFileStreamContent> {
const stream = await this.fileService.readFileStream(resource, options);
// in case of acceptTextOnly: true, we check the first
// chunk for possibly being binary by looking for 0-bytes
// we limit this check to the first 512 bytes
let checkedForBinary = false;
const throwOnBinary = (data: VSBuffer): Error | undefined => {
if (!checkedForBinary) {
checkedForBinary = true;
this.validateBinary(data, options);
}
return undefined;
};
return {
...stream,
encoding: 'utf8',
value: await createTextBufferFactoryFromStream(stream.value, undefined, options && options.acceptTextOnly ? throwOnBinary : undefined)
};
}
private validateBinary(buffer: VSBuffer, options?: IReadTextFileOptions): void {
if (!options || !options.acceptTextOnly) {
return; // no validation needed
}
// in case of acceptTextOnly: true, we check the first
// chunk for possibly being binary by looking for 0-bytes
// we limit this check to the first 512 bytes
for (let i = 0; i < buffer.byteLength && i < 512; i++) {
if (buffer.readUInt8(i) === 0) {
throw new TextFileOperationError(nls.localize('fileBinaryError', "File seems to be binary and cannot be opened as text"), TextFileOperationResult.FILE_IS_BINARY, options);
}
}
}
async create(resource: URI, value?: string | ITextSnapshot, options?: ICreateFileOptions): Promise<IFileStatWithMetadata> {
const stat = await this.doCreate(resource, value, options);
// If we had an existing model for the given resource, load
// it again to make sure it is up to date with the contents
// we just wrote into the underlying resource by calling
// revert()
const existingModel = this.models.get(resource);
if (existingModel && !existingModel.isDisposed()) {
await existingModel.revert();
}
return stat;
}
protected doCreate(resource: URI, value?: string | ITextSnapshot, options?: ICreateFileOptions): Promise<IFileStatWithMetadata> {
return this.fileService.createFile(resource, toBufferOrReadable(value), options);
}
async write(resource: URI, value: string | ITextSnapshot, options?: IWriteTextFileOptions): Promise<IFileStatWithMetadata> {
return this.fileService.writeFile(resource, toBufferOrReadable(value), options);
}
async delete(resource: URI, options?: { useTrash?: boolean, recursive?: boolean }): Promise<void> {
const dirtyFiles = this.getDirty().filter(dirty => isEqualOrParent(dirty, resource, !platform.isLinux /* ignorecase */));
await this.revertAll(dirtyFiles, { soft: true });
return this.fileService.del(resource, options);
}
async move(source: URI, target: URI, overwrite?: boolean): Promise<IFileStatWithMetadata> {
const waitForPromises: Promise<unknown>[] = [];
// Event
this._onWillMove.fire({
oldResource: source,
newResource: target,
waitUntil(promise: Promise<unknown>) {
waitForPromises.push(promise.then(undefined, errors.onUnexpectedError));
}
});
// prevent async waitUntil-calls
Object.freeze(waitForPromises);
await Promise.all(waitForPromises);
// Handle target models if existing (if target URI is a folder, this can be multiple)
const dirtyTargetModels = this.getDirtyFileModels().filter(model => isEqualOrParent(model.getResource(), target, false /* do not ignorecase, see https://github.com/Microsoft/vscode/issues/56384 */));
if (dirtyTargetModels.length) {
await this.revertAll(dirtyTargetModels.map(targetModel => targetModel.getResource()), { soft: true });
}
// Handle dirty source models if existing (if source URI is a folder, this can be multiple)
const dirtySourceModels = this.getDirtyFileModels().filter(model => isEqualOrParent(model.getResource(), source, !platform.isLinux /* ignorecase */));
const dirtyTargetModelUris: URI[] = [];
if (dirtySourceModels.length) {
await Promise.all(dirtySourceModels.map(async sourceModel => {
const sourceModelResource = sourceModel.getResource();
let targetModelResource: URI;
// If the source is the actual model, just use target as new resource
if (isEqual(sourceModelResource, source, !platform.isLinux /* ignorecase */)) {
targetModelResource = target;
}
// Otherwise a parent folder of the source is being moved, so we need
// to compute the target resource based on that
else {
targetModelResource = sourceModelResource.with({ path: joinPath(target, sourceModelResource.path.substr(source.path.length + 1)).path });
}
// Remember as dirty target model to load after the operation
dirtyTargetModelUris.push(targetModelResource);
// Backup dirty source model to the target resource it will become later
await sourceModel.backup(targetModelResource);
}));
}
// Soft revert the dirty source files if any
await this.revertAll(dirtySourceModels.map(dirtySourceModel => dirtySourceModel.getResource()), { soft: true });
// Rename to target
try {
const stat = await this.fileService.move(source, target, overwrite);
// Load models that were dirty before
await Promise.all(dirtyTargetModelUris.map(dirtyTargetModel => this.models.loadOrCreate(dirtyTargetModel)));
return stat;
} catch (error) {
// In case of an error, discard any dirty target backups that were made
await Promise.all(dirtyTargetModelUris.map(dirtyTargetModel => this.backupFileService.discardResourceBackup(dirtyTargetModel)));
throw error;
}
}
//#endregion
//#region save/revert
async save(resource: URI, options?: ISaveOptions): Promise<boolean> {
// Run a forced save if we detect the file is not dirty so that save participants can still run
if (options && options.force && this.fileService.canHandleResource(resource) && !this.isDirty(resource)) {
const model = this._models.get(resource);
if (model) {
options.reason = SaveReason.EXPLICIT;
await model.save(options);
return !model.isDirty();
}
}
const result = await this.saveAll([resource], options);
return result.results.length === 1 && !!result.results[0].success;
}
async confirmSave(resources?: URI[]): Promise<ConfirmResult> {
if (this.environmentService.isExtensionDevelopment) {
return ConfirmResult.DONT_SAVE; // no veto when we are in extension dev mode because we cannot assum we run interactive (e.g. tests)
}
const resourcesToConfirm = this.getDirty(resources);
if (resourcesToConfirm.length === 0) {
return ConfirmResult.DONT_SAVE;
}
const message = resourcesToConfirm.length === 1 ? nls.localize('saveChangesMessage', "Do you want to save the changes you made to {0}?", basename(resourcesToConfirm[0]))
: getConfirmMessage(nls.localize('saveChangesMessages', "Do you want to save the changes to the following {0} files?", resourcesToConfirm.length), resourcesToConfirm);
const buttons: string[] = [
resourcesToConfirm.length > 1 ? nls.localize({ key: 'saveAll', comment: ['&& denotes a mnemonic'] }, "&&Save All") : nls.localize({ key: 'save', comment: ['&& denotes a mnemonic'] }, "&&Save"),
nls.localize({ key: 'dontSave', comment: ['&& denotes a mnemonic'] }, "Do&&n't Save"),
nls.localize('cancel', "Cancel")
];
const index = await this.dialogService.show(Severity.Warning, message, buttons, {
cancelId: 2,
detail: nls.localize('saveChangesDetail', "Your changes will be lost if you don't save them.")
});
switch (index) {
case 0: return ConfirmResult.SAVE;
case 1: return ConfirmResult.DONT_SAVE;
default: return ConfirmResult.CANCEL;
}
}
async confirmOverwrite(resource: URI): Promise<boolean> {
const confirm: IConfirmation = {
message: nls.localize('confirmOverwrite', "'{0}' already exists. Do you want to replace it?", basename(resource)),
detail: nls.localize('irreversible', "A file or folder with the same name already exists in the folder {0}. Replacing it will overwrite its current contents.", basename(dirname(resource))),
primaryButton: nls.localize({ key: 'replaceButtonLabel', comment: ['&& denotes a mnemonic'] }, "&&Replace"),
type: 'warning'
};
return (await this.dialogService.confirm(confirm)).confirmed;
}
saveAll(includeUntitled?: boolean, options?: ISaveOptions): Promise<ITextFileOperationResult>;
saveAll(resources: URI[], options?: ISaveOptions): Promise<ITextFileOperationResult>;
saveAll(arg1?: boolean | URI[], options?: ISaveOptions): Promise<ITextFileOperationResult> {
// get all dirty
let toSave: URI[] = [];
if (Array.isArray(arg1)) {
toSave = this.getDirty(arg1);
} else {
toSave = this.getDirty();
}
// split up between files and untitled
const filesToSave: URI[] = [];
const untitledToSave: URI[] = [];
toSave.forEach(s => {
if ((Array.isArray(arg1) || arg1 === true /* includeUntitled */) && s.scheme === Schemas.untitled) {
untitledToSave.push(s);
} else {
filesToSave.push(s);
}
});
return this.doSaveAll(filesToSave, untitledToSave, options);
}
private async doSaveAll(fileResources: URI[], untitledResources: URI[], options?: ISaveOptions): Promise<ITextFileOperationResult> {
// Handle files first that can just be saved
const result = await this.doSaveAllFiles(fileResources, options);
// Preflight for untitled to handle cancellation from the dialog
const targetsForUntitled: URI[] = [];
for (const untitled of untitledResources) {
if (this.untitledEditorService.exists(untitled)) {
let targetUri: URI;
// Untitled with associated file path don't need to prompt
if (this.untitledEditorService.hasAssociatedFilePath(untitled)) {
targetUri = toLocalResource(untitled, this.environmentService.configuration.remoteAuthority);
}
// Otherwise ask user
else {
const targetPath = await this.promptForPath(untitled, this.suggestFileName(untitled));
if (!targetPath) {
return { results: [...fileResources, ...untitledResources].map(r => ({ source: r })) };
}
targetUri = targetPath;
}
targetsForUntitled.push(targetUri);
}
}
// Handle untitled
await Promise.all(targetsForUntitled.map(async (target, index) => {
const uri = await this.saveAs(untitledResources[index], target);
result.results.push({
source: untitledResources[index],
target: uri,
success: !!uri
});
}));
return result;
}
protected async promptForPath(resource: URI, defaultUri: URI): Promise<URI | undefined> {
// Help user to find a name for the file by opening it first
await this.editorService.openEditor({ resource, options: { revealIfOpened: true, preserveFocus: true, } });
return this.fileDialogService.pickFileToSave(this.getSaveDialogOptions(defaultUri));
}
private getSaveDialogOptions(defaultUri: URI): ISaveDialogOptions {
const options: ISaveDialogOptions = {
defaultUri,
title: nls.localize('saveAsTitle', "Save As")
};
// Filters are only enabled on Windows where they work properly
if (!platform.isWindows) {
return options;
}
interface IFilter { name: string; extensions: string[]; }
// Build the file filter by using our known languages
const ext: string | undefined = defaultUri ? extname(defaultUri) : undefined;
let matchingFilter: IFilter | undefined;
const filters: IFilter[] = coalesce(this.modeService.getRegisteredLanguageNames().map(languageName => {
const extensions = this.modeService.getExtensions(languageName);
if (!extensions || !extensions.length) {
return null;
}
const filter: IFilter = { name: languageName, extensions: extensions.slice(0, 10).map(e => trim(e, '.')) };
if (ext && extensions.indexOf(ext) >= 0) {
matchingFilter = filter;
return null; // matching filter will be added last to the top
}
return filter;
}));
// Filters are a bit weird on Windows, based on having a match or not:
// Match: we put the matching filter first so that it shows up selected and the all files last
// No match: we put the all files filter first
const allFilesFilter = { name: nls.localize('allFiles', "All Files"), extensions: ['*'] };
if (matchingFilter) {
filters.unshift(matchingFilter);
filters.unshift(allFilesFilter);
} else {
filters.unshift(allFilesFilter);
}
// Allow to save file without extension
filters.push({ name: nls.localize('noExt', "No Extension"), extensions: [''] });
options.filters = filters;
return options;
}
private async doSaveAllFiles(resources?: URI[], options: ISaveOptions = Object.create(null)): Promise<ITextFileOperationResult> {
const dirtyFileModels = this.getDirtyFileModels(Array.isArray(resources) ? resources : undefined /* Save All */)
.filter(model => {
if ((model.hasState(ModelState.CONFLICT) || model.hasState(ModelState.ERROR)) && (options.reason === SaveReason.AUTO || options.reason === SaveReason.FOCUS_CHANGE || options.reason === SaveReason.WINDOW_CHANGE)) {
return false; // if model is in save conflict or error, do not save unless save reason is explicit or not provided at all
}
return true;
});
const mapResourceToResult = new ResourceMap<IResult>();
dirtyFileModels.forEach(m => {
mapResourceToResult.set(m.getResource(), {
source: m.getResource()
});
});
await Promise.all(dirtyFileModels.map(async model => {
await model.save(options);
if (!model.isDirty()) {
const result = mapResourceToResult.get(model.getResource());
if (result) {
result.success = true;
}
}
}));
return { results: mapResourceToResult.values() };
}
private getFileModels(arg1?: URI | URI[]): ITextFileEditorModel[] {
if (Array.isArray(arg1)) {
const models: ITextFileEditorModel[] = [];
arg1.forEach(resource => {
models.push(...this.getFileModels(resource));
});
return models;
}
return this._models.getAll(arg1);
}
private getDirtyFileModels(resources?: URI | URI[]): ITextFileEditorModel[] {
return this.getFileModels(resources).filter(model => model.isDirty());
}
async saveAs(resource: URI, targetResource?: URI, options?: ISaveOptions): Promise<URI | undefined> {
// Get to target resource
if (!targetResource) {
let dialogPath = resource;
if (resource.scheme === Schemas.untitled) {
dialogPath = this.suggestFileName(resource);
}
targetResource = await this.promptForPath(resource, dialogPath);
}
if (!targetResource) {
return; // user canceled
}
// Just save if target is same as models own resource
if (resource.toString() === targetResource.toString()) {
await this.save(resource, options);
return resource;
}
// Do it
return this.doSaveAs(resource, targetResource, options);
}
private async doSaveAs(resource: URI, target: URI, options?: ISaveOptions): Promise<URI> {
// Retrieve text model from provided resource if any
let model: ITextFileEditorModel | UntitledEditorModel | undefined;
if (this.fileService.canHandleResource(resource)) {
model = this._models.get(resource);
} else if (resource.scheme === Schemas.untitled && this.untitledEditorService.exists(resource)) {
model = await this.untitledEditorService.loadOrCreate({ resource });
}
// We have a model: Use it (can be null e.g. if this file is binary and not a text file or was never opened before)
let result: boolean;
if (model) {
result = await this.doSaveTextFileAs(model, resource, target, options);
}
// Otherwise we can only copy
else {
await this.fileService.copy(resource, target);
result = true;
}
// Return early if the operation was not running
if (!result) {
return target;
}
// Revert the source
await this.revert(resource);
return target;
}
private async doSaveTextFileAs(sourceModel: ITextFileEditorModel | UntitledEditorModel, resource: URI, target: URI, options?: ISaveOptions): Promise<boolean> {
// Prefer an existing model if it is already loaded for the given target resource
let targetExists: boolean = false;
let targetModel = this.models.get(target);
if (targetModel && targetModel.isResolved()) {
targetExists = true;
}
// Otherwise create the target file empty if it does not exist already and resolve it from there
else {
targetExists = await this.fileService.exists(target);
// create target model adhoc if file does not exist yet
if (!targetExists) {
await this.create(target, '');
}
targetModel = await this.models.loadOrCreate(target);
}
try {
// Confirm to overwrite if we have an untitled file with associated file where
// the file actually exists on disk and we are instructed to save to that file
// path. This can happen if the file was created after the untitled file was opened.
// See https://github.com/Microsoft/vscode/issues/67946
let write: boolean;
if (sourceModel instanceof UntitledEditorModel && sourceModel.hasAssociatedFilePath && targetExists && isEqual(target, toLocalResource(sourceModel.getResource(), this.environmentService.configuration.remoteAuthority))) {
write = await this.confirmOverwrite(target);
} else {
write = true;
}
if (!write) {
return false;
}
// take over encoding, mode and model value from source model
targetModel.updatePreferredEncoding(sourceModel.getEncoding());
if (sourceModel.isResolved() && targetModel.isResolved()) {
this.modelService.updateModel(targetModel.textEditorModel, createTextBufferFactoryFromSnapshot(sourceModel.createSnapshot()));
const mode = sourceModel.textEditorModel.getLanguageIdentifier();
if (mode.language !== PLAINTEXT_MODE_ID) {
targetModel.textEditorModel.setMode(mode); // only use if more specific than plain/text
}
}
// save model
await targetModel.save(options);
return true;
} catch (error) {
// binary model: delete the file and run the operation again
if (
(<TextFileOperationError>error).textFileOperationResult === TextFileOperationResult.FILE_IS_BINARY ||
(<FileOperationError>error).fileOperationResult === FileOperationResult.FILE_TOO_LARGE
) {
await this.fileService.del(target);
return this.doSaveTextFileAs(sourceModel, resource, target, options);
}
throw error;
}
}
private suggestFileName(untitledResource: URI): URI {
const untitledFileName = this.untitledEditorService.suggestFileName(untitledResource);
const remoteAuthority = this.environmentService.configuration.remoteAuthority;
const schemeFilter = remoteAuthority ? Schemas.vscodeRemote : Schemas.file;
const lastActiveFile = this.historyService.getLastActiveFile(schemeFilter);
if (lastActiveFile) {
const lastDir = dirname(lastActiveFile);
return joinPath(lastDir, untitledFileName);
}
const lastActiveFolder = this.historyService.getLastActiveWorkspaceRoot(schemeFilter);
if (lastActiveFolder) {
return joinPath(lastActiveFolder, untitledFileName);
}
return schemeFilter === Schemas.file ? URI.file(untitledFileName) : URI.from({ scheme: schemeFilter, authority: remoteAuthority, path: posix.sep + untitledFileName });
}
async revert(resource: URI, options?: IRevertOptions): Promise<boolean> {
const result = await this.revertAll([resource], options);
return result.results.length === 1 && !!result.results[0].success;
}
async revertAll(resources?: URI[], options?: IRevertOptions): Promise<ITextFileOperationResult> {
// Revert files first
const revertOperationResult = await this.doRevertAllFiles(resources, options);
// Revert untitled
const untitledReverted = this.untitledEditorService.revertAll(resources);
untitledReverted.forEach(untitled => revertOperationResult.results.push({ source: untitled, success: true }));
return revertOperationResult;
}
private async doRevertAllFiles(resources?: URI[], options?: IRevertOptions): Promise<ITextFileOperationResult> {
const fileModels = options && options.force ? this.getFileModels(resources) : this.getDirtyFileModels(resources);
const mapResourceToResult = new ResourceMap<IResult>();
fileModels.forEach(m => {
mapResourceToResult.set(m.getResource(), {
source: m.getResource()
});
});
await Promise.all(fileModels.map(async model => {
try {
await model.revert(options && options.soft);
if (!model.isDirty()) {
const result = mapResourceToResult.get(model.getResource());
if (result) {
result.success = true;
}
}
} catch (error) {
// FileNotFound means the file got deleted meanwhile, so still record as successful revert
if ((<FileOperationError>error).fileOperationResult === FileOperationResult.FILE_NOT_FOUND) {
const result = mapResourceToResult.get(model.getResource());
if (result) {
result.success = true;
}
}
// Otherwise bubble up the error
else {
throw error;
}
}
}));
return { results: mapResourceToResult.values() };
}
getDirty(resources?: URI[]): URI[] {
// Collect files
const dirty = this.getDirtyFileModels(resources).map(m => m.getResource());
// Add untitled ones
dirty.push(...this.untitledEditorService.getDirty(resources));
return dirty;
}
isDirty(resource?: URI): boolean {
// Check for dirty file
if (this._models.getAll(resource).some(model => model.isDirty())) {
return true;
}
// Check for dirty untitled
return this.untitledEditorService.getDirty().some(dirty => !resource || dirty.toString() === resource.toString());
}
//#endregion
//#region config
getAutoSaveMode(): AutoSaveMode {
if (this.configuredAutoSaveOnFocusChange) {
return AutoSaveMode.ON_FOCUS_CHANGE;
}
if (this.configuredAutoSaveOnWindowChange) {
return AutoSaveMode.ON_WINDOW_CHANGE;
}
if (this.configuredAutoSaveDelay && this.configuredAutoSaveDelay > 0) {
return this.configuredAutoSaveDelay <= 1000 ? AutoSaveMode.AFTER_SHORT_DELAY : AutoSaveMode.AFTER_LONG_DELAY;
}
return AutoSaveMode.OFF;
}
getAutoSaveConfiguration(): IAutoSaveConfiguration {
return {
autoSaveDelay: this.configuredAutoSaveDelay && this.configuredAutoSaveDelay > 0 ? this.configuredAutoSaveDelay : undefined,
autoSaveFocusChange: this.configuredAutoSaveOnFocusChange,
autoSaveApplicationChange: this.configuredAutoSaveOnWindowChange
};
}
get isHotExitEnabled(): boolean {
return !this.environmentService.isExtensionDevelopment && this.configuredHotExit !== HotExitConfiguration.OFF;
}
//#endregion
dispose(): void {
// Clear all caches
this._models.clear();
super.dispose();
}
} | src/vs/workbench/services/textfile/common/textFileService.ts | 1 | https://github.com/microsoft/vscode/commit/985de26b3446636f86e2bb2b14dbeb9ec1e33207 | [
0.9986504912376404,
0.21606644988059998,
0.0001654104853514582,
0.00017305831715930253,
0.3937247395515442
] |
{
"id": 11,
"code_window": [
"\t}\n",
"\n",
"\tprivate getSaveDialogOptions(defaultUri: URI): ISaveDialogOptions {\n",
"\t\tconst options: ISaveDialogOptions = {\n",
"\t\t\tdefaultUri,\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
"\tprivate getSaveDialogOptions(defaultUri: URI, availableFileSystems?: string[]): ISaveDialogOptions {\n"
],
"file_path": "src/vs/workbench/services/textfile/common/textFileService.ts",
"type": "replace",
"edit_start_line_idx": 658
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { LRUCache } from 'vs/base/common/map';
/**
* The normalize() method returns the Unicode Normalization Form of a given string. The form will be
* the Normalization Form Canonical Composition.
*
* @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/normalize}
*/
export const canNormalize = typeof ((<any>'').normalize) === 'function';
const nfcCache = new LRUCache<string, string>(10000); // bounded to 10000 elements
export function normalizeNFC(str: string): string {
return normalize(str, 'NFC', nfcCache);
}
const nfdCache = new LRUCache<string, string>(10000); // bounded to 10000 elements
export function normalizeNFD(str: string): string {
return normalize(str, 'NFD', nfdCache);
}
const nonAsciiCharactersPattern = /[^\u0000-\u0080]/;
function normalize(str: string, form: string, normalizedCache: LRUCache<string, string>): string {
if (!canNormalize || !str) {
return str;
}
const cached = normalizedCache.get(str);
if (cached) {
return cached;
}
let res: string;
if (nonAsciiCharactersPattern.test(str)) {
res = (<any>str).normalize(form);
} else {
res = str;
}
// Use the cache for fast lookup
normalizedCache.set(str, res);
return res;
}
| src/vs/base/common/normalization.ts | 0 | https://github.com/microsoft/vscode/commit/985de26b3446636f86e2bb2b14dbeb9ec1e33207 | [
0.0001751191302901134,
0.00017269744421355426,
0.00017066614236682653,
0.00017332255083601922,
0.0000016773509514678153
] |
{
"id": 11,
"code_window": [
"\t}\n",
"\n",
"\tprivate getSaveDialogOptions(defaultUri: URI): ISaveDialogOptions {\n",
"\t\tconst options: ISaveDialogOptions = {\n",
"\t\t\tdefaultUri,\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
"\tprivate getSaveDialogOptions(defaultUri: URI, availableFileSystems?: string[]): ISaveDialogOptions {\n"
],
"file_path": "src/vs/workbench/services/textfile/common/textFileService.ts",
"type": "replace",
"edit_start_line_idx": 658
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { URI, UriComponents } from 'vs/base/common/uri';
import { IModeService } from 'vs/editor/common/services/modeService';
import { IModelService } from 'vs/editor/common/services/modelService';
import { MainThreadLanguagesShape, MainContext, IExtHostContext } from '../common/extHost.protocol';
import { extHostNamedCustomer } from 'vs/workbench/api/common/extHostCustomers';
@extHostNamedCustomer(MainContext.MainThreadLanguages)
export class MainThreadLanguages implements MainThreadLanguagesShape {
constructor(
_extHostContext: IExtHostContext,
@IModeService private readonly _modeService: IModeService,
@IModelService private readonly _modelService: IModelService
) {
}
dispose(): void {
// nothing
}
$getLanguages(): Promise<string[]> {
return Promise.resolve(this._modeService.getRegisteredModes());
}
$changeLanguage(resource: UriComponents, languageId: string): Promise<void> {
const uri = URI.revive(resource);
const model = this._modelService.getModel(uri);
if (!model) {
return Promise.reject(new Error('Invalid uri'));
}
const languageIdentifier = this._modeService.getLanguageIdentifier(languageId);
if (!languageIdentifier || languageIdentifier.language !== languageId) {
return Promise.reject(new Error(`Unknown language id: ${languageId}`));
}
this._modelService.setMode(model, this._modeService.create(languageId));
return Promise.resolve(undefined);
}
}
| src/vs/workbench/api/browser/mainThreadLanguages.ts | 0 | https://github.com/microsoft/vscode/commit/985de26b3446636f86e2bb2b14dbeb9ec1e33207 | [
0.00017252928228117526,
0.000170297033037059,
0.00016808186774142087,
0.00016985731781460345,
0.000001653462845752074
] |
{
"id": 11,
"code_window": [
"\t}\n",
"\n",
"\tprivate getSaveDialogOptions(defaultUri: URI): ISaveDialogOptions {\n",
"\t\tconst options: ISaveDialogOptions = {\n",
"\t\t\tdefaultUri,\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
"\tprivate getSaveDialogOptions(defaultUri: URI, availableFileSystems?: string[]): ISaveDialogOptions {\n"
],
"file_path": "src/vs/workbench/services/textfile/common/textFileService.ts",
"type": "replace",
"edit_start_line_idx": 658
} | /*---------------------------------------------------------------------------------------------
* 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 { Mode, IEntryRunContext, IAutoFocus, IQuickNavigateConfiguration, IModel } from 'vs/base/parts/quickopen/common/quickOpen';
import { QuickOpenModel, QuickOpenEntry } from 'vs/base/parts/quickopen/browser/quickOpenModel';
import { QuickOpenHandler } from 'vs/workbench/browser/quickopen';
import { ITerminalService, ITerminalInstance } from 'vs/workbench/contrib/terminal/common/terminal';
import { ContributableActionProvider } from 'vs/workbench/browser/actions';
import { stripWildcards } from 'vs/base/common/strings';
import { matchesFuzzy } from 'vs/base/common/filters';
import { ICommandService } from 'vs/platform/commands/common/commands';
import { CancellationToken } from 'vs/base/common/cancellation';
export class TerminalEntry extends QuickOpenEntry {
constructor(
public instance: ITerminalInstance,
private label: string,
private terminalService: ITerminalService
) {
super();
}
public getLabel(): string {
return this.label;
}
public getAriaLabel(): string {
return nls.localize('termEntryAriaLabel', "{0}, terminal picker", this.getLabel());
}
public run(mode: Mode, context: IEntryRunContext): boolean {
if (mode === Mode.OPEN) {
setTimeout(() => {
this.terminalService.setActiveInstance(this.instance);
this.terminalService.showPanel(true);
}, 0);
return true;
}
return super.run(mode, context);
}
}
export class CreateTerminal extends QuickOpenEntry {
constructor(
private label: string,
private commandService: ICommandService
) {
super();
}
public getLabel(): string {
return this.label;
}
public getAriaLabel(): string {
return nls.localize('termCreateEntryAriaLabel', "{0}, create new terminal", this.getLabel());
}
public run(mode: Mode, context: IEntryRunContext): boolean {
if (mode === Mode.OPEN) {
setTimeout(() => this.commandService.executeCommand('workbench.action.terminal.new'), 0);
return true;
}
return super.run(mode, context);
}
}
export class TerminalPickerHandler extends QuickOpenHandler {
public static readonly ID = 'workbench.picker.terminals';
constructor(
@ITerminalService private readonly terminalService: ITerminalService,
@ICommandService private readonly commandService: ICommandService,
) {
super();
}
public getResults(searchValue: string, token: CancellationToken): Promise<QuickOpenModel> {
searchValue = searchValue.trim();
const normalizedSearchValueLowercase = stripWildcards(searchValue).toLowerCase();
const terminalEntries: QuickOpenEntry[] = this.getTerminals();
terminalEntries.push(new CreateTerminal(nls.localize("workbench.action.terminal.newplus", "$(plus) Create New Integrated Terminal"), this.commandService));
const entries = terminalEntries.filter(e => {
if (!searchValue) {
return true;
}
const label = e.getLabel();
if (!label) {
return false;
}
const highlights = matchesFuzzy(normalizedSearchValueLowercase, label, true);
if (!highlights) {
return false;
}
e.setHighlights(highlights);
return true;
});
return Promise.resolve(new QuickOpenModel(entries, new ContributableActionProvider()));
}
private getTerminals(): TerminalEntry[] {
return this.terminalService.terminalTabs.reduce((terminals, tab, tabIndex) => {
const terminalsInTab = tab.terminalInstances.map((terminal, terminalIndex) => {
const label = `${tabIndex + 1}.${terminalIndex + 1}: ${terminal.title}`;
return new TerminalEntry(terminal, label, this.terminalService);
});
return [...terminals, ...terminalsInTab];
}, []);
}
public getAutoFocus(searchValue: string, context: { model: IModel<QuickOpenEntry>, quickNavigateConfiguration?: IQuickNavigateConfiguration }): IAutoFocus {
return {
autoFocusFirstEntry: !!searchValue || !!context.quickNavigateConfiguration
};
}
public getEmptyLabel(searchString: string): string {
if (searchString.length > 0) {
return nls.localize('noTerminalsMatching', "No terminals matching");
}
return nls.localize('noTerminalsFound', "No terminals open");
}
} | src/vs/workbench/contrib/terminal/browser/terminalQuickOpen.ts | 0 | https://github.com/microsoft/vscode/commit/985de26b3446636f86e2bb2b14dbeb9ec1e33207 | [
0.0001744252076605335,
0.00016949349083006382,
0.00016720157873351127,
0.0001687019830569625,
0.000002108324224536773
] |
{
"id": 12,
"code_window": [
"\t\tconst options: ISaveDialogOptions = {\n",
"\t\t\tdefaultUri,\n",
"\t\t\ttitle: nls.localize('saveAsTitle', \"Save As\")\n",
"\t\t};\n",
"\n",
"\t\t// Filters are only enabled on Windows where they work properly\n",
"\t\tif (!platform.isWindows) {\n",
"\t\t\treturn options;\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\ttitle: nls.localize('saveAsTitle', \"Save As\"),\n",
"\t\t\tavailableFileSystems,\n"
],
"file_path": "src/vs/workbench/services/textfile/common/textFileService.ts",
"type": "replace",
"edit_start_line_idx": 661
} | /*---------------------------------------------------------------------------------------------
* 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 resources from 'vs/base/common/resources';
import * as objects from 'vs/base/common/objects';
import { IFileService, IFileStat, FileKind } from 'vs/platform/files/common/files';
import { IQuickInputService, IQuickPickItem, IQuickPick } from 'vs/platform/quickinput/common/quickInput';
import { URI } from 'vs/base/common/uri';
import { isWindows, OperatingSystem } from 'vs/base/common/platform';
import { ISaveDialogOptions, IOpenDialogOptions, IFileDialogService } from 'vs/platform/dialogs/common/dialogs';
import { REMOTE_HOST_SCHEME } from 'vs/platform/remote/common/remoteHosts';
import { ILabelService } from 'vs/platform/label/common/label';
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
import { INotificationService } from 'vs/platform/notification/common/notification';
import { IModelService } from 'vs/editor/common/services/modelService';
import { IModeService } from 'vs/editor/common/services/modeService';
import { getIconClasses } from 'vs/editor/common/services/getIconClasses';
import { Schemas } from 'vs/base/common/network';
import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService';
import { IRemoteAgentService } from 'vs/workbench/services/remote/common/remoteAgentService';
import { IContextKeyService, IContextKey } from 'vs/platform/contextkey/common/contextkey';
import { equalsIgnoreCase, format, startsWithIgnoreCase } from 'vs/base/common/strings';
import { OpenLocalFileAction, OpenLocalFileFolderAction, OpenLocalFolderAction, SaveLocalFileAction } from 'vs/workbench/browser/actions/workspaceActions';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { IRemoteAgentEnvironment } from 'vs/platform/remote/common/remoteAgentEnvironment';
import { isValidBasename } from 'vs/base/common/extpath';
import { RemoteFileDialogContext } from 'vs/workbench/browser/contextkeys';
import { Emitter } from 'vs/base/common/event';
import { IDisposable, dispose } from 'vs/base/common/lifecycle';
interface FileQuickPickItem extends IQuickPickItem {
uri: URI;
isFolder: boolean;
}
enum UpdateResult {
Updated,
Updating,
NotUpdated,
InvalidPath
}
export class RemoteFileDialog {
private options: IOpenDialogOptions;
private currentFolder: URI;
private filePickBox: IQuickPick<FileQuickPickItem>;
private hidden: boolean;
private allowFileSelection: boolean;
private allowFolderSelection: boolean;
private remoteAuthority: string | undefined;
private requiresTrailing: boolean;
private trailing: string | undefined;
private scheme: string = REMOTE_HOST_SCHEME;
private contextKey: IContextKey<boolean>;
private userEnteredPathSegment: string;
private autoCompletePathSegment: string;
private activeItem: FileQuickPickItem;
private userHome: URI;
private badPath: string | undefined;
private remoteAgentEnvironment: IRemoteAgentEnvironment | null;
private separator: string;
private onBusyChangeEmitter = new Emitter<boolean>();
protected disposables: IDisposable[] = [
this.onBusyChangeEmitter
];
constructor(
@IFileService private readonly fileService: IFileService,
@IQuickInputService private readonly quickInputService: IQuickInputService,
@ILabelService private readonly labelService: ILabelService,
@IWorkspaceContextService private readonly workspaceContextService: IWorkspaceContextService,
@INotificationService private readonly notificationService: INotificationService,
@IFileDialogService private readonly fileDialogService: IFileDialogService,
@IModelService private readonly modelService: IModelService,
@IModeService private readonly modeService: IModeService,
@IWorkbenchEnvironmentService private readonly environmentService: IWorkbenchEnvironmentService,
@IRemoteAgentService private readonly remoteAgentService: IRemoteAgentService,
@IKeybindingService private readonly keybindingService: IKeybindingService,
@IContextKeyService contextKeyService: IContextKeyService,
) {
this.remoteAuthority = this.environmentService.configuration.remoteAuthority;
this.contextKey = RemoteFileDialogContext.bindTo(contextKeyService);
}
set busy(busy: boolean) {
if (this.filePickBox.busy !== busy) {
this.filePickBox.busy = busy;
this.onBusyChangeEmitter.fire(busy);
}
}
get busy(): boolean {
return this.filePickBox.busy;
}
public async showOpenDialog(options: IOpenDialogOptions = {}): Promise<URI | undefined> {
this.scheme = this.getScheme(options.defaultUri, options.availableFileSystems);
this.userHome = await this.getUserHome();
const newOptions = await this.getOptions(options);
if (!newOptions) {
return Promise.resolve(undefined);
}
this.options = newOptions;
return this.pickResource();
}
public async showSaveDialog(options: ISaveDialogOptions): Promise<URI | undefined> {
this.scheme = this.getScheme(options.defaultUri, options.availableFileSystems);
this.userHome = await this.getUserHome();
this.requiresTrailing = true;
const newOptions = await this.getOptions(options, true);
if (!newOptions) {
return Promise.resolve(undefined);
}
this.options = newOptions;
this.options.canSelectFolders = true;
this.options.canSelectFiles = true;
return new Promise<URI | undefined>((resolve) => {
this.pickResource(true).then(folderUri => {
resolve(folderUri);
});
});
}
private getOptions(options: ISaveDialogOptions | IOpenDialogOptions, isSave: boolean = false): IOpenDialogOptions | undefined {
let defaultUri = options.defaultUri;
const filename = (defaultUri && isSave && (resources.dirname(defaultUri).path === '/')) ? resources.basename(defaultUri) : undefined;
if (!defaultUri || filename) {
defaultUri = this.userHome;
if (filename) {
defaultUri = resources.joinPath(defaultUri, filename);
}
}
if ((this.scheme !== Schemas.file) && !this.fileService.canHandleResource(defaultUri)) {
this.notificationService.info(nls.localize('remoteFileDialog.notConnectedToRemote', 'File system provider for {0} is not available.', defaultUri.toString()));
return undefined;
}
const newOptions: IOpenDialogOptions = objects.deepClone(options);
newOptions.defaultUri = defaultUri;
return newOptions;
}
private remoteUriFrom(path: string): URI {
path = path.replace(/\\/g, '/');
return resources.toLocalResource(URI.from({ scheme: this.scheme, path }), this.scheme === Schemas.file ? undefined : this.remoteAuthority);
}
private getScheme(defaultUri: URI | undefined, available: string[] | undefined): string {
return defaultUri ? defaultUri.scheme : (available ? available[0] : Schemas.file);
}
private async getRemoteAgentEnvironment(): Promise<IRemoteAgentEnvironment | null> {
if (this.remoteAgentEnvironment === undefined) {
this.remoteAgentEnvironment = await this.remoteAgentService.getEnvironment();
}
return this.remoteAgentEnvironment;
}
private async getUserHome(): Promise<URI> {
if (this.scheme !== Schemas.file) {
const env = await this.getRemoteAgentEnvironment();
if (env) {
return env.userHome;
}
}
return URI.from({ scheme: this.scheme, path: this.environmentService.userHome });
}
private async pickResource(isSave: boolean = false): Promise<URI | undefined> {
this.allowFolderSelection = !!this.options.canSelectFolders;
this.allowFileSelection = !!this.options.canSelectFiles;
this.separator = this.labelService.getSeparator(this.scheme, this.remoteAuthority);
this.hidden = false;
let homedir: URI = this.options.defaultUri ? this.options.defaultUri : this.workspaceContextService.getWorkspace().folders[0].uri;
let stat: IFileStat | undefined;
let ext: string = resources.extname(homedir);
if (this.options.defaultUri) {
try {
stat = await this.fileService.resolve(this.options.defaultUri);
} catch (e) {
// The file or folder doesn't exist
}
if (!stat || !stat.isDirectory) {
homedir = resources.dirname(this.options.defaultUri);
this.trailing = resources.basename(this.options.defaultUri);
}
// append extension
if (isSave && !ext && this.options.filters) {
for (let i = 0; i < this.options.filters.length; i++) {
if (this.options.filters[i].extensions[0] !== '*') {
ext = '.' + this.options.filters[i].extensions[0];
this.trailing = this.trailing ? this.trailing + ext : ext;
break;
}
}
}
}
return new Promise<URI | undefined>(async (resolve) => {
this.filePickBox = this.quickInputService.createQuickPick<FileQuickPickItem>();
this.busy = true;
this.filePickBox.matchOnLabel = false;
this.filePickBox.autoFocusOnList = false;
this.filePickBox.ignoreFocusOut = true;
this.filePickBox.ok = true;
if (this.options && this.options.availableFileSystems && (this.options.availableFileSystems.length > 1)) {
this.filePickBox.customButton = true;
this.filePickBox.customLabel = nls.localize('remoteFileDialog.local', 'Show Local');
let action;
if (isSave) {
action = SaveLocalFileAction;
} else {
action = this.allowFileSelection ? (this.allowFolderSelection ? OpenLocalFileFolderAction : OpenLocalFileAction) : OpenLocalFolderAction;
}
const keybinding = this.keybindingService.lookupKeybinding(action.ID);
if (keybinding) {
const label = keybinding.getLabel();
if (label) {
this.filePickBox.customHover = format('{0} ({1})', action.LABEL, label);
}
}
}
let isResolving: number = 0;
let isAcceptHandled = false;
this.currentFolder = homedir;
this.userEnteredPathSegment = '';
this.autoCompletePathSegment = '';
this.filePickBox.title = this.options.title;
this.filePickBox.value = this.pathFromUri(this.currentFolder, true);
this.filePickBox.valueSelection = [this.filePickBox.value.length, this.filePickBox.value.length];
this.filePickBox.items = [];
function doResolve(dialog: RemoteFileDialog, uri: URI | undefined) {
resolve(uri);
dialog.contextKey.set(false);
dialog.filePickBox.dispose();
dispose(dialog.disposables);
}
this.filePickBox.onDidCustom(() => {
if (isAcceptHandled || this.busy) {
return;
}
isAcceptHandled = true;
isResolving++;
if (this.options.availableFileSystems && (this.options.availableFileSystems.length > 1)) {
this.options.availableFileSystems.shift();
}
this.options.defaultUri = undefined;
this.filePickBox.hide();
if (isSave) {
// Remove defaultUri and filters to get a consistant experience with the keybinding.
this.options.defaultUri = undefined;
this.options.filters = undefined;
return this.fileDialogService.showSaveDialog(this.options).then(result => {
doResolve(this, result);
});
} else {
return this.fileDialogService.showOpenDialog(this.options).then(result => {
doResolve(this, result ? result[0] : undefined);
});
}
});
function handleAccept(dialog: RemoteFileDialog) {
if (dialog.busy) {
// Save the accept until the file picker is not busy.
dialog.onBusyChangeEmitter.event((busy: boolean) => {
if (!busy) {
handleAccept(dialog);
}
});
return;
} else if (isAcceptHandled) {
return;
}
isAcceptHandled = true;
isResolving++;
dialog.onDidAccept().then(resolveValue => {
if (resolveValue) {
dialog.filePickBox.hide();
doResolve(dialog, resolveValue);
} else if (dialog.hidden) {
doResolve(dialog, undefined);
} else {
isResolving--;
isAcceptHandled = false;
}
});
}
this.filePickBox.onDidAccept(_ => {
handleAccept(this);
});
this.filePickBox.onDidChangeActive(i => {
isAcceptHandled = false;
// update input box to match the first selected item
if ((i.length === 1) && this.isChangeFromUser()) {
this.filePickBox.validationMessage = undefined;
this.setAutoComplete(this.constructFullUserPath(), this.userEnteredPathSegment, i[0], true);
}
});
this.filePickBox.onDidChangeValue(async value => {
try {
// onDidChangeValue can also be triggered by the auto complete, so if it looks like the auto complete, don't do anything
if (this.isChangeFromUser()) {
// If the user has just entered more bad path, don't change anything
if (!equalsIgnoreCase(value, this.constructFullUserPath()) && !this.isBadSubpath(value)) {
this.filePickBox.validationMessage = undefined;
const filePickBoxUri = this.filePickBoxValue();
let updated: UpdateResult = UpdateResult.NotUpdated;
if (!resources.isEqual(this.currentFolder, filePickBoxUri, true)) {
updated = await this.tryUpdateItems(value, filePickBoxUri);
}
if (updated === UpdateResult.NotUpdated) {
this.setActiveItems(value);
}
} else {
this.filePickBox.activeItems = [];
}
}
} catch {
// Since any text can be entered in the input box, there is potential for error causing input. If this happens, do nothing.
}
});
this.filePickBox.onDidHide(() => {
this.hidden = true;
if (isResolving === 0) {
doResolve(this, undefined);
}
});
this.filePickBox.show();
this.contextKey.set(true);
await this.updateItems(homedir, true, this.trailing);
if (this.trailing) {
this.filePickBox.valueSelection = [this.filePickBox.value.length - this.trailing.length, this.filePickBox.value.length - ext.length];
} else {
this.filePickBox.valueSelection = [this.filePickBox.value.length, this.filePickBox.value.length];
}
this.busy = false;
});
}
private isBadSubpath(value: string) {
return this.badPath && (value.length > this.badPath.length) && equalsIgnoreCase(value.substring(0, this.badPath.length), this.badPath);
}
private isChangeFromUser(): boolean {
if (equalsIgnoreCase(this.filePickBox.value, this.pathAppend(this.currentFolder, this.userEnteredPathSegment + this.autoCompletePathSegment))
&& (this.activeItem === (this.filePickBox.activeItems ? this.filePickBox.activeItems[0] : undefined))) {
return false;
}
return true;
}
private constructFullUserPath(): string {
return this.pathAppend(this.currentFolder, this.userEnteredPathSegment);
}
private filePickBoxValue(): URI {
// The file pick box can't render everything, so we use the current folder to create the uri so that it is an existing path.
const directUri = this.remoteUriFrom(this.filePickBox.value);
const currentPath = this.pathFromUri(this.currentFolder);
if (equalsIgnoreCase(this.filePickBox.value, currentPath)) {
return this.currentFolder;
}
const currentDisplayUri = this.remoteUriFrom(currentPath);
const relativePath = resources.relativePath(currentDisplayUri, directUri);
const isSameRoot = (this.filePickBox.value.length > 1 && currentPath.length > 1) ? equalsIgnoreCase(this.filePickBox.value.substr(0, 2), currentPath.substr(0, 2)) : false;
if (relativePath && isSameRoot) {
const path = resources.joinPath(this.currentFolder, relativePath);
return resources.hasTrailingPathSeparator(directUri) ? resources.addTrailingPathSeparator(path) : path;
} else {
return directUri;
}
}
private async onDidAccept(): Promise<URI | undefined> {
this.busy = true;
if (this.filePickBox.activeItems.length === 1) {
const item = this.filePickBox.selectedItems[0];
if (item.isFolder) {
if (this.trailing) {
await this.updateItems(item.uri, true, this.trailing);
} else {
// When possible, cause the update to happen by modifying the input box.
// This allows all input box updates to happen first, and uses the same code path as the user typing.
const newPath = this.pathFromUri(item.uri);
if (startsWithIgnoreCase(newPath, this.filePickBox.value) && (equalsIgnoreCase(item.label, resources.basename(item.uri)))) {
this.filePickBox.valueSelection = [this.pathFromUri(this.currentFolder).length, this.filePickBox.value.length];
this.insertText(newPath, item.label);
} else if ((item.label === '..') && startsWithIgnoreCase(this.filePickBox.value, newPath)) {
this.filePickBox.valueSelection = [newPath.length, this.filePickBox.value.length];
this.insertText(newPath, '');
} else {
await this.updateItems(item.uri, true);
}
}
this.filePickBox.busy = false;
return;
}
} else {
// If the items have updated, don't try to resolve
if ((await this.tryUpdateItems(this.filePickBox.value, this.filePickBoxValue())) !== UpdateResult.NotUpdated) {
this.filePickBox.busy = false;
return;
}
}
let resolveValue: URI | undefined;
// Find resolve value
if (this.filePickBox.activeItems.length === 0) {
resolveValue = this.filePickBoxValue();
} else if (this.filePickBox.activeItems.length === 1) {
resolveValue = this.filePickBox.selectedItems[0].uri;
}
if (resolveValue) {
resolveValue = this.addPostfix(resolveValue);
}
if (await this.validate(resolveValue)) {
this.busy = false;
return resolveValue;
}
this.busy = false;
return undefined;
}
private async tryUpdateItems(value: string, valueUri: URI): Promise<UpdateResult> {
if ((value.length > 0) && ((value[value.length - 1] === '~') || (value[0] === '~'))) {
let newDir = this.userHome;
if ((value[0] === '~') && (value.length > 1)) {
newDir = resources.joinPath(newDir, value.substring(1));
}
await this.updateItems(newDir, true);
return UpdateResult.Updated;
} else if (!resources.isEqual(this.currentFolder, valueUri, true) && (this.endsWithSlash(value) || (!resources.isEqual(this.currentFolder, resources.dirname(valueUri), true) && resources.isEqualOrParent(this.currentFolder, resources.dirname(valueUri), true)))) {
let stat: IFileStat | undefined;
try {
stat = await this.fileService.resolve(valueUri);
} catch (e) {
// do nothing
}
if (stat && stat.isDirectory && (resources.basename(valueUri) !== '.') && this.endsWithSlash(value)) {
await this.updateItems(valueUri);
return UpdateResult.Updated;
} else if (this.endsWithSlash(value)) {
// The input box contains a path that doesn't exist on the system.
this.filePickBox.validationMessage = nls.localize('remoteFileDialog.badPath', 'The path does not exist.');
// Save this bad path. It can take too long to to a stat on every user entered character, but once a user enters a bad path they are likely
// to keep typing more bad path. We can compare against this bad path and see if the user entered path starts with it.
this.badPath = value;
return UpdateResult.InvalidPath;
} else {
const inputUriDirname = resources.dirname(valueUri);
if (!resources.isEqual(resources.removeTrailingPathSeparator(this.currentFolder), inputUriDirname, true)) {
let statWithoutTrailing: IFileStat | undefined;
try {
statWithoutTrailing = await this.fileService.resolve(inputUriDirname);
} catch (e) {
// do nothing
}
if (statWithoutTrailing && statWithoutTrailing.isDirectory && (resources.basename(valueUri) !== '.')) {
await this.updateItems(inputUriDirname, false, resources.basename(valueUri));
this.badPath = undefined;
return UpdateResult.Updated;
}
}
}
}
this.badPath = undefined;
return UpdateResult.NotUpdated;
}
private setActiveItems(value: string) {
const inputBasename = resources.basename(this.remoteUriFrom(value));
// Make sure that the folder whose children we are currently viewing matches the path in the input
const userPath = this.constructFullUserPath();
if (equalsIgnoreCase(userPath, value.substring(0, userPath.length))) {
let hasMatch = false;
for (let i = 0; i < this.filePickBox.items.length; i++) {
const item = <FileQuickPickItem>this.filePickBox.items[i];
if (this.setAutoComplete(value, inputBasename, item)) {
hasMatch = true;
break;
}
}
if (!hasMatch) {
this.userEnteredPathSegment = inputBasename;
this.autoCompletePathSegment = '';
this.filePickBox.activeItems = [];
}
} else {
if (!equalsIgnoreCase(inputBasename, resources.basename(this.currentFolder))) {
this.userEnteredPathSegment = inputBasename;
} else {
this.userEnteredPathSegment = '';
}
this.autoCompletePathSegment = '';
}
}
private setAutoComplete(startingValue: string, startingBasename: string, quickPickItem: FileQuickPickItem, force: boolean = false): boolean {
if (this.busy) {
// We're in the middle of something else. Doing an auto complete now can result jumbled or incorrect autocompletes.
this.userEnteredPathSegment = startingBasename;
this.autoCompletePathSegment = '';
return false;
}
const itemBasename = this.trimTrailingSlash(quickPickItem.label);
// Either force the autocomplete, or the old value should be one smaller than the new value and match the new value.
if (itemBasename === '..') {
// Don't match on the up directory item ever.
this.userEnteredPathSegment = startingValue;
this.autoCompletePathSegment = '';
this.activeItem = quickPickItem;
if (force) {
// clear any selected text
this.insertText(this.userEnteredPathSegment, '');
}
return false;
} else if (!force && (itemBasename.length >= startingBasename.length) && equalsIgnoreCase(itemBasename.substr(0, startingBasename.length), startingBasename)) {
this.userEnteredPathSegment = startingBasename;
this.activeItem = quickPickItem;
// Changing the active items will trigger the onDidActiveItemsChanged. Clear the autocomplete first, then set it after.
this.autoCompletePathSegment = '';
this.filePickBox.activeItems = [quickPickItem];
return true;
} else if (force && (!equalsIgnoreCase(quickPickItem.label, (this.userEnteredPathSegment + this.autoCompletePathSegment)))) {
this.userEnteredPathSegment = '';
this.autoCompletePathSegment = this.trimTrailingSlash(itemBasename);
this.activeItem = quickPickItem;
this.filePickBox.valueSelection = [this.pathFromUri(this.currentFolder, true).length, this.filePickBox.value.length];
// use insert text to preserve undo buffer
this.insertText(this.pathAppend(this.currentFolder, this.autoCompletePathSegment), this.autoCompletePathSegment);
this.filePickBox.valueSelection = [this.filePickBox.value.length - this.autoCompletePathSegment.length, this.filePickBox.value.length];
return true;
} else {
this.userEnteredPathSegment = startingBasename;
this.autoCompletePathSegment = '';
return false;
}
}
private insertText(wholeValue: string, insertText: string) {
if (this.filePickBox.inputHasFocus()) {
document.execCommand('insertText', false, insertText);
} else {
this.filePickBox.value = wholeValue;
}
}
private addPostfix(uri: URI): URI {
let result = uri;
if (this.requiresTrailing && this.options.filters && this.options.filters.length > 0) {
// Make sure that the suffix is added. If the user deleted it, we automatically add it here
let hasExt: boolean = false;
const currentExt = resources.extname(uri).substr(1);
for (let i = 0; i < this.options.filters.length; i++) {
for (let j = 0; j < this.options.filters[i].extensions.length; j++) {
if ((this.options.filters[i].extensions[j] === '*') || (this.options.filters[i].extensions[j] === currentExt)) {
hasExt = true;
break;
}
}
if (hasExt) {
break;
}
}
if (!hasExt) {
result = resources.joinPath(resources.dirname(uri), resources.basename(uri) + '.' + this.options.filters[0].extensions[0]);
}
}
return result;
}
private trimTrailingSlash(path: string): string {
return ((path.length > 1) && this.endsWithSlash(path)) ? path.substr(0, path.length - 1) : path;
}
private yesNoPrompt(uri: URI, message: string): Promise<boolean> {
interface YesNoItem extends IQuickPickItem {
value: boolean;
}
const prompt = this.quickInputService.createQuickPick<YesNoItem>();
prompt.title = message;
prompt.ignoreFocusOut = true;
prompt.ok = true;
prompt.customButton = true;
prompt.customLabel = nls.localize('remoteFileDialog.cancel', 'Cancel');
prompt.value = this.pathFromUri(uri);
let isResolving = false;
return new Promise<boolean>(resolve => {
prompt.onDidAccept(() => {
isResolving = true;
prompt.hide();
resolve(true);
});
prompt.onDidHide(() => {
if (!isResolving) {
resolve(false);
}
this.filePickBox.show();
this.hidden = false;
this.filePickBox.items = this.filePickBox.items;
prompt.dispose();
});
prompt.onDidChangeValue(() => {
prompt.hide();
});
prompt.onDidCustom(() => {
prompt.hide();
});
prompt.show();
});
}
private async validate(uri: URI | undefined): Promise<boolean> {
if (uri === undefined) {
this.filePickBox.validationMessage = nls.localize('remoteFileDialog.invalidPath', 'Please enter a valid path.');
return Promise.resolve(false);
}
let stat: IFileStat | undefined;
let statDirname: IFileStat | undefined;
try {
statDirname = await this.fileService.resolve(resources.dirname(uri));
stat = await this.fileService.resolve(uri);
} catch (e) {
// do nothing
}
if (this.requiresTrailing) { // save
if (stat && stat.isDirectory) {
// Can't do this
this.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateFolder', 'The folder already exists. Please use a new file name.');
return Promise.resolve(false);
} else if (stat) {
// Replacing a file.
// Show a yes/no prompt
const message = nls.localize('remoteFileDialog.validateExisting', '{0} already exists. Are you sure you want to overwrite it?', resources.basename(uri));
return this.yesNoPrompt(uri, message);
} else if (!(isValidBasename(resources.basename(uri), await this.isWindowsOS()))) {
// Filename not allowed
this.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateBadFilename', 'Please enter a valid file name.');
return Promise.resolve(false);
} else if (!statDirname || !statDirname.isDirectory) {
// Folder to save in doesn't exist
this.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateNonexistentDir', 'Please enter a path that exists.');
return Promise.resolve(false);
}
} else { // open
if (!stat) {
// File or folder doesn't exist
this.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateNonexistentDir', 'Please enter a path that exists.');
return Promise.resolve(false);
} else if (stat.isDirectory && !this.allowFolderSelection) {
// Folder selected when folder selection not permitted
this.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateFileOnly', 'Please select a file.');
return Promise.resolve(false);
} else if (!stat.isDirectory && !this.allowFileSelection) {
// File selected when file selection not permitted
this.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateFolderOnly', 'Please select a folder.');
return Promise.resolve(false);
}
}
return Promise.resolve(true);
}
private async updateItems(newFolder: URI, force: boolean = false, trailing?: string) {
this.busy = true;
this.userEnteredPathSegment = trailing ? trailing : '';
this.autoCompletePathSegment = '';
const newValue = trailing ? this.pathFromUri(resources.joinPath(newFolder, trailing)) : this.pathFromUri(newFolder, true);
this.currentFolder = resources.addTrailingPathSeparator(newFolder, this.separator);
return this.createItems(this.currentFolder).then(items => {
this.filePickBox.items = items;
if (this.allowFolderSelection) {
this.filePickBox.activeItems = [];
}
// the user might have continued typing while we were updating. Only update the input box if it doesn't match the directory.
if (!equalsIgnoreCase(this.filePickBox.value, newValue) && force) {
this.filePickBox.valueSelection = [0, this.filePickBox.value.length];
this.insertText(newValue, newValue);
}
if (force && trailing) {
// Keep the cursor position in front of the save as name.
this.filePickBox.valueSelection = [this.filePickBox.value.length - trailing.length, this.filePickBox.value.length - trailing.length];
} else if (!trailing) {
// If there is trailing, we don't move the cursor. If there is no trailing, cursor goes at the end.
this.filePickBox.valueSelection = [this.filePickBox.value.length, this.filePickBox.value.length];
}
this.busy = false;
});
}
private pathFromUri(uri: URI, endWithSeparator: boolean = false): string {
let result: string = uri.fsPath.replace(/\n/g, '');
if (this.separator === '/') {
result = result.replace(/\\/g, this.separator);
} else {
result = result.replace(/\//g, this.separator);
}
if (endWithSeparator && !this.endsWithSlash(result)) {
result = result + this.separator;
}
return result;
}
private pathAppend(uri: URI, additional: string): string {
if ((additional === '..') || (additional === '.')) {
const basePath = this.pathFromUri(uri);
return basePath + (this.endsWithSlash(basePath) ? '' : this.separator) + additional;
} else {
return this.pathFromUri(resources.joinPath(uri, additional));
}
}
private async isWindowsOS(): Promise<boolean> {
let isWindowsOS = isWindows;
const env = await this.getRemoteAgentEnvironment();
if (env) {
isWindowsOS = env.os === OperatingSystem.Windows;
}
return isWindowsOS;
}
private endsWithSlash(s: string) {
return /[\/\\]$/.test(s);
}
private basenameWithTrailingSlash(fullPath: URI): string {
const child = this.pathFromUri(fullPath, true);
const parent = this.pathFromUri(resources.dirname(fullPath), true);
return child.substring(parent.length);
}
private createBackItem(currFolder: URI): FileQuickPickItem | null {
const parentFolder = resources.dirname(currFolder)!;
if (!resources.isEqual(currFolder, parentFolder, true)) {
return { label: '..', uri: resources.addTrailingPathSeparator(parentFolder, this.separator), isFolder: true };
}
return null;
}
private async createItems(currentFolder: URI): Promise<FileQuickPickItem[]> {
const result: FileQuickPickItem[] = [];
const backDir = this.createBackItem(currentFolder);
try {
const folder = await this.fileService.resolve(currentFolder);
const fileNames = folder.children ? folder.children.map(child => child.name) : [];
const items = await Promise.all(fileNames.map(fileName => this.createItem(fileName, currentFolder)));
for (let item of items) {
if (item) {
result.push(item);
}
}
} catch (e) {
// ignore
console.log(e);
}
const sorted = result.sort((i1, i2) => {
if (i1.isFolder !== i2.isFolder) {
return i1.isFolder ? -1 : 1;
}
const trimmed1 = this.endsWithSlash(i1.label) ? i1.label.substr(0, i1.label.length - 1) : i1.label;
const trimmed2 = this.endsWithSlash(i2.label) ? i2.label.substr(0, i2.label.length - 1) : i2.label;
return trimmed1.localeCompare(trimmed2);
});
if (backDir) {
sorted.unshift(backDir);
}
return sorted;
}
private filterFile(file: URI): boolean {
if (this.options.filters) {
const ext = resources.extname(file);
for (let i = 0; i < this.options.filters.length; i++) {
for (let j = 0; j < this.options.filters[i].extensions.length; j++) {
if (ext === ('.' + this.options.filters[i].extensions[j])) {
return true;
}
}
}
return false;
}
return true;
}
private async createItem(filename: string, parent: URI): Promise<FileQuickPickItem | undefined> {
let fullPath = resources.joinPath(parent, filename);
try {
const stat = await this.fileService.resolve(fullPath);
if (stat.isDirectory) {
filename = this.basenameWithTrailingSlash(fullPath);
fullPath = resources.addTrailingPathSeparator(fullPath, this.separator);
return { label: filename, uri: fullPath, isFolder: true, iconClasses: getIconClasses(this.modelService, this.modeService, fullPath || undefined, FileKind.FOLDER) };
} else if (!stat.isDirectory && this.allowFileSelection && this.filterFile(fullPath)) {
return { label: filename, uri: fullPath, isFolder: false, iconClasses: getIconClasses(this.modelService, this.modeService, fullPath || undefined) };
}
return undefined;
} catch (e) {
return undefined;
}
}
} | src/vs/workbench/services/dialogs/browser/remoteFileDialog.ts | 1 | https://github.com/microsoft/vscode/commit/985de26b3446636f86e2bb2b14dbeb9ec1e33207 | [
0.9574731588363647,
0.029005881398916245,
0.00016458921891171485,
0.0001743916072882712,
0.14934580028057098
] |
{
"id": 12,
"code_window": [
"\t\tconst options: ISaveDialogOptions = {\n",
"\t\t\tdefaultUri,\n",
"\t\t\ttitle: nls.localize('saveAsTitle', \"Save As\")\n",
"\t\t};\n",
"\n",
"\t\t// Filters are only enabled on Windows where they work properly\n",
"\t\tif (!platform.isWindows) {\n",
"\t\t\treturn options;\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\ttitle: nls.localize('saveAsTitle', \"Save As\"),\n",
"\t\t\tavailableFileSystems,\n"
],
"file_path": "src/vs/workbench/services/textfile/common/textFileService.ts",
"type": "replace",
"edit_start_line_idx": 661
} | {
"version": "0.1.0",
// List of configurations. Add new configurations or edit existing ones.
"configurations": [
{
"name": "Attach",
"type": "node",
"request": "attach",
"port": 6044,
"protocol": "inspector",
"sourceMaps": true,
"outFiles": ["${workspaceFolder}/out/**/*.js"]
},
{
"name": "Unit Tests",
"type": "node",
"request": "launch",
"program": "${workspaceFolder}/../../../node_modules/mocha/bin/_mocha",
"stopOnEntry": false,
"args": [
"--timeout",
"999999",
"--colors"
],
"cwd": "${workspaceFolder}",
"runtimeExecutable": null,
"runtimeArgs": [],
"env": {},
"sourceMaps": true,
"outFiles": ["${workspaceFolder}/out/**/*.js"]
}
]
} | extensions/css-language-features/server/.vscode/launch.json | 0 | https://github.com/microsoft/vscode/commit/985de26b3446636f86e2bb2b14dbeb9ec1e33207 | [
0.00017947251035366207,
0.00017356073658447713,
0.00016776499978732318,
0.00017350273265037686,
0.000004226384135108674
] |
{
"id": 12,
"code_window": [
"\t\tconst options: ISaveDialogOptions = {\n",
"\t\t\tdefaultUri,\n",
"\t\t\ttitle: nls.localize('saveAsTitle', \"Save As\")\n",
"\t\t};\n",
"\n",
"\t\t// Filters are only enabled on Windows where they work properly\n",
"\t\tif (!platform.isWindows) {\n",
"\t\t\treturn options;\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\ttitle: nls.localize('saveAsTitle', \"Save As\"),\n",
"\t\t\tavailableFileSystems,\n"
],
"file_path": "src/vs/workbench/services/textfile/common/textFileService.ts",
"type": "replace",
"edit_start_line_idx": 661
} | <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><defs><style>.icon-canvas-transparent,.icon-vs-out{fill:#f6f6f6;}.icon-canvas-transparent{opacity:0;}.icon-vs-red{fill:#e51400;}</style></defs><title>breakpoint-log</title><g id="canvas"><path class="icon-canvas-transparent" d="M16,0V16H0V0Z"/></g><g id="outline" style="display: none;"><path class="icon-vs-out" d="M13.414,8,8,13.414,2.586,8,8,2.586Z"/></g><g id="iconBg"><path class="icon-vs-red" d="M12,8,8,12,4,8,8,4Z"/></g></svg> | src/vs/workbench/contrib/debug/browser/media/breakpoint-log.svg | 0 | https://github.com/microsoft/vscode/commit/985de26b3446636f86e2bb2b14dbeb9ec1e33207 | [
0.0001749459042912349,
0.0001749459042912349,
0.0001749459042912349,
0.0001749459042912349,
0
] |
{
"id": 12,
"code_window": [
"\t\tconst options: ISaveDialogOptions = {\n",
"\t\t\tdefaultUri,\n",
"\t\t\ttitle: nls.localize('saveAsTitle', \"Save As\")\n",
"\t\t};\n",
"\n",
"\t\t// Filters are only enabled on Windows where they work properly\n",
"\t\tif (!platform.isWindows) {\n",
"\t\t\treturn options;\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\ttitle: nls.localize('saveAsTitle', \"Save As\"),\n",
"\t\t\tavailableFileSystems,\n"
],
"file_path": "src/vs/workbench/services/textfile/common/textFileService.ts",
"type": "replace",
"edit_start_line_idx": 661
} | /*---------------------------------------------------------------------------------------------
* 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 { Disposable, dispose } from 'vs/base/common/lifecycle';
import { EditOperation } from 'vs/editor/common/core/editOperation';
import { Position } from 'vs/editor/common/core/position';
import { Range } from 'vs/editor/common/core/range';
import { TokenizationResult2 } from 'vs/editor/common/core/token';
import { TextModel } from 'vs/editor/common/model/textModel';
import { ModelRawContentChangedEvent, ModelRawFlush, ModelRawLineChanged, ModelRawLinesDeleted, ModelRawLinesInserted } from 'vs/editor/common/model/textModelEvents';
import { IState, LanguageIdentifier, MetadataConsts, TokenizationRegistry } from 'vs/editor/common/modes';
import { LanguageConfigurationRegistry } from 'vs/editor/common/modes/languageConfigurationRegistry';
import { NULL_STATE } from 'vs/editor/common/modes/nullMode';
import { MockMode } from 'vs/editor/test/common/mocks/mockMode';
// --------- utils
const LINE1 = 'My First Line';
const LINE2 = '\t\tMy Second Line';
const LINE3 = ' Third Line';
const LINE4 = '';
const LINE5 = '1';
suite('Editor Model - Model', () => {
let thisModel: TextModel;
setup(() => {
const text =
LINE1 + '\r\n' +
LINE2 + '\n' +
LINE3 + '\n' +
LINE4 + '\r\n' +
LINE5;
thisModel = TextModel.createFromString(text);
});
teardown(() => {
thisModel.dispose();
});
// --------- insert text
test('model getValue', () => {
assert.equal(thisModel.getValue(), 'My First Line\n\t\tMy Second Line\n Third Line\n\n1');
});
test('model insert empty text', () => {
thisModel.applyEdits([EditOperation.insert(new Position(1, 1), '')]);
assert.equal(thisModel.getLineCount(), 5);
assert.equal(thisModel.getLineContent(1), 'My First Line');
});
test('model insert text without newline 1', () => {
thisModel.applyEdits([EditOperation.insert(new Position(1, 1), 'foo ')]);
assert.equal(thisModel.getLineCount(), 5);
assert.equal(thisModel.getLineContent(1), 'foo My First Line');
});
test('model insert text without newline 2', () => {
thisModel.applyEdits([EditOperation.insert(new Position(1, 3), ' foo')]);
assert.equal(thisModel.getLineCount(), 5);
assert.equal(thisModel.getLineContent(1), 'My foo First Line');
});
test('model insert text with one newline', () => {
thisModel.applyEdits([EditOperation.insert(new Position(1, 3), ' new line\nNo longer')]);
assert.equal(thisModel.getLineCount(), 6);
assert.equal(thisModel.getLineContent(1), 'My new line');
assert.equal(thisModel.getLineContent(2), 'No longer First Line');
});
test('model insert text with two newlines', () => {
thisModel.applyEdits([EditOperation.insert(new Position(1, 3), ' new line\nOne more line in the middle\nNo longer')]);
assert.equal(thisModel.getLineCount(), 7);
assert.equal(thisModel.getLineContent(1), 'My new line');
assert.equal(thisModel.getLineContent(2), 'One more line in the middle');
assert.equal(thisModel.getLineContent(3), 'No longer First Line');
});
test('model insert text with many newlines', () => {
thisModel.applyEdits([EditOperation.insert(new Position(1, 3), '\n\n\n\n')]);
assert.equal(thisModel.getLineCount(), 9);
assert.equal(thisModel.getLineContent(1), 'My');
assert.equal(thisModel.getLineContent(2), '');
assert.equal(thisModel.getLineContent(3), '');
assert.equal(thisModel.getLineContent(4), '');
assert.equal(thisModel.getLineContent(5), ' First Line');
});
// --------- insert text eventing
test('model insert empty text does not trigger eventing', () => {
thisModel.onDidChangeRawContent((e) => {
assert.ok(false, 'was not expecting event');
});
thisModel.applyEdits([EditOperation.insert(new Position(1, 1), '')]);
});
test('model insert text without newline eventing', () => {
let e: ModelRawContentChangedEvent | null = null;
thisModel.onDidChangeRawContent((_e) => {
if (e !== null) {
assert.fail('Unexpected assertion error');
}
e = _e;
});
thisModel.applyEdits([EditOperation.insert(new Position(1, 1), 'foo ')]);
assert.deepEqual(e, new ModelRawContentChangedEvent(
[
new ModelRawLineChanged(1, 'foo My First Line')
],
2,
false,
false
));
});
test('model insert text with one newline eventing', () => {
let e: ModelRawContentChangedEvent | null = null;
thisModel.onDidChangeRawContent((_e) => {
if (e !== null) {
assert.fail('Unexpected assertion error');
}
e = _e;
});
thisModel.applyEdits([EditOperation.insert(new Position(1, 3), ' new line\nNo longer')]);
assert.deepEqual(e, new ModelRawContentChangedEvent(
[
new ModelRawLineChanged(1, 'My new line'),
new ModelRawLinesInserted(2, 2, ['No longer First Line']),
],
2,
false,
false
));
});
// --------- delete text
test('model delete empty text', () => {
thisModel.applyEdits([EditOperation.delete(new Range(1, 1, 1, 1))]);
assert.equal(thisModel.getLineCount(), 5);
assert.equal(thisModel.getLineContent(1), 'My First Line');
});
test('model delete text from one line', () => {
thisModel.applyEdits([EditOperation.delete(new Range(1, 1, 1, 2))]);
assert.equal(thisModel.getLineCount(), 5);
assert.equal(thisModel.getLineContent(1), 'y First Line');
});
test('model delete text from one line 2', () => {
thisModel.applyEdits([EditOperation.insert(new Position(1, 1), 'a')]);
assert.equal(thisModel.getLineContent(1), 'aMy First Line');
thisModel.applyEdits([EditOperation.delete(new Range(1, 2, 1, 4))]);
assert.equal(thisModel.getLineCount(), 5);
assert.equal(thisModel.getLineContent(1), 'a First Line');
});
test('model delete all text from a line', () => {
thisModel.applyEdits([EditOperation.delete(new Range(1, 1, 1, 14))]);
assert.equal(thisModel.getLineCount(), 5);
assert.equal(thisModel.getLineContent(1), '');
});
test('model delete text from two lines', () => {
thisModel.applyEdits([EditOperation.delete(new Range(1, 4, 2, 6))]);
assert.equal(thisModel.getLineCount(), 4);
assert.equal(thisModel.getLineContent(1), 'My Second Line');
});
test('model delete text from many lines', () => {
thisModel.applyEdits([EditOperation.delete(new Range(1, 4, 3, 5))]);
assert.equal(thisModel.getLineCount(), 3);
assert.equal(thisModel.getLineContent(1), 'My Third Line');
});
test('model delete everything', () => {
thisModel.applyEdits([EditOperation.delete(new Range(1, 1, 5, 2))]);
assert.equal(thisModel.getLineCount(), 1);
assert.equal(thisModel.getLineContent(1), '');
});
// --------- delete text eventing
test('model delete empty text does not trigger eventing', () => {
thisModel.onDidChangeRawContent((e) => {
assert.ok(false, 'was not expecting event');
});
thisModel.applyEdits([EditOperation.delete(new Range(1, 1, 1, 1))]);
});
test('model delete text from one line eventing', () => {
let e: ModelRawContentChangedEvent | null = null;
thisModel.onDidChangeRawContent((_e) => {
if (e !== null) {
assert.fail('Unexpected assertion error');
}
e = _e;
});
thisModel.applyEdits([EditOperation.delete(new Range(1, 1, 1, 2))]);
assert.deepEqual(e, new ModelRawContentChangedEvent(
[
new ModelRawLineChanged(1, 'y First Line'),
],
2,
false,
false
));
});
test('model delete all text from a line eventing', () => {
let e: ModelRawContentChangedEvent | null = null;
thisModel.onDidChangeRawContent((_e) => {
if (e !== null) {
assert.fail('Unexpected assertion error');
}
e = _e;
});
thisModel.applyEdits([EditOperation.delete(new Range(1, 1, 1, 14))]);
assert.deepEqual(e, new ModelRawContentChangedEvent(
[
new ModelRawLineChanged(1, ''),
],
2,
false,
false
));
});
test('model delete text from two lines eventing', () => {
let e: ModelRawContentChangedEvent | null = null;
thisModel.onDidChangeRawContent((_e) => {
if (e !== null) {
assert.fail('Unexpected assertion error');
}
e = _e;
});
thisModel.applyEdits([EditOperation.delete(new Range(1, 4, 2, 6))]);
assert.deepEqual(e, new ModelRawContentChangedEvent(
[
new ModelRawLineChanged(1, 'My Second Line'),
new ModelRawLinesDeleted(2, 2),
],
2,
false,
false
));
});
test('model delete text from many lines eventing', () => {
let e: ModelRawContentChangedEvent | null = null;
thisModel.onDidChangeRawContent((_e) => {
if (e !== null) {
assert.fail('Unexpected assertion error');
}
e = _e;
});
thisModel.applyEdits([EditOperation.delete(new Range(1, 4, 3, 5))]);
assert.deepEqual(e, new ModelRawContentChangedEvent(
[
new ModelRawLineChanged(1, 'My Third Line'),
new ModelRawLinesDeleted(2, 3),
],
2,
false,
false
));
});
// --------- getValueInRange
test('getValueInRange', () => {
assert.equal(thisModel.getValueInRange(new Range(1, 1, 1, 1)), '');
assert.equal(thisModel.getValueInRange(new Range(1, 1, 1, 2)), 'M');
assert.equal(thisModel.getValueInRange(new Range(1, 2, 1, 3)), 'y');
assert.equal(thisModel.getValueInRange(new Range(1, 1, 1, 14)), 'My First Line');
assert.equal(thisModel.getValueInRange(new Range(1, 1, 2, 1)), 'My First Line\n');
assert.equal(thisModel.getValueInRange(new Range(1, 1, 2, 2)), 'My First Line\n\t');
assert.equal(thisModel.getValueInRange(new Range(1, 1, 2, 3)), 'My First Line\n\t\t');
assert.equal(thisModel.getValueInRange(new Range(1, 1, 2, 17)), 'My First Line\n\t\tMy Second Line');
assert.equal(thisModel.getValueInRange(new Range(1, 1, 3, 1)), 'My First Line\n\t\tMy Second Line\n');
assert.equal(thisModel.getValueInRange(new Range(1, 1, 4, 1)), 'My First Line\n\t\tMy Second Line\n Third Line\n');
});
// --------- getValueLengthInRange
test('getValueLengthInRange', () => {
assert.equal(thisModel.getValueLengthInRange(new Range(1, 1, 1, 1)), ''.length);
assert.equal(thisModel.getValueLengthInRange(new Range(1, 1, 1, 2)), 'M'.length);
assert.equal(thisModel.getValueLengthInRange(new Range(1, 2, 1, 3)), 'y'.length);
assert.equal(thisModel.getValueLengthInRange(new Range(1, 1, 1, 14)), 'My First Line'.length);
assert.equal(thisModel.getValueLengthInRange(new Range(1, 1, 2, 1)), 'My First Line\n'.length);
assert.equal(thisModel.getValueLengthInRange(new Range(1, 1, 2, 2)), 'My First Line\n\t'.length);
assert.equal(thisModel.getValueLengthInRange(new Range(1, 1, 2, 3)), 'My First Line\n\t\t'.length);
assert.equal(thisModel.getValueLengthInRange(new Range(1, 1, 2, 17)), 'My First Line\n\t\tMy Second Line'.length);
assert.equal(thisModel.getValueLengthInRange(new Range(1, 1, 3, 1)), 'My First Line\n\t\tMy Second Line\n'.length);
assert.equal(thisModel.getValueLengthInRange(new Range(1, 1, 4, 1)), 'My First Line\n\t\tMy Second Line\n Third Line\n'.length);
});
// --------- setValue
test('setValue eventing', () => {
let e: ModelRawContentChangedEvent | null = null;
thisModel.onDidChangeRawContent((_e) => {
if (e !== null) {
assert.fail('Unexpected assertion error');
}
e = _e;
});
thisModel.setValue('new value');
assert.deepEqual(e, new ModelRawContentChangedEvent(
[
new ModelRawFlush()
],
2,
false,
false
));
});
test('issue #46342: Maintain edit operation order in applyEdits', () => {
let res = thisModel.applyEdits([
{ range: new Range(2, 1, 2, 1), text: 'a' },
{ range: new Range(1, 1, 1, 1), text: 'b' },
]);
assert.deepEqual(res[0].range, new Range(2, 1, 2, 2));
assert.deepEqual(res[1].range, new Range(1, 1, 1, 2));
});
});
// --------- Special Unicode LINE SEPARATOR character
suite('Editor Model - Model Line Separators', () => {
let thisModel: TextModel;
setup(() => {
const text =
LINE1 + '\u2028' +
LINE2 + '\n' +
LINE3 + '\u2028' +
LINE4 + '\r\n' +
LINE5;
thisModel = TextModel.createFromString(text);
});
teardown(() => {
thisModel.dispose();
});
test('model getValue', () => {
assert.equal(thisModel.getValue(), 'My First Line\u2028\t\tMy Second Line\n Third Line\u2028\n1');
});
test('model lines', () => {
assert.equal(thisModel.getLineCount(), 3);
});
test('Bug 13333:Model should line break on lonely CR too', () => {
let model = TextModel.createFromString('Hello\rWorld!\r\nAnother line');
assert.equal(model.getLineCount(), 3);
assert.equal(model.getValue(), 'Hello\r\nWorld!\r\nAnother line');
model.dispose();
});
});
// --------- Words
suite('Editor Model - Words', () => {
const OUTER_LANGUAGE_ID = new LanguageIdentifier('outerMode', 3);
const INNER_LANGUAGE_ID = new LanguageIdentifier('innerMode', 4);
class OuterMode extends MockMode {
constructor() {
super(OUTER_LANGUAGE_ID);
this._register(LanguageConfigurationRegistry.register(this.getLanguageIdentifier(), {}));
this._register(TokenizationRegistry.register(this.getLanguageIdentifier().language, {
getInitialState: (): IState => NULL_STATE,
tokenize: undefined!,
tokenize2: (line: string, state: IState): TokenizationResult2 => {
const tokensArr: number[] = [];
let prevLanguageId: LanguageIdentifier | undefined = undefined;
for (let i = 0; i < line.length; i++) {
const languageId = (line.charAt(i) === 'x' ? INNER_LANGUAGE_ID : OUTER_LANGUAGE_ID);
if (prevLanguageId !== languageId) {
tokensArr.push(i);
tokensArr.push((languageId.id << MetadataConsts.LANGUAGEID_OFFSET));
}
prevLanguageId = languageId;
}
const tokens = new Uint32Array(tokensArr.length);
for (let i = 0; i < tokens.length; i++) {
tokens[i] = tokensArr[i];
}
return new TokenizationResult2(tokens, state);
}
}));
}
}
class InnerMode extends MockMode {
constructor() {
super(INNER_LANGUAGE_ID);
this._register(LanguageConfigurationRegistry.register(this.getLanguageIdentifier(), {}));
}
}
let disposables: Disposable[] = [];
setup(() => {
disposables = [];
});
teardown(() => {
dispose(disposables);
disposables = [];
});
test('Get word at position', () => {
const text = ['This text has some words. '];
const thisModel = TextModel.createFromString(text.join('\n'));
disposables.push(thisModel);
assert.deepEqual(thisModel.getWordAtPosition(new Position(1, 1)), { word: 'This', startColumn: 1, endColumn: 5 });
assert.deepEqual(thisModel.getWordAtPosition(new Position(1, 2)), { word: 'This', startColumn: 1, endColumn: 5 });
assert.deepEqual(thisModel.getWordAtPosition(new Position(1, 4)), { word: 'This', startColumn: 1, endColumn: 5 });
assert.deepEqual(thisModel.getWordAtPosition(new Position(1, 5)), { word: 'This', startColumn: 1, endColumn: 5 });
assert.deepEqual(thisModel.getWordAtPosition(new Position(1, 6)), { word: 'text', startColumn: 6, endColumn: 10 });
assert.deepEqual(thisModel.getWordAtPosition(new Position(1, 19)), { word: 'some', startColumn: 15, endColumn: 19 });
assert.deepEqual(thisModel.getWordAtPosition(new Position(1, 20)), null);
assert.deepEqual(thisModel.getWordAtPosition(new Position(1, 21)), { word: 'words', startColumn: 21, endColumn: 26 });
assert.deepEqual(thisModel.getWordAtPosition(new Position(1, 26)), { word: 'words', startColumn: 21, endColumn: 26 });
assert.deepEqual(thisModel.getWordAtPosition(new Position(1, 27)), null);
assert.deepEqual(thisModel.getWordAtPosition(new Position(1, 28)), null);
});
test('getWordAtPosition at embedded language boundaries', () => {
const outerMode = new OuterMode();
const innerMode = new InnerMode();
disposables.push(outerMode, innerMode);
const model = TextModel.createFromString('ab<xx>ab<x>', undefined, outerMode.getLanguageIdentifier());
disposables.push(model);
assert.deepEqual(model.getWordAtPosition(new Position(1, 1)), { word: 'ab', startColumn: 1, endColumn: 3 });
assert.deepEqual(model.getWordAtPosition(new Position(1, 2)), { word: 'ab', startColumn: 1, endColumn: 3 });
assert.deepEqual(model.getWordAtPosition(new Position(1, 3)), { word: 'ab', startColumn: 1, endColumn: 3 });
assert.deepEqual(model.getWordAtPosition(new Position(1, 4)), { word: 'xx', startColumn: 4, endColumn: 6 });
assert.deepEqual(model.getWordAtPosition(new Position(1, 5)), { word: 'xx', startColumn: 4, endColumn: 6 });
assert.deepEqual(model.getWordAtPosition(new Position(1, 6)), { word: 'xx', startColumn: 4, endColumn: 6 });
assert.deepEqual(model.getWordAtPosition(new Position(1, 7)), { word: 'ab', startColumn: 7, endColumn: 9 });
});
test('issue #61296: VS code freezes when editing CSS file with emoji', () => {
const MODE_ID = new LanguageIdentifier('testMode', 4);
const mode = new class extends MockMode {
constructor() {
super(MODE_ID);
this._register(LanguageConfigurationRegistry.register(this.getLanguageIdentifier(), {
wordPattern: /(#?-?\d*\.\d\w*%?)|(::?[\w-]*(?=[^,{;]*[,{]))|(([@#.!])?[\w-?]+%?|[@#!.])/g
}));
}
};
disposables.push(mode);
const thisModel = TextModel.createFromString('.🐷-a-b', undefined, MODE_ID);
disposables.push(thisModel);
assert.deepEqual(thisModel.getWordAtPosition(new Position(1, 1)), { word: '.', startColumn: 1, endColumn: 2 });
assert.deepEqual(thisModel.getWordAtPosition(new Position(1, 2)), { word: '.', startColumn: 1, endColumn: 2 });
assert.deepEqual(thisModel.getWordAtPosition(new Position(1, 3)), null);
assert.deepEqual(thisModel.getWordAtPosition(new Position(1, 4)), { word: '-a-b', startColumn: 4, endColumn: 8 });
assert.deepEqual(thisModel.getWordAtPosition(new Position(1, 5)), { word: '-a-b', startColumn: 4, endColumn: 8 });
assert.deepEqual(thisModel.getWordAtPosition(new Position(1, 6)), { word: '-a-b', startColumn: 4, endColumn: 8 });
assert.deepEqual(thisModel.getWordAtPosition(new Position(1, 7)), { word: '-a-b', startColumn: 4, endColumn: 8 });
assert.deepEqual(thisModel.getWordAtPosition(new Position(1, 8)), { word: '-a-b', startColumn: 4, endColumn: 8 });
});
});
| src/vs/editor/test/common/model/model.test.ts | 0 | https://github.com/microsoft/vscode/commit/985de26b3446636f86e2bb2b14dbeb9ec1e33207 | [
0.00017931874026544392,
0.00017557558021508157,
0.00016709623741917312,
0.0001759517181199044,
0.0000026344032448832877
] |
{
"id": 13,
"code_window": [
"\t\t\t\tdialogPath = this.suggestFileName(resource);\n",
"\t\t\t}\n",
"\n",
"\t\t\ttargetResource = await this.promptForPath(resource, dialogPath);\n",
"\t\t}\n",
"\n",
"\t\tif (!targetResource) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\ttargetResource = await this.promptForPath(resource, dialogPath, options ? options.availableFileSystems : undefined);\n"
],
"file_path": "src/vs/workbench/services/textfile/common/textFileService.ts",
"type": "replace",
"edit_start_line_idx": 767
} | /*---------------------------------------------------------------------------------------------
* 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 resources from 'vs/base/common/resources';
import * as objects from 'vs/base/common/objects';
import { IFileService, IFileStat, FileKind } from 'vs/platform/files/common/files';
import { IQuickInputService, IQuickPickItem, IQuickPick } from 'vs/platform/quickinput/common/quickInput';
import { URI } from 'vs/base/common/uri';
import { isWindows, OperatingSystem } from 'vs/base/common/platform';
import { ISaveDialogOptions, IOpenDialogOptions, IFileDialogService } from 'vs/platform/dialogs/common/dialogs';
import { REMOTE_HOST_SCHEME } from 'vs/platform/remote/common/remoteHosts';
import { ILabelService } from 'vs/platform/label/common/label';
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
import { INotificationService } from 'vs/platform/notification/common/notification';
import { IModelService } from 'vs/editor/common/services/modelService';
import { IModeService } from 'vs/editor/common/services/modeService';
import { getIconClasses } from 'vs/editor/common/services/getIconClasses';
import { Schemas } from 'vs/base/common/network';
import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService';
import { IRemoteAgentService } from 'vs/workbench/services/remote/common/remoteAgentService';
import { IContextKeyService, IContextKey } from 'vs/platform/contextkey/common/contextkey';
import { equalsIgnoreCase, format, startsWithIgnoreCase } from 'vs/base/common/strings';
import { OpenLocalFileAction, OpenLocalFileFolderAction, OpenLocalFolderAction, SaveLocalFileAction } from 'vs/workbench/browser/actions/workspaceActions';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { IRemoteAgentEnvironment } from 'vs/platform/remote/common/remoteAgentEnvironment';
import { isValidBasename } from 'vs/base/common/extpath';
import { RemoteFileDialogContext } from 'vs/workbench/browser/contextkeys';
import { Emitter } from 'vs/base/common/event';
import { IDisposable, dispose } from 'vs/base/common/lifecycle';
interface FileQuickPickItem extends IQuickPickItem {
uri: URI;
isFolder: boolean;
}
enum UpdateResult {
Updated,
Updating,
NotUpdated,
InvalidPath
}
export class RemoteFileDialog {
private options: IOpenDialogOptions;
private currentFolder: URI;
private filePickBox: IQuickPick<FileQuickPickItem>;
private hidden: boolean;
private allowFileSelection: boolean;
private allowFolderSelection: boolean;
private remoteAuthority: string | undefined;
private requiresTrailing: boolean;
private trailing: string | undefined;
private scheme: string = REMOTE_HOST_SCHEME;
private contextKey: IContextKey<boolean>;
private userEnteredPathSegment: string;
private autoCompletePathSegment: string;
private activeItem: FileQuickPickItem;
private userHome: URI;
private badPath: string | undefined;
private remoteAgentEnvironment: IRemoteAgentEnvironment | null;
private separator: string;
private onBusyChangeEmitter = new Emitter<boolean>();
protected disposables: IDisposable[] = [
this.onBusyChangeEmitter
];
constructor(
@IFileService private readonly fileService: IFileService,
@IQuickInputService private readonly quickInputService: IQuickInputService,
@ILabelService private readonly labelService: ILabelService,
@IWorkspaceContextService private readonly workspaceContextService: IWorkspaceContextService,
@INotificationService private readonly notificationService: INotificationService,
@IFileDialogService private readonly fileDialogService: IFileDialogService,
@IModelService private readonly modelService: IModelService,
@IModeService private readonly modeService: IModeService,
@IWorkbenchEnvironmentService private readonly environmentService: IWorkbenchEnvironmentService,
@IRemoteAgentService private readonly remoteAgentService: IRemoteAgentService,
@IKeybindingService private readonly keybindingService: IKeybindingService,
@IContextKeyService contextKeyService: IContextKeyService,
) {
this.remoteAuthority = this.environmentService.configuration.remoteAuthority;
this.contextKey = RemoteFileDialogContext.bindTo(contextKeyService);
}
set busy(busy: boolean) {
if (this.filePickBox.busy !== busy) {
this.filePickBox.busy = busy;
this.onBusyChangeEmitter.fire(busy);
}
}
get busy(): boolean {
return this.filePickBox.busy;
}
public async showOpenDialog(options: IOpenDialogOptions = {}): Promise<URI | undefined> {
this.scheme = this.getScheme(options.defaultUri, options.availableFileSystems);
this.userHome = await this.getUserHome();
const newOptions = await this.getOptions(options);
if (!newOptions) {
return Promise.resolve(undefined);
}
this.options = newOptions;
return this.pickResource();
}
public async showSaveDialog(options: ISaveDialogOptions): Promise<URI | undefined> {
this.scheme = this.getScheme(options.defaultUri, options.availableFileSystems);
this.userHome = await this.getUserHome();
this.requiresTrailing = true;
const newOptions = await this.getOptions(options, true);
if (!newOptions) {
return Promise.resolve(undefined);
}
this.options = newOptions;
this.options.canSelectFolders = true;
this.options.canSelectFiles = true;
return new Promise<URI | undefined>((resolve) => {
this.pickResource(true).then(folderUri => {
resolve(folderUri);
});
});
}
private getOptions(options: ISaveDialogOptions | IOpenDialogOptions, isSave: boolean = false): IOpenDialogOptions | undefined {
let defaultUri = options.defaultUri;
const filename = (defaultUri && isSave && (resources.dirname(defaultUri).path === '/')) ? resources.basename(defaultUri) : undefined;
if (!defaultUri || filename) {
defaultUri = this.userHome;
if (filename) {
defaultUri = resources.joinPath(defaultUri, filename);
}
}
if ((this.scheme !== Schemas.file) && !this.fileService.canHandleResource(defaultUri)) {
this.notificationService.info(nls.localize('remoteFileDialog.notConnectedToRemote', 'File system provider for {0} is not available.', defaultUri.toString()));
return undefined;
}
const newOptions: IOpenDialogOptions = objects.deepClone(options);
newOptions.defaultUri = defaultUri;
return newOptions;
}
private remoteUriFrom(path: string): URI {
path = path.replace(/\\/g, '/');
return resources.toLocalResource(URI.from({ scheme: this.scheme, path }), this.scheme === Schemas.file ? undefined : this.remoteAuthority);
}
private getScheme(defaultUri: URI | undefined, available: string[] | undefined): string {
return defaultUri ? defaultUri.scheme : (available ? available[0] : Schemas.file);
}
private async getRemoteAgentEnvironment(): Promise<IRemoteAgentEnvironment | null> {
if (this.remoteAgentEnvironment === undefined) {
this.remoteAgentEnvironment = await this.remoteAgentService.getEnvironment();
}
return this.remoteAgentEnvironment;
}
private async getUserHome(): Promise<URI> {
if (this.scheme !== Schemas.file) {
const env = await this.getRemoteAgentEnvironment();
if (env) {
return env.userHome;
}
}
return URI.from({ scheme: this.scheme, path: this.environmentService.userHome });
}
private async pickResource(isSave: boolean = false): Promise<URI | undefined> {
this.allowFolderSelection = !!this.options.canSelectFolders;
this.allowFileSelection = !!this.options.canSelectFiles;
this.separator = this.labelService.getSeparator(this.scheme, this.remoteAuthority);
this.hidden = false;
let homedir: URI = this.options.defaultUri ? this.options.defaultUri : this.workspaceContextService.getWorkspace().folders[0].uri;
let stat: IFileStat | undefined;
let ext: string = resources.extname(homedir);
if (this.options.defaultUri) {
try {
stat = await this.fileService.resolve(this.options.defaultUri);
} catch (e) {
// The file or folder doesn't exist
}
if (!stat || !stat.isDirectory) {
homedir = resources.dirname(this.options.defaultUri);
this.trailing = resources.basename(this.options.defaultUri);
}
// append extension
if (isSave && !ext && this.options.filters) {
for (let i = 0; i < this.options.filters.length; i++) {
if (this.options.filters[i].extensions[0] !== '*') {
ext = '.' + this.options.filters[i].extensions[0];
this.trailing = this.trailing ? this.trailing + ext : ext;
break;
}
}
}
}
return new Promise<URI | undefined>(async (resolve) => {
this.filePickBox = this.quickInputService.createQuickPick<FileQuickPickItem>();
this.busy = true;
this.filePickBox.matchOnLabel = false;
this.filePickBox.autoFocusOnList = false;
this.filePickBox.ignoreFocusOut = true;
this.filePickBox.ok = true;
if (this.options && this.options.availableFileSystems && (this.options.availableFileSystems.length > 1)) {
this.filePickBox.customButton = true;
this.filePickBox.customLabel = nls.localize('remoteFileDialog.local', 'Show Local');
let action;
if (isSave) {
action = SaveLocalFileAction;
} else {
action = this.allowFileSelection ? (this.allowFolderSelection ? OpenLocalFileFolderAction : OpenLocalFileAction) : OpenLocalFolderAction;
}
const keybinding = this.keybindingService.lookupKeybinding(action.ID);
if (keybinding) {
const label = keybinding.getLabel();
if (label) {
this.filePickBox.customHover = format('{0} ({1})', action.LABEL, label);
}
}
}
let isResolving: number = 0;
let isAcceptHandled = false;
this.currentFolder = homedir;
this.userEnteredPathSegment = '';
this.autoCompletePathSegment = '';
this.filePickBox.title = this.options.title;
this.filePickBox.value = this.pathFromUri(this.currentFolder, true);
this.filePickBox.valueSelection = [this.filePickBox.value.length, this.filePickBox.value.length];
this.filePickBox.items = [];
function doResolve(dialog: RemoteFileDialog, uri: URI | undefined) {
resolve(uri);
dialog.contextKey.set(false);
dialog.filePickBox.dispose();
dispose(dialog.disposables);
}
this.filePickBox.onDidCustom(() => {
if (isAcceptHandled || this.busy) {
return;
}
isAcceptHandled = true;
isResolving++;
if (this.options.availableFileSystems && (this.options.availableFileSystems.length > 1)) {
this.options.availableFileSystems.shift();
}
this.options.defaultUri = undefined;
this.filePickBox.hide();
if (isSave) {
// Remove defaultUri and filters to get a consistant experience with the keybinding.
this.options.defaultUri = undefined;
this.options.filters = undefined;
return this.fileDialogService.showSaveDialog(this.options).then(result => {
doResolve(this, result);
});
} else {
return this.fileDialogService.showOpenDialog(this.options).then(result => {
doResolve(this, result ? result[0] : undefined);
});
}
});
function handleAccept(dialog: RemoteFileDialog) {
if (dialog.busy) {
// Save the accept until the file picker is not busy.
dialog.onBusyChangeEmitter.event((busy: boolean) => {
if (!busy) {
handleAccept(dialog);
}
});
return;
} else if (isAcceptHandled) {
return;
}
isAcceptHandled = true;
isResolving++;
dialog.onDidAccept().then(resolveValue => {
if (resolveValue) {
dialog.filePickBox.hide();
doResolve(dialog, resolveValue);
} else if (dialog.hidden) {
doResolve(dialog, undefined);
} else {
isResolving--;
isAcceptHandled = false;
}
});
}
this.filePickBox.onDidAccept(_ => {
handleAccept(this);
});
this.filePickBox.onDidChangeActive(i => {
isAcceptHandled = false;
// update input box to match the first selected item
if ((i.length === 1) && this.isChangeFromUser()) {
this.filePickBox.validationMessage = undefined;
this.setAutoComplete(this.constructFullUserPath(), this.userEnteredPathSegment, i[0], true);
}
});
this.filePickBox.onDidChangeValue(async value => {
try {
// onDidChangeValue can also be triggered by the auto complete, so if it looks like the auto complete, don't do anything
if (this.isChangeFromUser()) {
// If the user has just entered more bad path, don't change anything
if (!equalsIgnoreCase(value, this.constructFullUserPath()) && !this.isBadSubpath(value)) {
this.filePickBox.validationMessage = undefined;
const filePickBoxUri = this.filePickBoxValue();
let updated: UpdateResult = UpdateResult.NotUpdated;
if (!resources.isEqual(this.currentFolder, filePickBoxUri, true)) {
updated = await this.tryUpdateItems(value, filePickBoxUri);
}
if (updated === UpdateResult.NotUpdated) {
this.setActiveItems(value);
}
} else {
this.filePickBox.activeItems = [];
}
}
} catch {
// Since any text can be entered in the input box, there is potential for error causing input. If this happens, do nothing.
}
});
this.filePickBox.onDidHide(() => {
this.hidden = true;
if (isResolving === 0) {
doResolve(this, undefined);
}
});
this.filePickBox.show();
this.contextKey.set(true);
await this.updateItems(homedir, true, this.trailing);
if (this.trailing) {
this.filePickBox.valueSelection = [this.filePickBox.value.length - this.trailing.length, this.filePickBox.value.length - ext.length];
} else {
this.filePickBox.valueSelection = [this.filePickBox.value.length, this.filePickBox.value.length];
}
this.busy = false;
});
}
private isBadSubpath(value: string) {
return this.badPath && (value.length > this.badPath.length) && equalsIgnoreCase(value.substring(0, this.badPath.length), this.badPath);
}
private isChangeFromUser(): boolean {
if (equalsIgnoreCase(this.filePickBox.value, this.pathAppend(this.currentFolder, this.userEnteredPathSegment + this.autoCompletePathSegment))
&& (this.activeItem === (this.filePickBox.activeItems ? this.filePickBox.activeItems[0] : undefined))) {
return false;
}
return true;
}
private constructFullUserPath(): string {
return this.pathAppend(this.currentFolder, this.userEnteredPathSegment);
}
private filePickBoxValue(): URI {
// The file pick box can't render everything, so we use the current folder to create the uri so that it is an existing path.
const directUri = this.remoteUriFrom(this.filePickBox.value);
const currentPath = this.pathFromUri(this.currentFolder);
if (equalsIgnoreCase(this.filePickBox.value, currentPath)) {
return this.currentFolder;
}
const currentDisplayUri = this.remoteUriFrom(currentPath);
const relativePath = resources.relativePath(currentDisplayUri, directUri);
const isSameRoot = (this.filePickBox.value.length > 1 && currentPath.length > 1) ? equalsIgnoreCase(this.filePickBox.value.substr(0, 2), currentPath.substr(0, 2)) : false;
if (relativePath && isSameRoot) {
const path = resources.joinPath(this.currentFolder, relativePath);
return resources.hasTrailingPathSeparator(directUri) ? resources.addTrailingPathSeparator(path) : path;
} else {
return directUri;
}
}
private async onDidAccept(): Promise<URI | undefined> {
this.busy = true;
if (this.filePickBox.activeItems.length === 1) {
const item = this.filePickBox.selectedItems[0];
if (item.isFolder) {
if (this.trailing) {
await this.updateItems(item.uri, true, this.trailing);
} else {
// When possible, cause the update to happen by modifying the input box.
// This allows all input box updates to happen first, and uses the same code path as the user typing.
const newPath = this.pathFromUri(item.uri);
if (startsWithIgnoreCase(newPath, this.filePickBox.value) && (equalsIgnoreCase(item.label, resources.basename(item.uri)))) {
this.filePickBox.valueSelection = [this.pathFromUri(this.currentFolder).length, this.filePickBox.value.length];
this.insertText(newPath, item.label);
} else if ((item.label === '..') && startsWithIgnoreCase(this.filePickBox.value, newPath)) {
this.filePickBox.valueSelection = [newPath.length, this.filePickBox.value.length];
this.insertText(newPath, '');
} else {
await this.updateItems(item.uri, true);
}
}
this.filePickBox.busy = false;
return;
}
} else {
// If the items have updated, don't try to resolve
if ((await this.tryUpdateItems(this.filePickBox.value, this.filePickBoxValue())) !== UpdateResult.NotUpdated) {
this.filePickBox.busy = false;
return;
}
}
let resolveValue: URI | undefined;
// Find resolve value
if (this.filePickBox.activeItems.length === 0) {
resolveValue = this.filePickBoxValue();
} else if (this.filePickBox.activeItems.length === 1) {
resolveValue = this.filePickBox.selectedItems[0].uri;
}
if (resolveValue) {
resolveValue = this.addPostfix(resolveValue);
}
if (await this.validate(resolveValue)) {
this.busy = false;
return resolveValue;
}
this.busy = false;
return undefined;
}
private async tryUpdateItems(value: string, valueUri: URI): Promise<UpdateResult> {
if ((value.length > 0) && ((value[value.length - 1] === '~') || (value[0] === '~'))) {
let newDir = this.userHome;
if ((value[0] === '~') && (value.length > 1)) {
newDir = resources.joinPath(newDir, value.substring(1));
}
await this.updateItems(newDir, true);
return UpdateResult.Updated;
} else if (!resources.isEqual(this.currentFolder, valueUri, true) && (this.endsWithSlash(value) || (!resources.isEqual(this.currentFolder, resources.dirname(valueUri), true) && resources.isEqualOrParent(this.currentFolder, resources.dirname(valueUri), true)))) {
let stat: IFileStat | undefined;
try {
stat = await this.fileService.resolve(valueUri);
} catch (e) {
// do nothing
}
if (stat && stat.isDirectory && (resources.basename(valueUri) !== '.') && this.endsWithSlash(value)) {
await this.updateItems(valueUri);
return UpdateResult.Updated;
} else if (this.endsWithSlash(value)) {
// The input box contains a path that doesn't exist on the system.
this.filePickBox.validationMessage = nls.localize('remoteFileDialog.badPath', 'The path does not exist.');
// Save this bad path. It can take too long to to a stat on every user entered character, but once a user enters a bad path they are likely
// to keep typing more bad path. We can compare against this bad path and see if the user entered path starts with it.
this.badPath = value;
return UpdateResult.InvalidPath;
} else {
const inputUriDirname = resources.dirname(valueUri);
if (!resources.isEqual(resources.removeTrailingPathSeparator(this.currentFolder), inputUriDirname, true)) {
let statWithoutTrailing: IFileStat | undefined;
try {
statWithoutTrailing = await this.fileService.resolve(inputUriDirname);
} catch (e) {
// do nothing
}
if (statWithoutTrailing && statWithoutTrailing.isDirectory && (resources.basename(valueUri) !== '.')) {
await this.updateItems(inputUriDirname, false, resources.basename(valueUri));
this.badPath = undefined;
return UpdateResult.Updated;
}
}
}
}
this.badPath = undefined;
return UpdateResult.NotUpdated;
}
private setActiveItems(value: string) {
const inputBasename = resources.basename(this.remoteUriFrom(value));
// Make sure that the folder whose children we are currently viewing matches the path in the input
const userPath = this.constructFullUserPath();
if (equalsIgnoreCase(userPath, value.substring(0, userPath.length))) {
let hasMatch = false;
for (let i = 0; i < this.filePickBox.items.length; i++) {
const item = <FileQuickPickItem>this.filePickBox.items[i];
if (this.setAutoComplete(value, inputBasename, item)) {
hasMatch = true;
break;
}
}
if (!hasMatch) {
this.userEnteredPathSegment = inputBasename;
this.autoCompletePathSegment = '';
this.filePickBox.activeItems = [];
}
} else {
if (!equalsIgnoreCase(inputBasename, resources.basename(this.currentFolder))) {
this.userEnteredPathSegment = inputBasename;
} else {
this.userEnteredPathSegment = '';
}
this.autoCompletePathSegment = '';
}
}
private setAutoComplete(startingValue: string, startingBasename: string, quickPickItem: FileQuickPickItem, force: boolean = false): boolean {
if (this.busy) {
// We're in the middle of something else. Doing an auto complete now can result jumbled or incorrect autocompletes.
this.userEnteredPathSegment = startingBasename;
this.autoCompletePathSegment = '';
return false;
}
const itemBasename = this.trimTrailingSlash(quickPickItem.label);
// Either force the autocomplete, or the old value should be one smaller than the new value and match the new value.
if (itemBasename === '..') {
// Don't match on the up directory item ever.
this.userEnteredPathSegment = startingValue;
this.autoCompletePathSegment = '';
this.activeItem = quickPickItem;
if (force) {
// clear any selected text
this.insertText(this.userEnteredPathSegment, '');
}
return false;
} else if (!force && (itemBasename.length >= startingBasename.length) && equalsIgnoreCase(itemBasename.substr(0, startingBasename.length), startingBasename)) {
this.userEnteredPathSegment = startingBasename;
this.activeItem = quickPickItem;
// Changing the active items will trigger the onDidActiveItemsChanged. Clear the autocomplete first, then set it after.
this.autoCompletePathSegment = '';
this.filePickBox.activeItems = [quickPickItem];
return true;
} else if (force && (!equalsIgnoreCase(quickPickItem.label, (this.userEnteredPathSegment + this.autoCompletePathSegment)))) {
this.userEnteredPathSegment = '';
this.autoCompletePathSegment = this.trimTrailingSlash(itemBasename);
this.activeItem = quickPickItem;
this.filePickBox.valueSelection = [this.pathFromUri(this.currentFolder, true).length, this.filePickBox.value.length];
// use insert text to preserve undo buffer
this.insertText(this.pathAppend(this.currentFolder, this.autoCompletePathSegment), this.autoCompletePathSegment);
this.filePickBox.valueSelection = [this.filePickBox.value.length - this.autoCompletePathSegment.length, this.filePickBox.value.length];
return true;
} else {
this.userEnteredPathSegment = startingBasename;
this.autoCompletePathSegment = '';
return false;
}
}
private insertText(wholeValue: string, insertText: string) {
if (this.filePickBox.inputHasFocus()) {
document.execCommand('insertText', false, insertText);
} else {
this.filePickBox.value = wholeValue;
}
}
private addPostfix(uri: URI): URI {
let result = uri;
if (this.requiresTrailing && this.options.filters && this.options.filters.length > 0) {
// Make sure that the suffix is added. If the user deleted it, we automatically add it here
let hasExt: boolean = false;
const currentExt = resources.extname(uri).substr(1);
for (let i = 0; i < this.options.filters.length; i++) {
for (let j = 0; j < this.options.filters[i].extensions.length; j++) {
if ((this.options.filters[i].extensions[j] === '*') || (this.options.filters[i].extensions[j] === currentExt)) {
hasExt = true;
break;
}
}
if (hasExt) {
break;
}
}
if (!hasExt) {
result = resources.joinPath(resources.dirname(uri), resources.basename(uri) + '.' + this.options.filters[0].extensions[0]);
}
}
return result;
}
private trimTrailingSlash(path: string): string {
return ((path.length > 1) && this.endsWithSlash(path)) ? path.substr(0, path.length - 1) : path;
}
private yesNoPrompt(uri: URI, message: string): Promise<boolean> {
interface YesNoItem extends IQuickPickItem {
value: boolean;
}
const prompt = this.quickInputService.createQuickPick<YesNoItem>();
prompt.title = message;
prompt.ignoreFocusOut = true;
prompt.ok = true;
prompt.customButton = true;
prompt.customLabel = nls.localize('remoteFileDialog.cancel', 'Cancel');
prompt.value = this.pathFromUri(uri);
let isResolving = false;
return new Promise<boolean>(resolve => {
prompt.onDidAccept(() => {
isResolving = true;
prompt.hide();
resolve(true);
});
prompt.onDidHide(() => {
if (!isResolving) {
resolve(false);
}
this.filePickBox.show();
this.hidden = false;
this.filePickBox.items = this.filePickBox.items;
prompt.dispose();
});
prompt.onDidChangeValue(() => {
prompt.hide();
});
prompt.onDidCustom(() => {
prompt.hide();
});
prompt.show();
});
}
private async validate(uri: URI | undefined): Promise<boolean> {
if (uri === undefined) {
this.filePickBox.validationMessage = nls.localize('remoteFileDialog.invalidPath', 'Please enter a valid path.');
return Promise.resolve(false);
}
let stat: IFileStat | undefined;
let statDirname: IFileStat | undefined;
try {
statDirname = await this.fileService.resolve(resources.dirname(uri));
stat = await this.fileService.resolve(uri);
} catch (e) {
// do nothing
}
if (this.requiresTrailing) { // save
if (stat && stat.isDirectory) {
// Can't do this
this.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateFolder', 'The folder already exists. Please use a new file name.');
return Promise.resolve(false);
} else if (stat) {
// Replacing a file.
// Show a yes/no prompt
const message = nls.localize('remoteFileDialog.validateExisting', '{0} already exists. Are you sure you want to overwrite it?', resources.basename(uri));
return this.yesNoPrompt(uri, message);
} else if (!(isValidBasename(resources.basename(uri), await this.isWindowsOS()))) {
// Filename not allowed
this.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateBadFilename', 'Please enter a valid file name.');
return Promise.resolve(false);
} else if (!statDirname || !statDirname.isDirectory) {
// Folder to save in doesn't exist
this.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateNonexistentDir', 'Please enter a path that exists.');
return Promise.resolve(false);
}
} else { // open
if (!stat) {
// File or folder doesn't exist
this.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateNonexistentDir', 'Please enter a path that exists.');
return Promise.resolve(false);
} else if (stat.isDirectory && !this.allowFolderSelection) {
// Folder selected when folder selection not permitted
this.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateFileOnly', 'Please select a file.');
return Promise.resolve(false);
} else if (!stat.isDirectory && !this.allowFileSelection) {
// File selected when file selection not permitted
this.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateFolderOnly', 'Please select a folder.');
return Promise.resolve(false);
}
}
return Promise.resolve(true);
}
private async updateItems(newFolder: URI, force: boolean = false, trailing?: string) {
this.busy = true;
this.userEnteredPathSegment = trailing ? trailing : '';
this.autoCompletePathSegment = '';
const newValue = trailing ? this.pathFromUri(resources.joinPath(newFolder, trailing)) : this.pathFromUri(newFolder, true);
this.currentFolder = resources.addTrailingPathSeparator(newFolder, this.separator);
return this.createItems(this.currentFolder).then(items => {
this.filePickBox.items = items;
if (this.allowFolderSelection) {
this.filePickBox.activeItems = [];
}
// the user might have continued typing while we were updating. Only update the input box if it doesn't match the directory.
if (!equalsIgnoreCase(this.filePickBox.value, newValue) && force) {
this.filePickBox.valueSelection = [0, this.filePickBox.value.length];
this.insertText(newValue, newValue);
}
if (force && trailing) {
// Keep the cursor position in front of the save as name.
this.filePickBox.valueSelection = [this.filePickBox.value.length - trailing.length, this.filePickBox.value.length - trailing.length];
} else if (!trailing) {
// If there is trailing, we don't move the cursor. If there is no trailing, cursor goes at the end.
this.filePickBox.valueSelection = [this.filePickBox.value.length, this.filePickBox.value.length];
}
this.busy = false;
});
}
private pathFromUri(uri: URI, endWithSeparator: boolean = false): string {
let result: string = uri.fsPath.replace(/\n/g, '');
if (this.separator === '/') {
result = result.replace(/\\/g, this.separator);
} else {
result = result.replace(/\//g, this.separator);
}
if (endWithSeparator && !this.endsWithSlash(result)) {
result = result + this.separator;
}
return result;
}
private pathAppend(uri: URI, additional: string): string {
if ((additional === '..') || (additional === '.')) {
const basePath = this.pathFromUri(uri);
return basePath + (this.endsWithSlash(basePath) ? '' : this.separator) + additional;
} else {
return this.pathFromUri(resources.joinPath(uri, additional));
}
}
private async isWindowsOS(): Promise<boolean> {
let isWindowsOS = isWindows;
const env = await this.getRemoteAgentEnvironment();
if (env) {
isWindowsOS = env.os === OperatingSystem.Windows;
}
return isWindowsOS;
}
private endsWithSlash(s: string) {
return /[\/\\]$/.test(s);
}
private basenameWithTrailingSlash(fullPath: URI): string {
const child = this.pathFromUri(fullPath, true);
const parent = this.pathFromUri(resources.dirname(fullPath), true);
return child.substring(parent.length);
}
private createBackItem(currFolder: URI): FileQuickPickItem | null {
const parentFolder = resources.dirname(currFolder)!;
if (!resources.isEqual(currFolder, parentFolder, true)) {
return { label: '..', uri: resources.addTrailingPathSeparator(parentFolder, this.separator), isFolder: true };
}
return null;
}
private async createItems(currentFolder: URI): Promise<FileQuickPickItem[]> {
const result: FileQuickPickItem[] = [];
const backDir = this.createBackItem(currentFolder);
try {
const folder = await this.fileService.resolve(currentFolder);
const fileNames = folder.children ? folder.children.map(child => child.name) : [];
const items = await Promise.all(fileNames.map(fileName => this.createItem(fileName, currentFolder)));
for (let item of items) {
if (item) {
result.push(item);
}
}
} catch (e) {
// ignore
console.log(e);
}
const sorted = result.sort((i1, i2) => {
if (i1.isFolder !== i2.isFolder) {
return i1.isFolder ? -1 : 1;
}
const trimmed1 = this.endsWithSlash(i1.label) ? i1.label.substr(0, i1.label.length - 1) : i1.label;
const trimmed2 = this.endsWithSlash(i2.label) ? i2.label.substr(0, i2.label.length - 1) : i2.label;
return trimmed1.localeCompare(trimmed2);
});
if (backDir) {
sorted.unshift(backDir);
}
return sorted;
}
private filterFile(file: URI): boolean {
if (this.options.filters) {
const ext = resources.extname(file);
for (let i = 0; i < this.options.filters.length; i++) {
for (let j = 0; j < this.options.filters[i].extensions.length; j++) {
if (ext === ('.' + this.options.filters[i].extensions[j])) {
return true;
}
}
}
return false;
}
return true;
}
private async createItem(filename: string, parent: URI): Promise<FileQuickPickItem | undefined> {
let fullPath = resources.joinPath(parent, filename);
try {
const stat = await this.fileService.resolve(fullPath);
if (stat.isDirectory) {
filename = this.basenameWithTrailingSlash(fullPath);
fullPath = resources.addTrailingPathSeparator(fullPath, this.separator);
return { label: filename, uri: fullPath, isFolder: true, iconClasses: getIconClasses(this.modelService, this.modeService, fullPath || undefined, FileKind.FOLDER) };
} else if (!stat.isDirectory && this.allowFileSelection && this.filterFile(fullPath)) {
return { label: filename, uri: fullPath, isFolder: false, iconClasses: getIconClasses(this.modelService, this.modeService, fullPath || undefined) };
}
return undefined;
} catch (e) {
return undefined;
}
}
} | src/vs/workbench/services/dialogs/browser/remoteFileDialog.ts | 1 | https://github.com/microsoft/vscode/commit/985de26b3446636f86e2bb2b14dbeb9ec1e33207 | [
0.00030780586530454457,
0.00017268057854380459,
0.00016285671154037118,
0.00017044157721102238,
0.000017140951968031004
] |
{
"id": 13,
"code_window": [
"\t\t\t\tdialogPath = this.suggestFileName(resource);\n",
"\t\t\t}\n",
"\n",
"\t\t\ttargetResource = await this.promptForPath(resource, dialogPath);\n",
"\t\t}\n",
"\n",
"\t\tif (!targetResource) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\ttargetResource = await this.promptForPath(resource, dialogPath, options ? options.availableFileSystems : undefined);\n"
],
"file_path": "src/vs/workbench/services/textfile/common/textFileService.ts",
"type": "replace",
"edit_start_line_idx": 767
} | {
"name": "typescript",
"description": "%description%",
"displayName": "%displayName%",
"version": "1.0.0",
"author": "vscode",
"publisher": "vscode",
"license": "MIT",
"engines": {
"vscode": "*"
},
"scripts": {
"update-grammar": "node ./build/update-grammars.js"
},
"contributes": {
"languages": [
{
"id": "typescript",
"aliases": [
"TypeScript",
"ts",
"typescript"
],
"extensions": [
".ts"
],
"configuration": "./language-configuration.json"
},
{
"id": "typescriptreact",
"aliases": [
"TypeScript React",
"tsx"
],
"extensions": [
".tsx"
],
"configuration": "./language-configuration.json"
},
{
"id": "jsonc",
"filenames": [
"tsconfig.json",
"jsconfig.json"
],
"filenamePatterns": [
"tsconfig.*.json",
"tsconfig-*.json"
]
}
],
"grammars": [
{
"language": "typescript",
"scopeName": "source.ts",
"path": "./syntaxes/TypeScript.tmLanguage.json",
"tokenTypes": {
"entity.name.type.instance.jsdoc": "other",
"entity.name.function.tagged-template": "other",
"meta.import string.quoted": "other",
"variable.other.jsdoc": "other"
}
},
{
"language": "typescriptreact",
"scopeName": "source.tsx",
"path": "./syntaxes/TypeScriptReact.tmLanguage.json",
"embeddedLanguages": {
"meta.tag.tsx": "jsx-tags",
"meta.tag.without-attributes.tsx": "jsx-tags",
"meta.tag.attributes.tsx": "typescriptreact",
"meta.embedded.expression.tsx": "typescriptreact"
},
"tokenTypes": {
"entity.name.type.instance.jsdoc": "other",
"entity.name.function.tagged-template": "other",
"meta.import string.quoted": "other",
"variable.other.jsdoc": "other"
}
},
{
"scopeName": "documentation.injection",
"path": "./syntaxes/jsdoc.injection.tmLanguage.json",
"injectTo": [
"source.ts",
"source.tsx",
"source.js",
"source.js.jsx"
]
}
],
"snippets": [
{
"language": "typescript",
"path": "./snippets/typescript.json"
},
{
"language": "typescriptreact",
"path": "./snippets/typescript.json"
}
],
"jsonValidation": [
{
"fileMatch": "tsconfig.json",
"url": "https://schemastore.azurewebsites.net/schemas/json/tsconfig.json"
},
{
"fileMatch": "tsconfig.json",
"url": "./schemas/tsconfig.schema.json"
},
{
"fileMatch": "tsconfig.*.json",
"url": "https://schemastore.azurewebsites.net/schemas/json/tsconfig.json"
},
{
"fileMatch": "tsconfig-*.json",
"url": "./schemas/tsconfig.schema.json"
},
{
"fileMatch": "tsconfig-*.json",
"url": "https://schemastore.azurewebsites.net/schemas/json/tsconfig.json"
},
{
"fileMatch": "tsconfig.*.json",
"url": "./schemas/tsconfig.schema.json"
},
{
"fileMatch": "typings.json",
"url": "https://schemastore.azurewebsites.net/schemas/json/typings.json"
}
]
}
} | extensions/typescript-basics/package.json | 0 | https://github.com/microsoft/vscode/commit/985de26b3446636f86e2bb2b14dbeb9ec1e33207 | [
0.00017604141612537205,
0.00017222101450897753,
0.00016988163406495005,
0.00017202005255967379,
0.0000016564523548368015
] |
{
"id": 13,
"code_window": [
"\t\t\t\tdialogPath = this.suggestFileName(resource);\n",
"\t\t\t}\n",
"\n",
"\t\t\ttargetResource = await this.promptForPath(resource, dialogPath);\n",
"\t\t}\n",
"\n",
"\t\tif (!targetResource) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\ttargetResource = await this.promptForPath(resource, dialogPath, options ? options.availableFileSystems : undefined);\n"
],
"file_path": "src/vs/workbench/services/textfile/common/textFileService.ts",
"type": "replace",
"edit_start_line_idx": 767
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
.monaco-workbench .part.editor > .content .walkThroughContent {
box-sizing: border-box;
padding: 10px 20px;
line-height: 22px;
user-select: initial;
}
.monaco-workbench .part.editor > .content .walkThroughContent img {
max-width: 100%;
max-height: 100%;
}
.monaco-workbench .part.editor > .content .walkThroughContent a {
text-decoration: none;
}
.monaco-workbench .part.editor > .content .walkThroughContent a:focus,
.monaco-workbench .part.editor > .content .walkThroughContent input:focus,
.monaco-workbench .part.editor > .content .walkThroughContent select:focus,
.monaco-workbench .part.editor > .content .walkThroughContent textarea:focus {
outline: 1px solid -webkit-focus-ring-color;
outline-offset: -1px;
}
.monaco-workbench .part.editor > .content .walkThroughContent hr {
border: 0;
height: 2px;
border-bottom: 2px solid;
}
.monaco-workbench .part.editor > .content .walkThroughContent h1,
.monaco-workbench .part.editor > .content .walkThroughContent h2,
.monaco-workbench .part.editor > .content .walkThroughContent h3 {
font-weight: lighter;
margin-top: 20px;
margin-bottom: 10px;
}
.monaco-workbench .part.editor > .content .walkThroughContent h1 {
padding-bottom: 0.3em;
line-height: 1.2;
border-bottom-width: 1px;
border-bottom-style: solid;
font-size: 40px;
margin-bottom: 15px;
}
.monaco-workbench .part.editor > .content .walkThroughContent h2 {
font-size: 30px;
margin-top: 30px;
}
.monaco-workbench .part.editor > .content .walkThroughContent h3 {
font-size: 22px;
}
.monaco-workbench .part.editor > .content .walkThroughContent h4 {
font-size: 12px;
text-transform: uppercase;
margin-top: 30px;
margin-bottom: 10px;
}
.monaco-workbench .part.editor > .content .walkThroughContent a:hover {
text-decoration: underline;
}
.monaco-workbench .part.editor > .content .walkThroughContent table {
border-collapse: collapse;
}
.monaco-workbench .part.editor > .content .walkThroughContent table > thead > tr > th {
text-align: left;
border-bottom: 1px solid;
}
.monaco-workbench .part.editor > .content .walkThroughContent table > thead > tr > th,
.monaco-workbench .part.editor > .content .walkThroughContent table > thead > tr > td,
.monaco-workbench .part.editor > .content .walkThroughContent table > tbody > tr > th,
.monaco-workbench .part.editor > .content .walkThroughContent table > tbody > tr > td {
padding: 5px 10px;
}
.monaco-workbench .part.editor > .content .walkThroughContent table > tbody > tr + tr > td {
border-top: 1px solid;
}
.monaco-workbench .part.editor > .content .walkThroughContent blockquote {
margin: 0 7px 0 5px;
padding: 0 16px 0 10px;
border-left: 5px solid;
}
.monaco-workbench .part.editor > .content .walkThroughContent code,
.monaco-workbench .part.editor > .content .walkThroughContent .shortcut {
font-family: var(--monaco-monospace-font);
font-size: 14px;
line-height: 19px;
}
.monaco-workbench .part.editor > .content .walkThroughContent blockquote {
margin: 0 7px 0 5px;
padding: 0 16px 0 10px;
border-left: 5px solid;
}
.monaco-workbench .part.editor > .content .walkThroughContent .monaco-tokenized-source {
white-space: pre;
}
.file-icons-enabled .show-file-icons .vs_code_editor_walkthrough\.md-name-file-icon.md-ext-file-icon.ext-file-icon.markdown-lang-file-icon.file-icon::before {
content: ' ';
background-image: url('../../code-icon.svg');
}
.monaco-workbench .part.editor > .content .walkThroughContent .mac-only,
.monaco-workbench .part.editor > .content .walkThroughContent .windows-only,
.monaco-workbench .part.editor > .content .walkThroughContent .linux-only {
display: none;
}
.monaco-workbench.mac .part.editor > .content .walkThroughContent .mac-only {
display: initial;
}
.monaco-workbench.windows .part.editor > .content .walkThroughContent .windows-only {
display: initial;
}
.monaco-workbench.linux .part.editor > .content .walkThroughContent .linux-only {
display: initial;
}
.hc-black .monaco-workbench .part.editor > .content .walkThroughContent .monaco-editor {
border-width: 1px;
border-style: solid;
}
| src/vs/workbench/contrib/welcome/walkThrough/browser/walkThroughPart.css | 0 | https://github.com/microsoft/vscode/commit/985de26b3446636f86e2bb2b14dbeb9ec1e33207 | [
0.00017374464368913323,
0.00017104914877563715,
0.0001684198941802606,
0.00017081707483157516,
0.0000019777264697040664
] |
{
"id": 13,
"code_window": [
"\t\t\t\tdialogPath = this.suggestFileName(resource);\n",
"\t\t\t}\n",
"\n",
"\t\t\ttargetResource = await this.promptForPath(resource, dialogPath);\n",
"\t\t}\n",
"\n",
"\t\tif (!targetResource) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\ttargetResource = await this.promptForPath(resource, dialogPath, options ? options.availableFileSystems : undefined);\n"
],
"file_path": "src/vs/workbench/services/textfile/common/textFileService.ts",
"type": "replace",
"edit_start_line_idx": 767
} | /*---------------------------------------------------------------------------------------------
* 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 { CONTEXT_EXPRESSION_SELECTED, IViewModel, IStackFrame, IDebugSession, IThread, IExpression, IFunctionBreakpoint, CONTEXT_BREAKPOINT_SELECTED, CONTEXT_LOADED_SCRIPTS_SUPPORTED, CONTEXT_STEP_BACK_SUPPORTED, CONTEXT_FOCUSED_SESSION_IS_ATTACH, CONTEXT_RESTART_FRAME_SUPPORTED, CONTEXT_JUMP_TO_CURSOR_SUPPORTED } from 'vs/workbench/contrib/debug/common/debug';
import { IContextKeyService, IContextKey } from 'vs/platform/contextkey/common/contextkey';
import { isExtensionHostDebugging } from 'vs/workbench/contrib/debug/common/debugUtils';
export class ViewModel implements IViewModel {
firstSessionStart = true;
private _focusedStackFrame: IStackFrame | undefined;
private _focusedSession: IDebugSession | undefined;
private _focusedThread: IThread | undefined;
private selectedExpression: IExpression | undefined;
private selectedFunctionBreakpoint: IFunctionBreakpoint | undefined;
private readonly _onDidFocusSession: Emitter<IDebugSession | undefined>;
private readonly _onDidFocusStackFrame: Emitter<{ stackFrame: IStackFrame | undefined, explicit: boolean }>;
private readonly _onDidSelectExpression: Emitter<IExpression | undefined>;
private multiSessionView: boolean;
private expressionSelectedContextKey: IContextKey<boolean>;
private breakpointSelectedContextKey: IContextKey<boolean>;
private loadedScriptsSupportedContextKey: IContextKey<boolean>;
private stepBackSupportedContextKey: IContextKey<boolean>;
private focusedSessionIsAttach: IContextKey<boolean>;
private restartFrameSupportedContextKey: IContextKey<boolean>;
private jumpToCursorSupported: IContextKey<boolean>;
constructor(contextKeyService: IContextKeyService) {
this._onDidFocusSession = new Emitter<IDebugSession | undefined>();
this._onDidFocusStackFrame = new Emitter<{ stackFrame: IStackFrame, explicit: boolean }>();
this._onDidSelectExpression = new Emitter<IExpression>();
this.multiSessionView = false;
this.expressionSelectedContextKey = CONTEXT_EXPRESSION_SELECTED.bindTo(contextKeyService);
this.breakpointSelectedContextKey = CONTEXT_BREAKPOINT_SELECTED.bindTo(contextKeyService);
this.loadedScriptsSupportedContextKey = CONTEXT_LOADED_SCRIPTS_SUPPORTED.bindTo(contextKeyService);
this.stepBackSupportedContextKey = CONTEXT_STEP_BACK_SUPPORTED.bindTo(contextKeyService);
this.focusedSessionIsAttach = CONTEXT_FOCUSED_SESSION_IS_ATTACH.bindTo(contextKeyService);
this.restartFrameSupportedContextKey = CONTEXT_RESTART_FRAME_SUPPORTED.bindTo(contextKeyService);
this.jumpToCursorSupported = CONTEXT_JUMP_TO_CURSOR_SUPPORTED.bindTo(contextKeyService);
}
getId(): string {
return 'root';
}
get focusedSession(): IDebugSession | undefined {
return this._focusedSession;
}
get focusedThread(): IThread | undefined {
return this._focusedThread;
}
get focusedStackFrame(): IStackFrame | undefined {
return this._focusedStackFrame;
}
setFocus(stackFrame: IStackFrame | undefined, thread: IThread | undefined, session: IDebugSession | undefined, explicit: boolean): void {
const shouldEmitForStackFrame = this._focusedStackFrame !== stackFrame;
const shouldEmitForSession = this._focusedSession !== session;
this._focusedStackFrame = stackFrame;
this._focusedThread = thread;
this._focusedSession = session;
this.loadedScriptsSupportedContextKey.set(session ? !!session.capabilities.supportsLoadedSourcesRequest : false);
this.stepBackSupportedContextKey.set(session ? !!session.capabilities.supportsStepBack : false);
this.restartFrameSupportedContextKey.set(session ? !!session.capabilities.supportsRestartFrame : false);
this.jumpToCursorSupported.set(session ? !!session.capabilities.supportsGotoTargetsRequest : false);
const attach = !!session && !session.parentSession && session.configuration.request === 'attach' && !isExtensionHostDebugging(session.configuration);
this.focusedSessionIsAttach.set(attach);
if (shouldEmitForSession) {
this._onDidFocusSession.fire(session);
}
if (shouldEmitForStackFrame) {
this._onDidFocusStackFrame.fire({ stackFrame, explicit });
}
}
get onDidFocusSession(): Event<IDebugSession | undefined> {
return this._onDidFocusSession.event;
}
get onDidFocusStackFrame(): Event<{ stackFrame: IStackFrame | undefined, explicit: boolean }> {
return this._onDidFocusStackFrame.event;
}
getSelectedExpression(): IExpression | undefined {
return this.selectedExpression;
}
setSelectedExpression(expression: IExpression | undefined) {
this.selectedExpression = expression;
this.expressionSelectedContextKey.set(!!expression);
this._onDidSelectExpression.fire(expression);
}
get onDidSelectExpression(): Event<IExpression | undefined> {
return this._onDidSelectExpression.event;
}
getSelectedFunctionBreakpoint(): IFunctionBreakpoint | undefined {
return this.selectedFunctionBreakpoint;
}
setSelectedFunctionBreakpoint(functionBreakpoint: IFunctionBreakpoint | undefined): void {
this.selectedFunctionBreakpoint = functionBreakpoint;
this.breakpointSelectedContextKey.set(!!functionBreakpoint);
}
isMultiSessionView(): boolean {
return this.multiSessionView;
}
setMultiSessionView(isMultiSessionView: boolean): void {
this.multiSessionView = isMultiSessionView;
}
}
| src/vs/workbench/contrib/debug/common/debugViewModel.ts | 0 | https://github.com/microsoft/vscode/commit/985de26b3446636f86e2bb2b14dbeb9ec1e33207 | [
0.00017307448433712125,
0.00016996162594296038,
0.00016518542543053627,
0.00017067624139599502,
0.0000022952067411097232
] |
{
"id": 14,
"code_window": [
"\toverwriteReadonly?: boolean;\n",
"\toverwriteEncoding?: boolean;\n",
"\tskipSaveParticipants?: boolean;\n",
"\twriteElevated?: boolean;\n",
"}\n",
"\n",
"export interface ILoadOptions {\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tavailableFileSystems?: string[];\n"
],
"file_path": "src/vs/workbench/services/textfile/common/textfiles.ts",
"type": "add",
"edit_start_line_idx": 430
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as nls from 'vs/nls';
import { URI } from 'vs/base/common/uri';
import * as errors from 'vs/base/common/errors';
import * as objects from 'vs/base/common/objects';
import { Event, Emitter } from 'vs/base/common/event';
import * as platform from 'vs/base/common/platform';
import { IWindowsService } from 'vs/platform/windows/common/windows';
import { IBackupFileService } from 'vs/workbench/services/backup/common/backup';
import { IResult, ITextFileOperationResult, ITextFileService, ITextFileStreamContent, IAutoSaveConfiguration, AutoSaveMode, SaveReason, ITextFileEditorModelManager, ITextFileEditorModel, ModelState, ISaveOptions, AutoSaveContext, IWillMoveEvent, ITextFileContent, IResourceEncodings, IReadTextFileOptions, IWriteTextFileOptions, toBufferOrReadable, TextFileOperationError, TextFileOperationResult } from 'vs/workbench/services/textfile/common/textfiles';
import { ConfirmResult, IRevertOptions } from 'vs/workbench/common/editor';
import { ILifecycleService, ShutdownReason, LifecyclePhase } from 'vs/platform/lifecycle/common/lifecycle';
import { IWorkspaceContextService, WorkbenchState } from 'vs/platform/workspace/common/workspace';
import { IFileService, IFilesConfiguration, FileOperationError, FileOperationResult, AutoSaveConfiguration, HotExitConfiguration, IFileStatWithMetadata, ICreateFileOptions } from 'vs/platform/files/common/files';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { Disposable } from 'vs/base/common/lifecycle';
import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService';
import { IUntitledEditorService } from 'vs/workbench/services/untitled/common/untitledEditorService';
import { UntitledEditorModel } from 'vs/workbench/common/editor/untitledEditorModel';
import { TextFileEditorModelManager } from 'vs/workbench/services/textfile/common/textFileEditorModelManager';
import { IInstantiationService, ServiceIdentifier } from 'vs/platform/instantiation/common/instantiation';
import { ResourceMap } from 'vs/base/common/map';
import { Schemas } from 'vs/base/common/network';
import { IHistoryService } from 'vs/workbench/services/history/common/history';
import { IContextKey, IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { createTextBufferFactoryFromSnapshot, createTextBufferFactoryFromStream } from 'vs/editor/common/model/textModel';
import { IModelService } from 'vs/editor/common/services/modelService';
import { INotificationService, Severity } from 'vs/platform/notification/common/notification';
import { isEqualOrParent, isEqual, joinPath, dirname, extname, basename, toLocalResource } from 'vs/base/common/resources';
import { posix } from 'vs/base/common/path';
import { getConfirmMessage, IDialogService, IFileDialogService, ISaveDialogOptions, IConfirmation } from 'vs/platform/dialogs/common/dialogs';
import { IModeService } from 'vs/editor/common/services/modeService';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { coalesce } from 'vs/base/common/arrays';
import { trim } from 'vs/base/common/strings';
import { VSBuffer } from 'vs/base/common/buffer';
import { ITextSnapshot } from 'vs/editor/common/model';
import { ITextResourceConfigurationService } from 'vs/editor/common/services/resourceConfiguration';
import { PLAINTEXT_MODE_ID } from 'vs/editor/common/modes/modesRegistry';
/**
* The workbench file service implementation implements the raw file service spec and adds additional methods on top.
*/
export abstract class TextFileService extends Disposable implements ITextFileService {
_serviceBrand: ServiceIdentifier<any>;
private readonly _onAutoSaveConfigurationChange: Emitter<IAutoSaveConfiguration> = this._register(new Emitter<IAutoSaveConfiguration>());
get onAutoSaveConfigurationChange(): Event<IAutoSaveConfiguration> { return this._onAutoSaveConfigurationChange.event; }
private readonly _onFilesAssociationChange: Emitter<void> = this._register(new Emitter<void>());
get onFilesAssociationChange(): Event<void> { return this._onFilesAssociationChange.event; }
private readonly _onWillMove = this._register(new Emitter<IWillMoveEvent>());
get onWillMove(): Event<IWillMoveEvent> { return this._onWillMove.event; }
private _models: TextFileEditorModelManager;
get models(): ITextFileEditorModelManager { return this._models; }
abstract get encoding(): IResourceEncodings;
private currentFilesAssociationConfig: { [key: string]: string; };
private configuredAutoSaveDelay?: number;
private configuredAutoSaveOnFocusChange: boolean;
private configuredAutoSaveOnWindowChange: boolean;
private configuredHotExit: string;
private autoSaveContext: IContextKey<string>;
constructor(
@IWorkspaceContextService private readonly contextService: IWorkspaceContextService,
@IFileService protected readonly fileService: IFileService,
@IUntitledEditorService private readonly untitledEditorService: IUntitledEditorService,
@ILifecycleService private readonly lifecycleService: ILifecycleService,
@IInstantiationService protected instantiationService: IInstantiationService,
@IConfigurationService private readonly configurationService: IConfigurationService,
@IModeService private readonly modeService: IModeService,
@IModelService private readonly modelService: IModelService,
@IWorkbenchEnvironmentService protected readonly environmentService: IWorkbenchEnvironmentService,
@INotificationService private readonly notificationService: INotificationService,
@IBackupFileService private readonly backupFileService: IBackupFileService,
@IWindowsService private readonly windowsService: IWindowsService,
@IHistoryService private readonly historyService: IHistoryService,
@IContextKeyService contextKeyService: IContextKeyService,
@IDialogService private readonly dialogService: IDialogService,
@IFileDialogService private readonly fileDialogService: IFileDialogService,
@IEditorService private readonly editorService: IEditorService,
@ITextResourceConfigurationService protected readonly textResourceConfigurationService: ITextResourceConfigurationService
) {
super();
this._models = this._register(instantiationService.createInstance(TextFileEditorModelManager));
this.autoSaveContext = AutoSaveContext.bindTo(contextKeyService);
const configuration = configurationService.getValue<IFilesConfiguration>();
this.currentFilesAssociationConfig = configuration && configuration.files && configuration.files.associations;
this.onFilesConfigurationChange(configuration);
this.registerListeners();
}
//#region event handling
private registerListeners(): void {
// Lifecycle
this.lifecycleService.onBeforeShutdown(event => event.veto(this.beforeShutdown(event.reason)));
this.lifecycleService.onShutdown(this.dispose, this);
// Files configuration changes
this._register(this.configurationService.onDidChangeConfiguration(e => {
if (e.affectsConfiguration('files')) {
this.onFilesConfigurationChange(this.configurationService.getValue<IFilesConfiguration>());
}
}));
}
private beforeShutdown(reason: ShutdownReason): boolean | Promise<boolean> {
// Dirty files need treatment on shutdown
const dirty = this.getDirty();
if (dirty.length) {
// If auto save is enabled, save all files and then check again for dirty files
// We DO NOT run any save participant if we are in the shutdown phase for performance reasons
if (this.getAutoSaveMode() !== AutoSaveMode.OFF) {
return this.saveAll(false /* files only */, { skipSaveParticipants: true }).then(() => {
// If we still have dirty files, we either have untitled ones or files that cannot be saved
const remainingDirty = this.getDirty();
if (remainingDirty.length) {
return this.handleDirtyBeforeShutdown(remainingDirty, reason);
}
return false;
});
}
// Auto save is not enabled
return this.handleDirtyBeforeShutdown(dirty, reason);
}
// No dirty files: no veto
return this.noVeto({ cleanUpBackups: true });
}
private handleDirtyBeforeShutdown(dirty: URI[], reason: ShutdownReason): boolean | Promise<boolean> {
// If hot exit is enabled, backup dirty files and allow to exit without confirmation
if (this.isHotExitEnabled) {
return this.backupBeforeShutdown(dirty, this.models, reason).then(didBackup => {
if (didBackup) {
return this.noVeto({ cleanUpBackups: false }); // no veto and no backup cleanup (since backup was successful)
}
// since a backup did not happen, we have to confirm for the dirty files now
return this.confirmBeforeShutdown();
}, errors => {
const firstError = errors[0];
this.notificationService.error(nls.localize('files.backup.failSave', "Files that are dirty could not be written to the backup location (Error: {0}). Try saving your files first and then exit.", firstError.message));
return true; // veto, the backups failed
});
}
// Otherwise just confirm from the user what to do with the dirty files
return this.confirmBeforeShutdown();
}
private async backupBeforeShutdown(dirtyToBackup: URI[], textFileEditorModelManager: ITextFileEditorModelManager, reason: ShutdownReason): Promise<boolean> {
const windowCount = await this.windowsService.getWindowCount();
// When quit is requested skip the confirm callback and attempt to backup all workspaces.
// When quit is not requested the confirm callback should be shown when the window being
// closed is the only VS Code window open, except for on Mac where hot exit is only
// ever activated when quit is requested.
let doBackup: boolean | undefined;
switch (reason) {
case ShutdownReason.CLOSE:
if (this.contextService.getWorkbenchState() !== WorkbenchState.EMPTY && this.configuredHotExit === HotExitConfiguration.ON_EXIT_AND_WINDOW_CLOSE) {
doBackup = true; // backup if a folder is open and onExitAndWindowClose is configured
} else if (windowCount > 1 || platform.isMacintosh) {
doBackup = false; // do not backup if a window is closed that does not cause quitting of the application
} else {
doBackup = true; // backup if last window is closed on win/linux where the application quits right after
}
break;
case ShutdownReason.QUIT:
doBackup = true; // backup because next start we restore all backups
break;
case ShutdownReason.RELOAD:
doBackup = true; // backup because after window reload, backups restore
break;
case ShutdownReason.LOAD:
if (this.contextService.getWorkbenchState() !== WorkbenchState.EMPTY && this.configuredHotExit === HotExitConfiguration.ON_EXIT_AND_WINDOW_CLOSE) {
doBackup = true; // backup if a folder is open and onExitAndWindowClose is configured
} else {
doBackup = false; // do not backup because we are switching contexts
}
break;
}
if (!doBackup) {
return false;
}
await this.backupAll(dirtyToBackup, textFileEditorModelManager);
return true;
}
private backupAll(dirtyToBackup: URI[], textFileEditorModelManager: ITextFileEditorModelManager): Promise<void> {
// split up between files and untitled
const filesToBackup: ITextFileEditorModel[] = [];
const untitledToBackup: URI[] = [];
dirtyToBackup.forEach(s => {
if (this.fileService.canHandleResource(s)) {
const model = textFileEditorModelManager.get(s);
if (model) {
filesToBackup.push(model);
}
} else if (s.scheme === Schemas.untitled) {
untitledToBackup.push(s);
}
});
return this.doBackupAll(filesToBackup, untitledToBackup);
}
private async doBackupAll(dirtyFileModels: ITextFileEditorModel[], untitledResources: URI[]): Promise<void> {
// Handle file resources first
await Promise.all(dirtyFileModels.map(model => model.backup()));
// Handle untitled resources
await Promise.all(untitledResources
.filter(untitled => this.untitledEditorService.exists(untitled))
.map(async untitled => (await this.untitledEditorService.loadOrCreate({ resource: untitled })).backup()));
}
private async confirmBeforeShutdown(): Promise<boolean> {
const confirm = await this.confirmSave();
// Save
if (confirm === ConfirmResult.SAVE) {
const result = await this.saveAll(true /* includeUntitled */, { skipSaveParticipants: true });
if (result.results.some(r => !r.success)) {
return true; // veto if some saves failed
}
return this.noVeto({ cleanUpBackups: true });
}
// Don't Save
else if (confirm === ConfirmResult.DONT_SAVE) {
// Make sure to revert untitled so that they do not restore
// see https://github.com/Microsoft/vscode/issues/29572
this.untitledEditorService.revertAll();
return this.noVeto({ cleanUpBackups: true });
}
// Cancel
else if (confirm === ConfirmResult.CANCEL) {
return true; // veto
}
return false;
}
private noVeto(options: { cleanUpBackups: boolean }): boolean | Promise<boolean> {
if (!options.cleanUpBackups) {
return false;
}
if (this.lifecycleService.phase < LifecyclePhase.Restored) {
return false; // if editors have not restored, we are not up to speed with backups and thus should not clean them
}
return this.cleanupBackupsBeforeShutdown().then(() => false, () => false);
}
protected async cleanupBackupsBeforeShutdown(): Promise<void> {
if (this.environmentService.isExtensionDevelopment) {
return;
}
await this.backupFileService.discardAllWorkspaceBackups();
}
protected onFilesConfigurationChange(configuration: IFilesConfiguration): void {
const wasAutoSaveEnabled = (this.getAutoSaveMode() !== AutoSaveMode.OFF);
const autoSaveMode = (configuration && configuration.files && configuration.files.autoSave) || AutoSaveConfiguration.OFF;
this.autoSaveContext.set(autoSaveMode);
switch (autoSaveMode) {
case AutoSaveConfiguration.AFTER_DELAY:
this.configuredAutoSaveDelay = configuration && configuration.files && configuration.files.autoSaveDelay;
this.configuredAutoSaveOnFocusChange = false;
this.configuredAutoSaveOnWindowChange = false;
break;
case AutoSaveConfiguration.ON_FOCUS_CHANGE:
this.configuredAutoSaveDelay = undefined;
this.configuredAutoSaveOnFocusChange = true;
this.configuredAutoSaveOnWindowChange = false;
break;
case AutoSaveConfiguration.ON_WINDOW_CHANGE:
this.configuredAutoSaveDelay = undefined;
this.configuredAutoSaveOnFocusChange = false;
this.configuredAutoSaveOnWindowChange = true;
break;
default:
this.configuredAutoSaveDelay = undefined;
this.configuredAutoSaveOnFocusChange = false;
this.configuredAutoSaveOnWindowChange = false;
break;
}
// Emit as event
this._onAutoSaveConfigurationChange.fire(this.getAutoSaveConfiguration());
// save all dirty when enabling auto save
if (!wasAutoSaveEnabled && this.getAutoSaveMode() !== AutoSaveMode.OFF) {
this.saveAll();
}
// Check for change in files associations
const filesAssociation = configuration && configuration.files && configuration.files.associations;
if (!objects.equals(this.currentFilesAssociationConfig, filesAssociation)) {
this.currentFilesAssociationConfig = filesAssociation;
this._onFilesAssociationChange.fire();
}
// Hot exit
const hotExitMode = configuration && configuration.files && configuration.files.hotExit;
if (hotExitMode === HotExitConfiguration.OFF || hotExitMode === HotExitConfiguration.ON_EXIT_AND_WINDOW_CLOSE) {
this.configuredHotExit = hotExitMode;
} else {
this.configuredHotExit = HotExitConfiguration.ON_EXIT;
}
}
//#endregion
//#region primitives (read, create, move, delete, update)
async read(resource: URI, options?: IReadTextFileOptions): Promise<ITextFileContent> {
const content = await this.fileService.readFile(resource, options);
// in case of acceptTextOnly: true, we check the first
// chunk for possibly being binary by looking for 0-bytes
// we limit this check to the first 512 bytes
this.validateBinary(content.value, options);
return {
...content,
encoding: 'utf8',
value: content.value.toString()
};
}
async readStream(resource: URI, options?: IReadTextFileOptions): Promise<ITextFileStreamContent> {
const stream = await this.fileService.readFileStream(resource, options);
// in case of acceptTextOnly: true, we check the first
// chunk for possibly being binary by looking for 0-bytes
// we limit this check to the first 512 bytes
let checkedForBinary = false;
const throwOnBinary = (data: VSBuffer): Error | undefined => {
if (!checkedForBinary) {
checkedForBinary = true;
this.validateBinary(data, options);
}
return undefined;
};
return {
...stream,
encoding: 'utf8',
value: await createTextBufferFactoryFromStream(stream.value, undefined, options && options.acceptTextOnly ? throwOnBinary : undefined)
};
}
private validateBinary(buffer: VSBuffer, options?: IReadTextFileOptions): void {
if (!options || !options.acceptTextOnly) {
return; // no validation needed
}
// in case of acceptTextOnly: true, we check the first
// chunk for possibly being binary by looking for 0-bytes
// we limit this check to the first 512 bytes
for (let i = 0; i < buffer.byteLength && i < 512; i++) {
if (buffer.readUInt8(i) === 0) {
throw new TextFileOperationError(nls.localize('fileBinaryError', "File seems to be binary and cannot be opened as text"), TextFileOperationResult.FILE_IS_BINARY, options);
}
}
}
async create(resource: URI, value?: string | ITextSnapshot, options?: ICreateFileOptions): Promise<IFileStatWithMetadata> {
const stat = await this.doCreate(resource, value, options);
// If we had an existing model for the given resource, load
// it again to make sure it is up to date with the contents
// we just wrote into the underlying resource by calling
// revert()
const existingModel = this.models.get(resource);
if (existingModel && !existingModel.isDisposed()) {
await existingModel.revert();
}
return stat;
}
protected doCreate(resource: URI, value?: string | ITextSnapshot, options?: ICreateFileOptions): Promise<IFileStatWithMetadata> {
return this.fileService.createFile(resource, toBufferOrReadable(value), options);
}
async write(resource: URI, value: string | ITextSnapshot, options?: IWriteTextFileOptions): Promise<IFileStatWithMetadata> {
return this.fileService.writeFile(resource, toBufferOrReadable(value), options);
}
async delete(resource: URI, options?: { useTrash?: boolean, recursive?: boolean }): Promise<void> {
const dirtyFiles = this.getDirty().filter(dirty => isEqualOrParent(dirty, resource, !platform.isLinux /* ignorecase */));
await this.revertAll(dirtyFiles, { soft: true });
return this.fileService.del(resource, options);
}
async move(source: URI, target: URI, overwrite?: boolean): Promise<IFileStatWithMetadata> {
const waitForPromises: Promise<unknown>[] = [];
// Event
this._onWillMove.fire({
oldResource: source,
newResource: target,
waitUntil(promise: Promise<unknown>) {
waitForPromises.push(promise.then(undefined, errors.onUnexpectedError));
}
});
// prevent async waitUntil-calls
Object.freeze(waitForPromises);
await Promise.all(waitForPromises);
// Handle target models if existing (if target URI is a folder, this can be multiple)
const dirtyTargetModels = this.getDirtyFileModels().filter(model => isEqualOrParent(model.getResource(), target, false /* do not ignorecase, see https://github.com/Microsoft/vscode/issues/56384 */));
if (dirtyTargetModels.length) {
await this.revertAll(dirtyTargetModels.map(targetModel => targetModel.getResource()), { soft: true });
}
// Handle dirty source models if existing (if source URI is a folder, this can be multiple)
const dirtySourceModels = this.getDirtyFileModels().filter(model => isEqualOrParent(model.getResource(), source, !platform.isLinux /* ignorecase */));
const dirtyTargetModelUris: URI[] = [];
if (dirtySourceModels.length) {
await Promise.all(dirtySourceModels.map(async sourceModel => {
const sourceModelResource = sourceModel.getResource();
let targetModelResource: URI;
// If the source is the actual model, just use target as new resource
if (isEqual(sourceModelResource, source, !platform.isLinux /* ignorecase */)) {
targetModelResource = target;
}
// Otherwise a parent folder of the source is being moved, so we need
// to compute the target resource based on that
else {
targetModelResource = sourceModelResource.with({ path: joinPath(target, sourceModelResource.path.substr(source.path.length + 1)).path });
}
// Remember as dirty target model to load after the operation
dirtyTargetModelUris.push(targetModelResource);
// Backup dirty source model to the target resource it will become later
await sourceModel.backup(targetModelResource);
}));
}
// Soft revert the dirty source files if any
await this.revertAll(dirtySourceModels.map(dirtySourceModel => dirtySourceModel.getResource()), { soft: true });
// Rename to target
try {
const stat = await this.fileService.move(source, target, overwrite);
// Load models that were dirty before
await Promise.all(dirtyTargetModelUris.map(dirtyTargetModel => this.models.loadOrCreate(dirtyTargetModel)));
return stat;
} catch (error) {
// In case of an error, discard any dirty target backups that were made
await Promise.all(dirtyTargetModelUris.map(dirtyTargetModel => this.backupFileService.discardResourceBackup(dirtyTargetModel)));
throw error;
}
}
//#endregion
//#region save/revert
async save(resource: URI, options?: ISaveOptions): Promise<boolean> {
// Run a forced save if we detect the file is not dirty so that save participants can still run
if (options && options.force && this.fileService.canHandleResource(resource) && !this.isDirty(resource)) {
const model = this._models.get(resource);
if (model) {
options.reason = SaveReason.EXPLICIT;
await model.save(options);
return !model.isDirty();
}
}
const result = await this.saveAll([resource], options);
return result.results.length === 1 && !!result.results[0].success;
}
async confirmSave(resources?: URI[]): Promise<ConfirmResult> {
if (this.environmentService.isExtensionDevelopment) {
return ConfirmResult.DONT_SAVE; // no veto when we are in extension dev mode because we cannot assum we run interactive (e.g. tests)
}
const resourcesToConfirm = this.getDirty(resources);
if (resourcesToConfirm.length === 0) {
return ConfirmResult.DONT_SAVE;
}
const message = resourcesToConfirm.length === 1 ? nls.localize('saveChangesMessage', "Do you want to save the changes you made to {0}?", basename(resourcesToConfirm[0]))
: getConfirmMessage(nls.localize('saveChangesMessages', "Do you want to save the changes to the following {0} files?", resourcesToConfirm.length), resourcesToConfirm);
const buttons: string[] = [
resourcesToConfirm.length > 1 ? nls.localize({ key: 'saveAll', comment: ['&& denotes a mnemonic'] }, "&&Save All") : nls.localize({ key: 'save', comment: ['&& denotes a mnemonic'] }, "&&Save"),
nls.localize({ key: 'dontSave', comment: ['&& denotes a mnemonic'] }, "Do&&n't Save"),
nls.localize('cancel', "Cancel")
];
const index = await this.dialogService.show(Severity.Warning, message, buttons, {
cancelId: 2,
detail: nls.localize('saveChangesDetail', "Your changes will be lost if you don't save them.")
});
switch (index) {
case 0: return ConfirmResult.SAVE;
case 1: return ConfirmResult.DONT_SAVE;
default: return ConfirmResult.CANCEL;
}
}
async confirmOverwrite(resource: URI): Promise<boolean> {
const confirm: IConfirmation = {
message: nls.localize('confirmOverwrite', "'{0}' already exists. Do you want to replace it?", basename(resource)),
detail: nls.localize('irreversible', "A file or folder with the same name already exists in the folder {0}. Replacing it will overwrite its current contents.", basename(dirname(resource))),
primaryButton: nls.localize({ key: 'replaceButtonLabel', comment: ['&& denotes a mnemonic'] }, "&&Replace"),
type: 'warning'
};
return (await this.dialogService.confirm(confirm)).confirmed;
}
saveAll(includeUntitled?: boolean, options?: ISaveOptions): Promise<ITextFileOperationResult>;
saveAll(resources: URI[], options?: ISaveOptions): Promise<ITextFileOperationResult>;
saveAll(arg1?: boolean | URI[], options?: ISaveOptions): Promise<ITextFileOperationResult> {
// get all dirty
let toSave: URI[] = [];
if (Array.isArray(arg1)) {
toSave = this.getDirty(arg1);
} else {
toSave = this.getDirty();
}
// split up between files and untitled
const filesToSave: URI[] = [];
const untitledToSave: URI[] = [];
toSave.forEach(s => {
if ((Array.isArray(arg1) || arg1 === true /* includeUntitled */) && s.scheme === Schemas.untitled) {
untitledToSave.push(s);
} else {
filesToSave.push(s);
}
});
return this.doSaveAll(filesToSave, untitledToSave, options);
}
private async doSaveAll(fileResources: URI[], untitledResources: URI[], options?: ISaveOptions): Promise<ITextFileOperationResult> {
// Handle files first that can just be saved
const result = await this.doSaveAllFiles(fileResources, options);
// Preflight for untitled to handle cancellation from the dialog
const targetsForUntitled: URI[] = [];
for (const untitled of untitledResources) {
if (this.untitledEditorService.exists(untitled)) {
let targetUri: URI;
// Untitled with associated file path don't need to prompt
if (this.untitledEditorService.hasAssociatedFilePath(untitled)) {
targetUri = toLocalResource(untitled, this.environmentService.configuration.remoteAuthority);
}
// Otherwise ask user
else {
const targetPath = await this.promptForPath(untitled, this.suggestFileName(untitled));
if (!targetPath) {
return { results: [...fileResources, ...untitledResources].map(r => ({ source: r })) };
}
targetUri = targetPath;
}
targetsForUntitled.push(targetUri);
}
}
// Handle untitled
await Promise.all(targetsForUntitled.map(async (target, index) => {
const uri = await this.saveAs(untitledResources[index], target);
result.results.push({
source: untitledResources[index],
target: uri,
success: !!uri
});
}));
return result;
}
protected async promptForPath(resource: URI, defaultUri: URI): Promise<URI | undefined> {
// Help user to find a name for the file by opening it first
await this.editorService.openEditor({ resource, options: { revealIfOpened: true, preserveFocus: true, } });
return this.fileDialogService.pickFileToSave(this.getSaveDialogOptions(defaultUri));
}
private getSaveDialogOptions(defaultUri: URI): ISaveDialogOptions {
const options: ISaveDialogOptions = {
defaultUri,
title: nls.localize('saveAsTitle', "Save As")
};
// Filters are only enabled on Windows where they work properly
if (!platform.isWindows) {
return options;
}
interface IFilter { name: string; extensions: string[]; }
// Build the file filter by using our known languages
const ext: string | undefined = defaultUri ? extname(defaultUri) : undefined;
let matchingFilter: IFilter | undefined;
const filters: IFilter[] = coalesce(this.modeService.getRegisteredLanguageNames().map(languageName => {
const extensions = this.modeService.getExtensions(languageName);
if (!extensions || !extensions.length) {
return null;
}
const filter: IFilter = { name: languageName, extensions: extensions.slice(0, 10).map(e => trim(e, '.')) };
if (ext && extensions.indexOf(ext) >= 0) {
matchingFilter = filter;
return null; // matching filter will be added last to the top
}
return filter;
}));
// Filters are a bit weird on Windows, based on having a match or not:
// Match: we put the matching filter first so that it shows up selected and the all files last
// No match: we put the all files filter first
const allFilesFilter = { name: nls.localize('allFiles', "All Files"), extensions: ['*'] };
if (matchingFilter) {
filters.unshift(matchingFilter);
filters.unshift(allFilesFilter);
} else {
filters.unshift(allFilesFilter);
}
// Allow to save file without extension
filters.push({ name: nls.localize('noExt', "No Extension"), extensions: [''] });
options.filters = filters;
return options;
}
private async doSaveAllFiles(resources?: URI[], options: ISaveOptions = Object.create(null)): Promise<ITextFileOperationResult> {
const dirtyFileModels = this.getDirtyFileModels(Array.isArray(resources) ? resources : undefined /* Save All */)
.filter(model => {
if ((model.hasState(ModelState.CONFLICT) || model.hasState(ModelState.ERROR)) && (options.reason === SaveReason.AUTO || options.reason === SaveReason.FOCUS_CHANGE || options.reason === SaveReason.WINDOW_CHANGE)) {
return false; // if model is in save conflict or error, do not save unless save reason is explicit or not provided at all
}
return true;
});
const mapResourceToResult = new ResourceMap<IResult>();
dirtyFileModels.forEach(m => {
mapResourceToResult.set(m.getResource(), {
source: m.getResource()
});
});
await Promise.all(dirtyFileModels.map(async model => {
await model.save(options);
if (!model.isDirty()) {
const result = mapResourceToResult.get(model.getResource());
if (result) {
result.success = true;
}
}
}));
return { results: mapResourceToResult.values() };
}
private getFileModels(arg1?: URI | URI[]): ITextFileEditorModel[] {
if (Array.isArray(arg1)) {
const models: ITextFileEditorModel[] = [];
arg1.forEach(resource => {
models.push(...this.getFileModels(resource));
});
return models;
}
return this._models.getAll(arg1);
}
private getDirtyFileModels(resources?: URI | URI[]): ITextFileEditorModel[] {
return this.getFileModels(resources).filter(model => model.isDirty());
}
async saveAs(resource: URI, targetResource?: URI, options?: ISaveOptions): Promise<URI | undefined> {
// Get to target resource
if (!targetResource) {
let dialogPath = resource;
if (resource.scheme === Schemas.untitled) {
dialogPath = this.suggestFileName(resource);
}
targetResource = await this.promptForPath(resource, dialogPath);
}
if (!targetResource) {
return; // user canceled
}
// Just save if target is same as models own resource
if (resource.toString() === targetResource.toString()) {
await this.save(resource, options);
return resource;
}
// Do it
return this.doSaveAs(resource, targetResource, options);
}
private async doSaveAs(resource: URI, target: URI, options?: ISaveOptions): Promise<URI> {
// Retrieve text model from provided resource if any
let model: ITextFileEditorModel | UntitledEditorModel | undefined;
if (this.fileService.canHandleResource(resource)) {
model = this._models.get(resource);
} else if (resource.scheme === Schemas.untitled && this.untitledEditorService.exists(resource)) {
model = await this.untitledEditorService.loadOrCreate({ resource });
}
// We have a model: Use it (can be null e.g. if this file is binary and not a text file or was never opened before)
let result: boolean;
if (model) {
result = await this.doSaveTextFileAs(model, resource, target, options);
}
// Otherwise we can only copy
else {
await this.fileService.copy(resource, target);
result = true;
}
// Return early if the operation was not running
if (!result) {
return target;
}
// Revert the source
await this.revert(resource);
return target;
}
private async doSaveTextFileAs(sourceModel: ITextFileEditorModel | UntitledEditorModel, resource: URI, target: URI, options?: ISaveOptions): Promise<boolean> {
// Prefer an existing model if it is already loaded for the given target resource
let targetExists: boolean = false;
let targetModel = this.models.get(target);
if (targetModel && targetModel.isResolved()) {
targetExists = true;
}
// Otherwise create the target file empty if it does not exist already and resolve it from there
else {
targetExists = await this.fileService.exists(target);
// create target model adhoc if file does not exist yet
if (!targetExists) {
await this.create(target, '');
}
targetModel = await this.models.loadOrCreate(target);
}
try {
// Confirm to overwrite if we have an untitled file with associated file where
// the file actually exists on disk and we are instructed to save to that file
// path. This can happen if the file was created after the untitled file was opened.
// See https://github.com/Microsoft/vscode/issues/67946
let write: boolean;
if (sourceModel instanceof UntitledEditorModel && sourceModel.hasAssociatedFilePath && targetExists && isEqual(target, toLocalResource(sourceModel.getResource(), this.environmentService.configuration.remoteAuthority))) {
write = await this.confirmOverwrite(target);
} else {
write = true;
}
if (!write) {
return false;
}
// take over encoding, mode and model value from source model
targetModel.updatePreferredEncoding(sourceModel.getEncoding());
if (sourceModel.isResolved() && targetModel.isResolved()) {
this.modelService.updateModel(targetModel.textEditorModel, createTextBufferFactoryFromSnapshot(sourceModel.createSnapshot()));
const mode = sourceModel.textEditorModel.getLanguageIdentifier();
if (mode.language !== PLAINTEXT_MODE_ID) {
targetModel.textEditorModel.setMode(mode); // only use if more specific than plain/text
}
}
// save model
await targetModel.save(options);
return true;
} catch (error) {
// binary model: delete the file and run the operation again
if (
(<TextFileOperationError>error).textFileOperationResult === TextFileOperationResult.FILE_IS_BINARY ||
(<FileOperationError>error).fileOperationResult === FileOperationResult.FILE_TOO_LARGE
) {
await this.fileService.del(target);
return this.doSaveTextFileAs(sourceModel, resource, target, options);
}
throw error;
}
}
private suggestFileName(untitledResource: URI): URI {
const untitledFileName = this.untitledEditorService.suggestFileName(untitledResource);
const remoteAuthority = this.environmentService.configuration.remoteAuthority;
const schemeFilter = remoteAuthority ? Schemas.vscodeRemote : Schemas.file;
const lastActiveFile = this.historyService.getLastActiveFile(schemeFilter);
if (lastActiveFile) {
const lastDir = dirname(lastActiveFile);
return joinPath(lastDir, untitledFileName);
}
const lastActiveFolder = this.historyService.getLastActiveWorkspaceRoot(schemeFilter);
if (lastActiveFolder) {
return joinPath(lastActiveFolder, untitledFileName);
}
return schemeFilter === Schemas.file ? URI.file(untitledFileName) : URI.from({ scheme: schemeFilter, authority: remoteAuthority, path: posix.sep + untitledFileName });
}
async revert(resource: URI, options?: IRevertOptions): Promise<boolean> {
const result = await this.revertAll([resource], options);
return result.results.length === 1 && !!result.results[0].success;
}
async revertAll(resources?: URI[], options?: IRevertOptions): Promise<ITextFileOperationResult> {
// Revert files first
const revertOperationResult = await this.doRevertAllFiles(resources, options);
// Revert untitled
const untitledReverted = this.untitledEditorService.revertAll(resources);
untitledReverted.forEach(untitled => revertOperationResult.results.push({ source: untitled, success: true }));
return revertOperationResult;
}
private async doRevertAllFiles(resources?: URI[], options?: IRevertOptions): Promise<ITextFileOperationResult> {
const fileModels = options && options.force ? this.getFileModels(resources) : this.getDirtyFileModels(resources);
const mapResourceToResult = new ResourceMap<IResult>();
fileModels.forEach(m => {
mapResourceToResult.set(m.getResource(), {
source: m.getResource()
});
});
await Promise.all(fileModels.map(async model => {
try {
await model.revert(options && options.soft);
if (!model.isDirty()) {
const result = mapResourceToResult.get(model.getResource());
if (result) {
result.success = true;
}
}
} catch (error) {
// FileNotFound means the file got deleted meanwhile, so still record as successful revert
if ((<FileOperationError>error).fileOperationResult === FileOperationResult.FILE_NOT_FOUND) {
const result = mapResourceToResult.get(model.getResource());
if (result) {
result.success = true;
}
}
// Otherwise bubble up the error
else {
throw error;
}
}
}));
return { results: mapResourceToResult.values() };
}
getDirty(resources?: URI[]): URI[] {
// Collect files
const dirty = this.getDirtyFileModels(resources).map(m => m.getResource());
// Add untitled ones
dirty.push(...this.untitledEditorService.getDirty(resources));
return dirty;
}
isDirty(resource?: URI): boolean {
// Check for dirty file
if (this._models.getAll(resource).some(model => model.isDirty())) {
return true;
}
// Check for dirty untitled
return this.untitledEditorService.getDirty().some(dirty => !resource || dirty.toString() === resource.toString());
}
//#endregion
//#region config
getAutoSaveMode(): AutoSaveMode {
if (this.configuredAutoSaveOnFocusChange) {
return AutoSaveMode.ON_FOCUS_CHANGE;
}
if (this.configuredAutoSaveOnWindowChange) {
return AutoSaveMode.ON_WINDOW_CHANGE;
}
if (this.configuredAutoSaveDelay && this.configuredAutoSaveDelay > 0) {
return this.configuredAutoSaveDelay <= 1000 ? AutoSaveMode.AFTER_SHORT_DELAY : AutoSaveMode.AFTER_LONG_DELAY;
}
return AutoSaveMode.OFF;
}
getAutoSaveConfiguration(): IAutoSaveConfiguration {
return {
autoSaveDelay: this.configuredAutoSaveDelay && this.configuredAutoSaveDelay > 0 ? this.configuredAutoSaveDelay : undefined,
autoSaveFocusChange: this.configuredAutoSaveOnFocusChange,
autoSaveApplicationChange: this.configuredAutoSaveOnWindowChange
};
}
get isHotExitEnabled(): boolean {
return !this.environmentService.isExtensionDevelopment && this.configuredHotExit !== HotExitConfiguration.OFF;
}
//#endregion
dispose(): void {
// Clear all caches
this._models.clear();
super.dispose();
}
} | src/vs/workbench/services/textfile/common/textFileService.ts | 1 | https://github.com/microsoft/vscode/commit/985de26b3446636f86e2bb2b14dbeb9ec1e33207 | [
0.002125628525391221,
0.00020216709526721388,
0.00016149405564647168,
0.0001722204324323684,
0.000198967129108496
] |
{
"id": 14,
"code_window": [
"\toverwriteReadonly?: boolean;\n",
"\toverwriteEncoding?: boolean;\n",
"\tskipSaveParticipants?: boolean;\n",
"\twriteElevated?: boolean;\n",
"}\n",
"\n",
"export interface ILoadOptions {\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tavailableFileSystems?: string[];\n"
],
"file_path": "src/vs/workbench/services/textfile/common/textfiles.ts",
"type": "add",
"edit_start_line_idx": 430
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { IExtensionsWorkbenchService } from 'vs/workbench/contrib/extensions/common/extensions';
import { IWorkbenchContribution } from 'vs/workbench/common/contributions';
import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions';
import { CommandsRegistry } from 'vs/platform/commands/common/commands';
import { MenuRegistry, MenuId } from 'vs/platform/actions/common/actions';
import { localize } from 'vs/nls';
import { values } from 'vs/base/common/map';
import { areSameExtensions } from 'vs/platform/extensionManagement/common/extensionManagementUtil';
import { INotificationService, Severity } from 'vs/platform/notification/common/notification';
import { Action } from 'vs/base/common/actions';
import { IWindowService } from 'vs/platform/windows/common/windows';
import { Disposable } from 'vs/base/common/lifecycle';
import { CancellationToken } from 'vs/base/common/cancellation';
export class ExtensionDependencyChecker extends Disposable implements IWorkbenchContribution {
constructor(
@IExtensionService private readonly extensionService: IExtensionService,
@IExtensionsWorkbenchService private readonly extensionsWorkbenchService: IExtensionsWorkbenchService,
@INotificationService private readonly notificationService: INotificationService,
@IWindowService private readonly windowService: IWindowService
) {
super();
CommandsRegistry.registerCommand('workbench.extensions.installMissingDepenencies', () => this.installMissingDependencies());
MenuRegistry.appendMenuItem(MenuId.CommandPalette, {
command: {
id: 'workbench.extensions.installMissingDepenencies',
category: localize('extensions', "Extensions"),
title: localize('auto install missing deps', "Install Missing Dependencies")
}
});
}
private async getUninstalledMissingDependencies(): Promise<string[]> {
const allMissingDependencies = await this.getAllMissingDependencies();
const localExtensions = await this.extensionsWorkbenchService.queryLocal();
return allMissingDependencies.filter(id => localExtensions.every(l => !areSameExtensions(l.identifier, { id })));
}
private async getAllMissingDependencies(): Promise<string[]> {
const runningExtensions = await this.extensionService.getExtensions();
const runningExtensionsIds: Set<string> = runningExtensions.reduce((result, r) => { result.add(r.identifier.value.toLowerCase()); return result; }, new Set<string>());
const missingDependencies: Set<string> = new Set<string>();
for (const extension of runningExtensions) {
if (extension.extensionDependencies) {
extension.extensionDependencies.forEach(dep => {
if (!runningExtensionsIds.has(dep.toLowerCase())) {
missingDependencies.add(dep);
}
});
}
}
return values(missingDependencies);
}
private async installMissingDependencies(): Promise<void> {
const missingDependencies = await this.getUninstalledMissingDependencies();
if (missingDependencies.length) {
const extensions = (await this.extensionsWorkbenchService.queryGallery({ names: missingDependencies, pageSize: missingDependencies.length }, CancellationToken.None)).firstPage;
if (extensions.length) {
await Promise.all(extensions.map(extension => this.extensionsWorkbenchService.install(extension)));
this.notificationService.notify({
severity: Severity.Info,
message: localize('finished installing missing deps', "Finished installing missing dependencies. Please reload the window now."),
actions: {
primary: [new Action('realod', localize('reload', "Realod Window"), '', true,
() => this.windowService.reloadWindow())]
}
});
}
} else {
this.notificationService.info(localize('no missing deps', "There are no missing dependencies to install."));
}
}
} | src/vs/workbench/contrib/extensions/electron-browser/extensionsDependencyChecker.ts | 0 | https://github.com/microsoft/vscode/commit/985de26b3446636f86e2bb2b14dbeb9ec1e33207 | [
0.00017839405336417258,
0.00017323716019745916,
0.000166576515766792,
0.00017337674216832966,
0.000003003137180712656
] |
{
"id": 14,
"code_window": [
"\toverwriteReadonly?: boolean;\n",
"\toverwriteEncoding?: boolean;\n",
"\tskipSaveParticipants?: boolean;\n",
"\twriteElevated?: boolean;\n",
"}\n",
"\n",
"export interface ILoadOptions {\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tavailableFileSystems?: string[];\n"
],
"file_path": "src/vs/workbench/services/textfile/common/textfiles.ts",
"type": "add",
"edit_start_line_idx": 430
} | <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><style>.icon-canvas-transparent{opacity:0;fill:#2d2d30}.icon-vs-out{fill:#2d2d30}.icon-vs-fg{fill:#2b282e}.icon-vs-action-blue{fill:#75beff}</style><path class="icon-canvas-transparent" d="M16 16H0V0h16v16z" id="canvas"/><path class="icon-vs-out" d="M0 15V6h6V2.586L7.585 1h6.829L16 2.586v5.829L14.414 10H10v5H0zm3-6z" id="outline"/><path class="icon-vs-fg" d="M8 3v3h5v1h-3v1h4V3H8zm5 2H9V4h4v1zM2 8v5h6V8H2zm5 3H3v-1h4v1z" id="iconFg"/><path class="icon-vs-action-blue" d="M10 6h3v1h-3V6zM9 4v1h4V4H9zm5-2H8L7 3v3h1V3h6v5h-4v1h4l1-1V3l-1-1zm-7 8H3v1h4v-1zm2-3v7H1V7h8zM8 8H2v5h6V8z" id="iconBg"/></svg> | src/vs/editor/contrib/documentSymbols/media/EnumItem_inverse_16x.svg | 0 | https://github.com/microsoft/vscode/commit/985de26b3446636f86e2bb2b14dbeb9ec1e33207 | [
0.00016657460946589708,
0.00016657460946589708,
0.00016657460946589708,
0.00016657460946589708,
0
] |
{
"id": 14,
"code_window": [
"\toverwriteReadonly?: boolean;\n",
"\toverwriteEncoding?: boolean;\n",
"\tskipSaveParticipants?: boolean;\n",
"\twriteElevated?: boolean;\n",
"}\n",
"\n",
"export interface ILoadOptions {\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tavailableFileSystems?: string[];\n"
],
"file_path": "src/vs/workbench/services/textfile/common/textfiles.ts",
"type": "add",
"edit_start_line_idx": 430
} | steps:
- script: |
set -e
sudo apt-get update
sudo apt-get install -y libxkbfile-dev pkg-config libsecret-1-dev libxss1 dbus xvfb libgtk-3-0
sudo cp build/azure-pipelines/linux/xvfb.init /etc/init.d/xvfb
sudo chmod +x /etc/init.d/xvfb
sudo update-rc.d xvfb defaults
sudo service xvfb start
- task: NodeTool@0
inputs:
versionSpec: "10.15.1"
- task: 1ESLighthouseEng.PipelineArtifactCaching.RestoreCacheV1.RestoreCache@1
inputs:
keyfile: '**/yarn.lock, !**/node_modules/**/yarn.lock, !**/.*/**/yarn.lock'
targetfolder: '**/node_modules, !**/node_modules/**/node_modules'
vstsFeed: '$(ArtifactFeed)'
- task: geeklearningio.gl-vsts-tasks-yarn.yarn-installer-task.YarnInstaller@2
inputs:
versionSpec: "1.10.1"
- script: |
yarn
displayName: Install Dependencies
condition: ne(variables['CacheRestored'], 'true')
- task: 1ESLighthouseEng.PipelineArtifactCaching.SaveCacheV1.SaveCache@1
inputs:
keyfile: '**/yarn.lock, !**/node_modules/**/yarn.lock, !**/.*/**/yarn.lock'
targetfolder: '**/node_modules, !**/node_modules/**/node_modules'
vstsFeed: '$(ArtifactFeed)'
condition: and(succeeded(), ne(variables['CacheRestored'], 'true'))
- script: |
yarn gulp electron-x64
displayName: Download Electron
- script: |
yarn gulp hygiene
displayName: Run Hygiene Checks
- script: |
yarn monaco-compile-check
displayName: Run Monaco Editor Checks
- script: |
yarn compile
displayName: Compile Sources
- script: |
yarn download-builtin-extensions
displayName: Download Built-in Extensions
- script: |
DISPLAY=:10 ./scripts/test.sh --tfs "Unit Tests"
displayName: Run Unit Tests
- task: PublishTestResults@2
displayName: Publish Tests Results
inputs:
testResultsFiles: '*-results.xml'
searchFolder: '$(Build.ArtifactStagingDirectory)/test-results'
condition: succeededOrFailed() | build/azure-pipelines/linux/continuous-build-linux.yml | 0 | https://github.com/microsoft/vscode/commit/985de26b3446636f86e2bb2b14dbeb9ec1e33207 | [
0.00017660867888480425,
0.00017450131417717785,
0.00016832933761179447,
0.00017525619477964938,
0.000002831125812008395
] |
{
"id": 0,
"code_window": [
" expressions: false,\n",
" newEdit: false,\n",
" meta: false,\n",
" };\n",
" licenseInfo: LicenseInfo = {} as LicenseInfo;\n",
"\n",
" constructor(options: GrafanaBootConfig) {\n",
" this.theme = options.bootData.user.lightTheme ? getTheme(GrafanaThemeType.Light) : getTheme(GrafanaThemeType.Dark);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" phantomJSRenderer = false;\n"
],
"file_path": "packages/grafana-runtime/src/config.ts",
"type": "add",
"edit_start_line_idx": 69
} | // Libraries
import _ from 'lodash';
import $ from 'jquery';
// @ts-ignore
import Drop from 'tether-drop';
// Utils and servies
import { colors } from '@grafana/ui';
import { setBackendSrv, setDataSourceSrv } from '@grafana/runtime';
import config from 'app/core/config';
import coreModule from 'app/core/core_module';
import { profiler } from 'app/core/profiler';
import appEvents from 'app/core/app_events';
import { TimeSrv, setTimeSrv } from 'app/features/dashboard/services/TimeSrv';
import { DatasourceSrv } from 'app/features/plugins/datasource_srv';
import { KeybindingSrv, setKeybindingSrv } from 'app/core/services/keybindingSrv';
import { AngularLoader, setAngularLoader } from 'app/core/services/AngularLoader';
import { configureStore } from 'app/store/configureStore';
import { LocationUpdate, setLocationSrv } from '@grafana/runtime';
import { updateLocation } from 'app/core/actions';
// Types
import { KioskUrlValue, CoreEvents, AppEventEmitter, AppEventConsumer } from 'app/types';
import { setLinkSrv, LinkSrv } from 'app/features/panel/panellinks/link_srv';
import { UtilSrv } from 'app/core/services/util_srv';
import { ContextSrv } from 'app/core/services/context_srv';
import { BridgeSrv } from 'app/core/services/bridge_srv';
import { PlaylistSrv } from 'app/features/playlist/playlist_srv';
import { DashboardSrv, setDashboardSrv } from 'app/features/dashboard/services/DashboardSrv';
import { ILocationService, ITimeoutService, IRootScopeService, IAngularEvent } from 'angular';
import { AppEvent, AppEvents } from '@grafana/data';
import { backendSrv } from 'app/core/services/backend_srv';
export type GrafanaRootScope = IRootScopeService & AppEventEmitter & AppEventConsumer & { colors: string[] };
export class GrafanaCtrl {
/** @ngInject */
constructor(
$scope: any,
utilSrv: UtilSrv,
$rootScope: GrafanaRootScope,
contextSrv: ContextSrv,
bridgeSrv: BridgeSrv,
timeSrv: TimeSrv,
linkSrv: LinkSrv,
datasourceSrv: DatasourceSrv,
keybindingSrv: KeybindingSrv,
dashboardSrv: DashboardSrv,
angularLoader: AngularLoader
) {
// make angular loader service available to react components
setAngularLoader(angularLoader);
setBackendSrv(backendSrv);
setDataSourceSrv(datasourceSrv);
setTimeSrv(timeSrv);
setLinkSrv(linkSrv);
setKeybindingSrv(keybindingSrv);
setDashboardSrv(dashboardSrv);
const store = configureStore();
setLocationSrv({
update: (opt: LocationUpdate) => {
store.dispatch(updateLocation(opt));
},
});
$scope.init = () => {
$scope.contextSrv = contextSrv;
$scope.appSubUrl = config.appSubUrl;
$scope._ = _;
profiler.init(config, $rootScope);
utilSrv.init();
bridgeSrv.init();
};
$rootScope.colors = colors;
$rootScope.onAppEvent = function<T>(
event: AppEvent<T> | string,
callback: (event: IAngularEvent, ...args: any[]) => void,
localScope?: any
) {
let unbind;
if (typeof event === 'string') {
unbind = $rootScope.$on(event, callback);
} else {
unbind = $rootScope.$on(event.name, callback);
}
let callerScope = this;
if (callerScope.$id === 1 && !localScope) {
console.log('warning rootScope onAppEvent called without localscope');
}
if (localScope) {
callerScope = localScope;
}
callerScope.$on('$destroy', unbind);
};
$rootScope.appEvent = <T>(event: AppEvent<T> | string, payload?: T | any) => {
if (typeof event === 'string') {
$rootScope.$emit(event, payload);
appEvents.emit(event, payload);
} else {
$rootScope.$emit(event.name, payload);
appEvents.emit(event, payload);
}
};
$scope.init();
}
}
function setViewModeBodyClass(body: JQuery, mode: KioskUrlValue) {
body.removeClass('view-mode--tv');
body.removeClass('view-mode--kiosk');
body.removeClass('view-mode--inactive');
switch (mode) {
case 'tv': {
body.addClass('view-mode--tv');
break;
}
// 1 & true for legacy states
case '1':
case true: {
body.addClass('view-mode--kiosk');
break;
}
}
}
/** @ngInject */
export function grafanaAppDirective(
playlistSrv: PlaylistSrv,
contextSrv: ContextSrv,
$timeout: ITimeoutService,
$rootScope: IRootScopeService,
$location: ILocationService
) {
return {
restrict: 'E',
controller: GrafanaCtrl,
link: (scope: IRootScopeService & AppEventEmitter, elem: JQuery) => {
const body = $('body');
// see https://github.com/zenorocha/clipboard.js/issues/155
$.fn.modal.Constructor.prototype.enforceFocus = () => {};
$('.preloader').remove();
appEvents.on(CoreEvents.toggleSidemenuMobile, () => {
body.toggleClass('sidemenu-open--xs');
});
appEvents.on(CoreEvents.toggleSidemenuHidden, () => {
body.toggleClass('sidemenu-hidden');
});
appEvents.on(CoreEvents.playlistStarted, () => {
elem.toggleClass('view-mode--playlist', true);
});
appEvents.on(CoreEvents.playlistStopped, () => {
elem.toggleClass('view-mode--playlist', false);
});
// check if we are in server side render
if (document.cookie.indexOf('renderKey') !== -1) {
body.addClass('body--phantomjs');
}
// tooltip removal fix
// manage page classes
let pageClass: string;
scope.$on('$routeChangeSuccess', (evt: any, data: any) => {
if (pageClass) {
body.removeClass(pageClass);
}
if (data.$$route) {
pageClass = data.$$route.pageClass;
if (pageClass) {
body.addClass(pageClass);
}
}
// clear body class sidemenu states
body.removeClass('sidemenu-open--xs');
$('#tooltip, .tooltip').remove();
// check for kiosk url param
setViewModeBodyClass(body, data.params.kiosk);
// close all drops
for (const drop of Drop.drops) {
drop.destroy();
}
appEvents.emit(CoreEvents.hideDashSearch);
});
// handle kiosk mode
appEvents.on(CoreEvents.toggleKioskMode, (options: { exit?: boolean }) => {
const search: { kiosk?: KioskUrlValue } = $location.search();
if (options && options.exit) {
search.kiosk = '1';
}
switch (search.kiosk) {
case 'tv': {
search.kiosk = true;
appEvents.emit(AppEvents.alertSuccess, ['Press ESC to exit Kiosk mode']);
break;
}
case '1':
case true: {
delete search.kiosk;
break;
}
default: {
search.kiosk = 'tv';
}
}
$timeout(() => $location.search(search));
setViewModeBodyClass(body, search.kiosk!);
});
// handle in active view state class
let lastActivity = new Date().getTime();
let activeUser = true;
const inActiveTimeLimit = 60 * 5000;
function checkForInActiveUser() {
if (!activeUser) {
return;
}
// only go to activity low mode on dashboard page
if (!body.hasClass('page-dashboard')) {
return;
}
if (new Date().getTime() - lastActivity > inActiveTimeLimit) {
activeUser = false;
body.addClass('view-mode--inactive');
}
}
function userActivityDetected() {
lastActivity = new Date().getTime();
if (!activeUser) {
activeUser = true;
body.removeClass('view-mode--inactive');
}
}
// mouse and keyboard is user activity
body.mousemove(userActivityDetected);
body.keydown(userActivityDetected);
// set useCapture = true to catch event here
document.addEventListener('wheel', userActivityDetected, { capture: true, passive: true });
// treat tab change as activity
document.addEventListener('visibilitychange', userActivityDetected);
// check every 2 seconds
setInterval(checkForInActiveUser, 2000);
appEvents.on(CoreEvents.toggleViewMode, () => {
lastActivity = 0;
checkForInActiveUser();
});
// handle document clicks that should hide things
body.click(evt => {
const target = $(evt.target);
if (target.parents().length === 0) {
return;
}
// ensure dropdown menu doesn't impact on z-index
body.find('.dropdown-menu-open').removeClass('dropdown-menu-open');
// for stuff that animates, slides out etc, clicking it needs to
// hide it right away
const clickAutoHide = target.closest('[data-click-hide]');
if (clickAutoHide.length) {
const clickAutoHideParent = clickAutoHide.parent();
clickAutoHide.detach();
setTimeout(() => {
clickAutoHideParent.append(clickAutoHide);
}, 100);
}
// hide search
if (body.find('.search-container').length > 0) {
if (target.parents('.search-results-container, .search-field-wrapper').length === 0) {
scope.$apply(() => {
scope.appEvent(CoreEvents.hideDashSearch);
});
}
}
// hide popovers
const popover = elem.find('.popover');
if (popover.length > 0 && target.parents('.graph-legend').length === 0) {
popover.hide();
}
});
},
};
}
coreModule.directive('grafanaApp', grafanaAppDirective);
| public/app/routes/GrafanaCtrl.ts | 1 | https://github.com/grafana/grafana/commit/6e80315531a0184b60021af3557a2b155a43b036 | [
0.9317649602890015,
0.029424607753753662,
0.00016643060371279716,
0.00017423430108465254,
0.16206666827201843
] |
{
"id": 0,
"code_window": [
" expressions: false,\n",
" newEdit: false,\n",
" meta: false,\n",
" };\n",
" licenseInfo: LicenseInfo = {} as LicenseInfo;\n",
"\n",
" constructor(options: GrafanaBootConfig) {\n",
" this.theme = options.bootData.user.lightTheme ? getTheme(GrafanaThemeType.Light) : getTheme(GrafanaThemeType.Dark);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" phantomJSRenderer = false;\n"
],
"file_path": "packages/grafana-runtime/src/config.ts",
"type": "add",
"edit_start_line_idx": 69
} | // Libraries
import _ from 'lodash';
// Utils
import { toUrlParams } from 'app/core/utils/url';
import coreModule from '../../core/core_module';
import appEvents from 'app/core/app_events';
import locationUtil from 'app/core/utils/location_util';
import kbn from 'app/core/utils/kbn';
import { store } from 'app/store/store';
import { CoreEvents } from 'app/types';
import { getBackendSrv } from '@grafana/runtime';
export const queryParamsToPreserve: { [key: string]: boolean } = {
kiosk: true,
autofitpanels: true,
orgId: true,
};
export class PlaylistSrv {
private cancelPromise: any;
private dashboards: Array<{ url: string }>;
private index: number;
private interval: number;
private startUrl: string;
private numberOfLoops = 0;
private storeUnsub: () => void;
private validPlaylistUrl: string;
isPlaying: boolean;
/** @ngInject */
constructor(private $location: any, private $timeout: any) {}
next() {
this.$timeout.cancel(this.cancelPromise);
const playedAllDashboards = this.index > this.dashboards.length - 1;
if (playedAllDashboards) {
this.numberOfLoops++;
// This does full reload of the playlist to keep memory in check due to existing leaks but at the same time
// we do not want page to flicker after each full loop.
if (this.numberOfLoops >= 3) {
window.location.href = this.startUrl;
return;
}
this.index = 0;
}
const dash = this.dashboards[this.index];
const queryParams = this.$location.search();
const filteredParams = _.pickBy(queryParams, (value: any, key: string) => queryParamsToPreserve[key]);
const nextDashboardUrl = locationUtil.stripBaseFromUrl(dash.url);
// this is done inside timeout to make sure digest happens after
// as this can be called from react
this.$timeout(() => {
this.$location.url(nextDashboardUrl + '?' + toUrlParams(filteredParams));
});
this.index++;
this.validPlaylistUrl = nextDashboardUrl;
this.cancelPromise = this.$timeout(() => this.next(), this.interval);
}
prev() {
this.index = Math.max(this.index - 2, 0);
this.next();
}
// Detect url changes not caused by playlist srv and stop playlist
storeUpdated() {
const state = store.getState();
if (state.location.path !== this.validPlaylistUrl) {
this.stop();
}
}
start(playlistId: number) {
this.stop();
this.startUrl = window.location.href;
this.index = 0;
this.isPlaying = true;
// setup location tracking
this.storeUnsub = store.subscribe(() => this.storeUpdated());
this.validPlaylistUrl = this.$location.path();
appEvents.emit(CoreEvents.playlistStarted);
return getBackendSrv()
.get(`/api/playlists/${playlistId}`)
.then((playlist: any) => {
return getBackendSrv()
.get(`/api/playlists/${playlistId}/dashboards`)
.then((dashboards: any) => {
this.dashboards = dashboards;
this.interval = kbn.interval_to_ms(playlist.interval);
this.next();
});
});
}
stop() {
if (this.isPlaying) {
const queryParams = this.$location.search();
if (queryParams.kiosk) {
appEvents.emit(CoreEvents.toggleKioskMode, { exit: true });
}
}
this.index = 0;
this.isPlaying = false;
if (this.storeUnsub) {
this.storeUnsub();
}
if (this.cancelPromise) {
this.$timeout.cancel(this.cancelPromise);
}
appEvents.emit(CoreEvents.playlistStopped);
}
}
coreModule.service('playlistSrv', PlaylistSrv);
| public/app/features/playlist/playlist_srv.ts | 0 | https://github.com/grafana/grafana/commit/6e80315531a0184b60021af3557a2b155a43b036 | [
0.001337860943749547,
0.0002622534811962396,
0.0001680536661297083,
0.0001733218814479187,
0.0003105095529463142
] |
{
"id": 0,
"code_window": [
" expressions: false,\n",
" newEdit: false,\n",
" meta: false,\n",
" };\n",
" licenseInfo: LicenseInfo = {} as LicenseInfo;\n",
"\n",
" constructor(options: GrafanaBootConfig) {\n",
" this.theme = options.bootData.user.lightTheme ? getTheme(GrafanaThemeType.Light) : getTheme(GrafanaThemeType.Dark);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" phantomJSRenderer = false;\n"
],
"file_path": "packages/grafana-runtime/src/config.ts",
"type": "add",
"edit_start_line_idx": 69
} | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Code generated by the FlatBuffers compiler. DO NOT EDIT.
package flatbuf
import (
flatbuffers "github.com/google/flatbuffers/go"
)
type SparseTensor struct {
_tab flatbuffers.Table
}
func GetRootAsSparseTensor(buf []byte, offset flatbuffers.UOffsetT) *SparseTensor {
n := flatbuffers.GetUOffsetT(buf[offset:])
x := &SparseTensor{}
x.Init(buf, n+offset)
return x
}
func (rcv *SparseTensor) Init(buf []byte, i flatbuffers.UOffsetT) {
rcv._tab.Bytes = buf
rcv._tab.Pos = i
}
func (rcv *SparseTensor) Table() flatbuffers.Table {
return rcv._tab
}
func (rcv *SparseTensor) TypeType() byte {
o := flatbuffers.UOffsetT(rcv._tab.Offset(4))
if o != 0 {
return rcv._tab.GetByte(o + rcv._tab.Pos)
}
return 0
}
func (rcv *SparseTensor) MutateTypeType(n byte) bool {
return rcv._tab.MutateByteSlot(4, n)
}
/// The type of data contained in a value cell.
/// Currently only fixed-width value types are supported,
/// no strings or nested types.
func (rcv *SparseTensor) Type(obj *flatbuffers.Table) bool {
o := flatbuffers.UOffsetT(rcv._tab.Offset(6))
if o != 0 {
rcv._tab.Union(obj, o)
return true
}
return false
}
/// The type of data contained in a value cell.
/// Currently only fixed-width value types are supported,
/// no strings or nested types.
/// The dimensions of the tensor, optionally named.
func (rcv *SparseTensor) Shape(obj *TensorDim, j int) bool {
o := flatbuffers.UOffsetT(rcv._tab.Offset(8))
if o != 0 {
x := rcv._tab.Vector(o)
x += flatbuffers.UOffsetT(j) * 4
x = rcv._tab.Indirect(x)
obj.Init(rcv._tab.Bytes, x)
return true
}
return false
}
func (rcv *SparseTensor) ShapeLength() int {
o := flatbuffers.UOffsetT(rcv._tab.Offset(8))
if o != 0 {
return rcv._tab.VectorLen(o)
}
return 0
}
/// The dimensions of the tensor, optionally named.
/// The number of non-zero values in a sparse tensor.
func (rcv *SparseTensor) NonZeroLength() int64 {
o := flatbuffers.UOffsetT(rcv._tab.Offset(10))
if o != 0 {
return rcv._tab.GetInt64(o + rcv._tab.Pos)
}
return 0
}
/// The number of non-zero values in a sparse tensor.
func (rcv *SparseTensor) MutateNonZeroLength(n int64) bool {
return rcv._tab.MutateInt64Slot(10, n)
}
func (rcv *SparseTensor) SparseIndexType() byte {
o := flatbuffers.UOffsetT(rcv._tab.Offset(12))
if o != 0 {
return rcv._tab.GetByte(o + rcv._tab.Pos)
}
return 0
}
func (rcv *SparseTensor) MutateSparseIndexType(n byte) bool {
return rcv._tab.MutateByteSlot(12, n)
}
/// Sparse tensor index
func (rcv *SparseTensor) SparseIndex(obj *flatbuffers.Table) bool {
o := flatbuffers.UOffsetT(rcv._tab.Offset(14))
if o != 0 {
rcv._tab.Union(obj, o)
return true
}
return false
}
/// Sparse tensor index
/// The location and size of the tensor's data
func (rcv *SparseTensor) Data(obj *Buffer) *Buffer {
o := flatbuffers.UOffsetT(rcv._tab.Offset(16))
if o != 0 {
x := o + rcv._tab.Pos
if obj == nil {
obj = new(Buffer)
}
obj.Init(rcv._tab.Bytes, x)
return obj
}
return nil
}
/// The location and size of the tensor's data
func SparseTensorStart(builder *flatbuffers.Builder) {
builder.StartObject(7)
}
func SparseTensorAddTypeType(builder *flatbuffers.Builder, typeType byte) {
builder.PrependByteSlot(0, typeType, 0)
}
func SparseTensorAddType(builder *flatbuffers.Builder, type_ flatbuffers.UOffsetT) {
builder.PrependUOffsetTSlot(1, flatbuffers.UOffsetT(type_), 0)
}
func SparseTensorAddShape(builder *flatbuffers.Builder, shape flatbuffers.UOffsetT) {
builder.PrependUOffsetTSlot(2, flatbuffers.UOffsetT(shape), 0)
}
func SparseTensorStartShapeVector(builder *flatbuffers.Builder, numElems int) flatbuffers.UOffsetT {
return builder.StartVector(4, numElems, 4)
}
func SparseTensorAddNonZeroLength(builder *flatbuffers.Builder, nonZeroLength int64) {
builder.PrependInt64Slot(3, nonZeroLength, 0)
}
func SparseTensorAddSparseIndexType(builder *flatbuffers.Builder, sparseIndexType byte) {
builder.PrependByteSlot(4, sparseIndexType, 0)
}
func SparseTensorAddSparseIndex(builder *flatbuffers.Builder, sparseIndex flatbuffers.UOffsetT) {
builder.PrependUOffsetTSlot(5, flatbuffers.UOffsetT(sparseIndex), 0)
}
func SparseTensorAddData(builder *flatbuffers.Builder, data flatbuffers.UOffsetT) {
builder.PrependStructSlot(6, flatbuffers.UOffsetT(data), 0)
}
func SparseTensorEnd(builder *flatbuffers.Builder) flatbuffers.UOffsetT {
return builder.EndObject()
}
| vendor/github.com/apache/arrow/go/arrow/internal/flatbuf/SparseTensor.go | 0 | https://github.com/grafana/grafana/commit/6e80315531a0184b60021af3557a2b155a43b036 | [
0.0031911449041217566,
0.000344515050528571,
0.00016673766367603093,
0.000172442349139601,
0.0006906497874297202
] |
{
"id": 0,
"code_window": [
" expressions: false,\n",
" newEdit: false,\n",
" meta: false,\n",
" };\n",
" licenseInfo: LicenseInfo = {} as LicenseInfo;\n",
"\n",
" constructor(options: GrafanaBootConfig) {\n",
" this.theme = options.bootData.user.lightTheme ? getTheme(GrafanaThemeType.Light) : getTheme(GrafanaThemeType.Dark);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" phantomJSRenderer = false;\n"
],
"file_path": "packages/grafana-runtime/src/config.ts",
"type": "add",
"edit_start_line_idx": 69
} | import _ from 'lodash';
import appEvents from 'app/core/app_events';
import { MysqlMetaQuery } from './meta_query';
import { QueryCtrl } from 'app/plugins/sdk';
import { SqlPart } from 'app/core/components/sql_part/sql_part';
import MysqlQuery from './mysql_query';
import sqlPart from './sql_part';
import { auto } from 'angular';
import { TemplateSrv } from 'app/features/templating/template_srv';
import { CoreEvents } from 'app/types';
import { PanelEvents } from '@grafana/data';
export interface QueryMeta {
sql: string;
}
const defaultQuery = `SELECT
UNIX_TIMESTAMP(<time_column>) as time_sec,
<value column> as value,
<series name column> as metric
FROM <table name>
WHERE $__timeFilter(time_column)
ORDER BY <time_column> ASC
`;
export class MysqlQueryCtrl extends QueryCtrl {
static templateUrl = 'partials/query.editor.html';
showLastQuerySQL: boolean;
formats: any[];
lastQueryMeta: QueryMeta;
lastQueryError: string;
showHelp: boolean;
queryModel: MysqlQuery;
metaBuilder: MysqlMetaQuery;
tableSegment: any;
whereAdd: any;
timeColumnSegment: any;
metricColumnSegment: any;
selectMenu: any[];
selectParts: SqlPart[][];
groupParts: SqlPart[];
whereParts: SqlPart[];
groupAdd: any;
/** @ngInject */
constructor(
$scope: any,
$injector: auto.IInjectorService,
private templateSrv: TemplateSrv,
private uiSegmentSrv: any
) {
super($scope, $injector);
this.target = this.target;
this.queryModel = new MysqlQuery(this.target, templateSrv, this.panel.scopedVars);
this.metaBuilder = new MysqlMetaQuery(this.target, this.queryModel);
this.updateProjection();
this.formats = [
{ text: 'Time series', value: 'time_series' },
{ text: 'Table', value: 'table' },
];
if (!this.target.rawSql) {
// special handling when in table panel
if (this.panelCtrl.panel.type === 'table') {
this.target.format = 'table';
this.target.rawSql = 'SELECT 1';
this.target.rawQuery = true;
} else {
this.target.rawSql = defaultQuery;
this.datasource.metricFindQuery(this.metaBuilder.findMetricTable()).then((result: any) => {
if (result.length > 0) {
this.target.table = result[0].text;
let segment = this.uiSegmentSrv.newSegment(this.target.table);
this.tableSegment.html = segment.html;
this.tableSegment.value = segment.value;
this.target.timeColumn = result[1].text;
segment = this.uiSegmentSrv.newSegment(this.target.timeColumn);
this.timeColumnSegment.html = segment.html;
this.timeColumnSegment.value = segment.value;
this.target.timeColumnType = 'timestamp';
this.target.select = [[{ type: 'column', params: [result[2].text] }]];
this.updateProjection();
this.updateRawSqlAndRefresh();
}
});
}
}
if (!this.target.table) {
this.tableSegment = uiSegmentSrv.newSegment({ value: 'select table', fake: true });
} else {
this.tableSegment = uiSegmentSrv.newSegment(this.target.table);
}
this.timeColumnSegment = uiSegmentSrv.newSegment(this.target.timeColumn);
this.metricColumnSegment = uiSegmentSrv.newSegment(this.target.metricColumn);
this.buildSelectMenu();
this.whereAdd = this.uiSegmentSrv.newPlusButton();
this.groupAdd = this.uiSegmentSrv.newPlusButton();
this.panelCtrl.events.on(PanelEvents.dataReceived, this.onDataReceived.bind(this), $scope);
this.panelCtrl.events.on(PanelEvents.dataError, this.onDataError.bind(this), $scope);
}
updateRawSqlAndRefresh() {
if (!this.target.rawQuery) {
this.target.rawSql = this.queryModel.buildQuery();
}
this.panelCtrl.refresh();
}
updateProjection() {
this.selectParts = _.map(this.target.select, (parts: any) => {
return _.map(parts, sqlPart.create).filter(n => n);
});
this.whereParts = _.map(this.target.where, sqlPart.create).filter(n => n);
this.groupParts = _.map(this.target.group, sqlPart.create).filter(n => n);
}
updatePersistedParts() {
this.target.select = _.map(this.selectParts, selectParts => {
return _.map(selectParts, (part: any) => {
return { type: part.def.type, datatype: part.datatype, params: part.params };
});
});
this.target.where = _.map(this.whereParts, (part: any) => {
return { type: part.def.type, datatype: part.datatype, name: part.name, params: part.params };
});
this.target.group = _.map(this.groupParts, (part: any) => {
return { type: part.def.type, datatype: part.datatype, params: part.params };
});
}
buildSelectMenu() {
this.selectMenu = [];
const aggregates = {
text: 'Aggregate Functions',
value: 'aggregate',
submenu: [
{ text: 'Average', value: 'avg' },
{ text: 'Count', value: 'count' },
{ text: 'Maximum', value: 'max' },
{ text: 'Minimum', value: 'min' },
{ text: 'Sum', value: 'sum' },
{ text: 'Standard deviation', value: 'stddev' },
{ text: 'Variance', value: 'variance' },
],
};
this.selectMenu.push(aggregates);
this.selectMenu.push({ text: 'Alias', value: 'alias' });
this.selectMenu.push({ text: 'Column', value: 'column' });
}
toggleEditorMode() {
if (this.target.rawQuery) {
appEvents.emit(CoreEvents.showConfirmModal, {
title: 'Warning',
text2: 'Switching to query builder may overwrite your raw SQL.',
icon: 'fa-exclamation',
yesText: 'Switch',
onConfirm: () => {
this.target.rawQuery = !this.target.rawQuery;
},
});
} else {
this.target.rawQuery = !this.target.rawQuery;
}
}
resetPlusButton(button: { html: any; value: any }) {
const plusButton = this.uiSegmentSrv.newPlusButton();
button.html = plusButton.html;
button.value = plusButton.value;
}
getTableSegments() {
return this.datasource
.metricFindQuery(this.metaBuilder.buildTableQuery())
.then(this.transformToSegments({}))
.catch(this.handleQueryError.bind(this));
}
tableChanged() {
this.target.table = this.tableSegment.value;
this.target.where = [];
this.target.group = [];
this.updateProjection();
const segment = this.uiSegmentSrv.newSegment('none');
this.metricColumnSegment.html = segment.html;
this.metricColumnSegment.value = segment.value;
this.target.metricColumn = 'none';
const task1 = this.datasource.metricFindQuery(this.metaBuilder.buildColumnQuery('time')).then((result: any) => {
// check if time column is still valid
if (result.length > 0 && !_.find(result, (r: any) => r.text === this.target.timeColumn)) {
const segment = this.uiSegmentSrv.newSegment(result[0].text);
this.timeColumnSegment.html = segment.html;
this.timeColumnSegment.value = segment.value;
}
return this.timeColumnChanged(false);
});
const task2 = this.datasource.metricFindQuery(this.metaBuilder.buildColumnQuery('value')).then((result: any) => {
if (result.length > 0) {
this.target.select = [[{ type: 'column', params: [result[0].text] }]];
this.updateProjection();
}
});
Promise.all([task1, task2]).then(() => {
this.updateRawSqlAndRefresh();
});
}
getTimeColumnSegments() {
return this.datasource
.metricFindQuery(this.metaBuilder.buildColumnQuery('time'))
.then(this.transformToSegments({}))
.catch(this.handleQueryError.bind(this));
}
timeColumnChanged(refresh?: boolean) {
this.target.timeColumn = this.timeColumnSegment.value;
return this.datasource
.metricFindQuery(this.metaBuilder.buildDatatypeQuery(this.target.timeColumn))
.then((result: any) => {
if (result.length === 1) {
if (this.target.timeColumnType !== result[0].text) {
this.target.timeColumnType = result[0].text;
}
let partModel;
if (this.queryModel.hasUnixEpochTimecolumn()) {
partModel = sqlPart.create({ type: 'macro', name: '$__unixEpochFilter', params: [] });
} else {
partModel = sqlPart.create({ type: 'macro', name: '$__timeFilter', params: [] });
}
if (this.whereParts.length >= 1 && this.whereParts[0].def.type === 'macro') {
// replace current macro
this.whereParts[0] = partModel;
} else {
this.whereParts.splice(0, 0, partModel);
}
}
this.updatePersistedParts();
if (refresh !== false) {
this.updateRawSqlAndRefresh();
}
});
}
getMetricColumnSegments() {
return this.datasource
.metricFindQuery(this.metaBuilder.buildColumnQuery('metric'))
.then(this.transformToSegments({ addNone: true }))
.catch(this.handleQueryError.bind(this));
}
metricColumnChanged() {
this.target.metricColumn = this.metricColumnSegment.value;
this.updateRawSqlAndRefresh();
}
onDataReceived(dataList: any) {
this.lastQueryMeta = null;
this.lastQueryError = null;
const anySeriesFromQuery: any = _.find(dataList, { refId: this.target.refId });
if (anySeriesFromQuery) {
this.lastQueryMeta = anySeriesFromQuery.meta;
}
}
onDataError(err: any) {
if (err.data && err.data.results) {
const queryRes = err.data.results[this.target.refId];
if (queryRes) {
this.lastQueryMeta = queryRes.meta;
this.lastQueryError = queryRes.error;
}
}
}
transformToSegments(config: any) {
return (results: any) => {
const segments = _.map(results, segment => {
return this.uiSegmentSrv.newSegment({
value: segment.text,
expandable: segment.expandable,
});
});
if (config.addTemplateVars) {
for (const variable of this.templateSrv.variables) {
let value;
value = '$' + variable.name;
if (config.templateQuoter && variable.multi === false) {
value = config.templateQuoter(value);
}
segments.unshift(
this.uiSegmentSrv.newSegment({
type: 'template',
value: value,
expandable: true,
})
);
}
}
if (config.addNone) {
segments.unshift(this.uiSegmentSrv.newSegment({ type: 'template', value: 'none', expandable: true }));
}
return segments;
};
}
findAggregateIndex(selectParts: any) {
return _.findIndex(selectParts, (p: any) => p.def.type === 'aggregate' || p.def.type === 'percentile');
}
findWindowIndex(selectParts: any) {
return _.findIndex(selectParts, (p: any) => p.def.type === 'window' || p.def.type === 'moving_window');
}
addSelectPart(selectParts: any[], item: { value: any }, subItem: { type: any; value: any }) {
let partType = item.value;
if (subItem && subItem.type) {
partType = subItem.type;
}
let partModel = sqlPart.create({ type: partType });
if (subItem) {
partModel.params[0] = subItem.value;
}
let addAlias = false;
switch (partType) {
case 'column':
const parts = _.map(selectParts, (part: any) => {
return sqlPart.create({ type: part.def.type, params: _.clone(part.params) });
});
this.selectParts.push(parts);
break;
case 'percentile':
case 'aggregate':
// add group by if no group by yet
if (this.target.group.length === 0) {
this.addGroup('time', '$__interval');
}
const aggIndex = this.findAggregateIndex(selectParts);
if (aggIndex !== -1) {
// replace current aggregation
selectParts[aggIndex] = partModel;
} else {
selectParts.splice(1, 0, partModel);
}
if (!_.find(selectParts, (p: any) => p.def.type === 'alias')) {
addAlias = true;
}
break;
case 'moving_window':
case 'window':
const windowIndex = this.findWindowIndex(selectParts);
if (windowIndex !== -1) {
// replace current window function
selectParts[windowIndex] = partModel;
} else {
const aggIndex = this.findAggregateIndex(selectParts);
if (aggIndex !== -1) {
selectParts.splice(aggIndex + 1, 0, partModel);
} else {
selectParts.splice(1, 0, partModel);
}
}
if (!_.find(selectParts, (p: any) => p.def.type === 'alias')) {
addAlias = true;
}
break;
case 'alias':
addAlias = true;
break;
}
if (addAlias) {
// set initial alias name to column name
partModel = sqlPart.create({ type: 'alias', params: [selectParts[0].params[0].replace(/"/g, '')] });
if (selectParts[selectParts.length - 1].def.type === 'alias') {
selectParts[selectParts.length - 1] = partModel;
} else {
selectParts.push(partModel);
}
}
this.updatePersistedParts();
this.updateRawSqlAndRefresh();
}
removeSelectPart(selectParts: any, part: { def: { type: string } }) {
if (part.def.type === 'column') {
// remove all parts of column unless its last column
if (this.selectParts.length > 1) {
const modelsIndex = _.indexOf(this.selectParts, selectParts);
this.selectParts.splice(modelsIndex, 1);
}
} else {
const partIndex = _.indexOf(selectParts, part);
selectParts.splice(partIndex, 1);
}
this.updatePersistedParts();
}
handleSelectPartEvent(selectParts: any, part: { def: any }, evt: { name: any }) {
switch (evt.name) {
case 'get-param-options': {
switch (part.def.type) {
// case 'aggregate':
// return this.datasource
// .metricFindQuery(this.metaBuilder.buildAggregateQuery())
// .then(this.transformToSegments({}))
// .catch(this.handleQueryError.bind(this));
case 'column':
return this.datasource
.metricFindQuery(this.metaBuilder.buildColumnQuery('value'))
.then(this.transformToSegments({}))
.catch(this.handleQueryError.bind(this));
}
}
case 'part-param-changed': {
this.updatePersistedParts();
this.updateRawSqlAndRefresh();
break;
}
case 'action': {
this.removeSelectPart(selectParts, part);
this.updateRawSqlAndRefresh();
break;
}
case 'get-part-actions': {
return Promise.resolve([{ text: 'Remove', value: 'remove-part' }]);
}
}
}
handleGroupPartEvent(part: any, index: any, evt: { name: any }) {
switch (evt.name) {
case 'get-param-options': {
return this.datasource
.metricFindQuery(this.metaBuilder.buildColumnQuery())
.then(this.transformToSegments({}))
.catch(this.handleQueryError.bind(this));
}
case 'part-param-changed': {
this.updatePersistedParts();
this.updateRawSqlAndRefresh();
break;
}
case 'action': {
this.removeGroup(part, index);
this.updateRawSqlAndRefresh();
break;
}
case 'get-part-actions': {
return Promise.resolve([{ text: 'Remove', value: 'remove-part' }]);
}
}
}
addGroup(partType: string, value: string) {
let params = [value];
if (partType === 'time') {
params = ['$__interval', 'none'];
}
const partModel = sqlPart.create({ type: partType, params: params });
if (partType === 'time') {
// put timeGroup at start
this.groupParts.splice(0, 0, partModel);
} else {
this.groupParts.push(partModel);
}
// add aggregates when adding group by
for (const selectParts of this.selectParts) {
if (!selectParts.some(part => part.def.type === 'aggregate')) {
const aggregate = sqlPart.create({ type: 'aggregate', params: ['avg'] });
selectParts.splice(1, 0, aggregate);
if (!selectParts.some(part => part.def.type === 'alias')) {
const alias = sqlPart.create({ type: 'alias', params: [selectParts[0].part.params[0]] });
selectParts.push(alias);
}
}
}
this.updatePersistedParts();
}
removeGroup(part: { def: { type: string } }, index: number) {
if (part.def.type === 'time') {
// remove aggregations
this.selectParts = _.map(this.selectParts, (s: any) => {
return _.filter(s, (part: any) => {
if (part.def.type === 'aggregate' || part.def.type === 'percentile') {
return false;
}
return true;
});
});
}
this.groupParts.splice(index, 1);
this.updatePersistedParts();
}
handleWherePartEvent(whereParts: any, part: any, evt: any, index: any) {
switch (evt.name) {
case 'get-param-options': {
switch (evt.param.name) {
case 'left':
return this.datasource
.metricFindQuery(this.metaBuilder.buildColumnQuery())
.then(this.transformToSegments({}))
.catch(this.handleQueryError.bind(this));
case 'right':
if (['int', 'bigint', 'double', 'datetime'].indexOf(part.datatype) > -1) {
// don't do value lookups for numerical fields
return Promise.resolve([]);
} else {
return this.datasource
.metricFindQuery(this.metaBuilder.buildValueQuery(part.params[0]))
.then(
this.transformToSegments({
addTemplateVars: true,
templateQuoter: (v: string) => {
return this.queryModel.quoteLiteral(v);
},
})
)
.catch(this.handleQueryError.bind(this));
}
case 'op':
return Promise.resolve(this.uiSegmentSrv.newOperators(this.metaBuilder.getOperators(part.datatype)));
default:
return Promise.resolve([]);
}
}
case 'part-param-changed': {
this.updatePersistedParts();
this.datasource.metricFindQuery(this.metaBuilder.buildDatatypeQuery(part.params[0])).then((d: any) => {
if (d.length === 1) {
part.datatype = d[0].text;
}
});
this.updateRawSqlAndRefresh();
break;
}
case 'action': {
// remove element
whereParts.splice(index, 1);
this.updatePersistedParts();
this.updateRawSqlAndRefresh();
break;
}
case 'get-part-actions': {
return Promise.resolve([{ text: 'Remove', value: 'remove-part' }]);
}
}
}
getWhereOptions() {
const options = [];
if (this.queryModel.hasUnixEpochTimecolumn()) {
options.push(this.uiSegmentSrv.newSegment({ type: 'macro', value: '$__unixEpochFilter' }));
} else {
options.push(this.uiSegmentSrv.newSegment({ type: 'macro', value: '$__timeFilter' }));
}
options.push(this.uiSegmentSrv.newSegment({ type: 'expression', value: 'Expression' }));
return Promise.resolve(options);
}
addWhereAction(part: any, index: number) {
switch (this.whereAdd.type) {
case 'macro': {
const partModel = sqlPart.create({ type: 'macro', name: this.whereAdd.value, params: [] });
if (this.whereParts.length >= 1 && this.whereParts[0].def.type === 'macro') {
// replace current macro
this.whereParts[0] = partModel;
} else {
this.whereParts.splice(0, 0, partModel);
}
break;
}
default: {
this.whereParts.push(sqlPart.create({ type: 'expression', params: ['value', '=', 'value'] }));
}
}
this.updatePersistedParts();
this.resetPlusButton(this.whereAdd);
this.updateRawSqlAndRefresh();
}
getGroupOptions() {
return this.datasource
.metricFindQuery(this.metaBuilder.buildColumnQuery('group'))
.then((tags: any) => {
const options = [];
if (!this.queryModel.hasTimeGroup()) {
options.push(this.uiSegmentSrv.newSegment({ type: 'time', value: 'time($__interval,none)' }));
}
for (const tag of tags) {
options.push(this.uiSegmentSrv.newSegment({ type: 'column', value: tag.text }));
}
return options;
})
.catch(this.handleQueryError.bind(this));
}
addGroupAction() {
switch (this.groupAdd.value) {
default: {
this.addGroup(this.groupAdd.type, this.groupAdd.value);
}
}
this.resetPlusButton(this.groupAdd);
this.updateRawSqlAndRefresh();
}
handleQueryError(err: any): any[] {
this.error = err.message || 'Failed to issue metric query';
return [];
}
}
| public/app/plugins/datasource/mysql/query_ctrl.ts | 0 | https://github.com/grafana/grafana/commit/6e80315531a0184b60021af3557a2b155a43b036 | [
0.004539847373962402,
0.0002725798112805933,
0.00016682369459886104,
0.00017278181621804833,
0.000590651121456176
] |
{
"id": 1,
"code_window": [
"import (\n",
"\t\"strconv\"\n",
"\n",
"\t\"github.com/grafana/grafana/pkg/components/simplejson\"\n",
"\t\"github.com/grafana/grafana/pkg/util\"\n",
"\n",
"\t\"github.com/grafana/grafana/pkg/bus\"\n",
"\t\"github.com/grafana/grafana/pkg/infra/log\"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\"github.com/grafana/grafana/pkg/services/rendering\"\n",
"\n"
],
"file_path": "pkg/api/frontendsettings.go",
"type": "add",
"edit_start_line_idx": 5
} | import extend from 'lodash/extend';
import { getTheme } from '@grafana/ui';
import { GrafanaTheme, GrafanaThemeType, PanelPluginMeta, DataSourceInstanceSettings } from '@grafana/data';
export interface BuildInfo {
version: string;
commit: string;
isEnterprise: boolean; // deprecated: use licenseInfo.hasLicense instead
env: string;
edition: string;
latestVersion: string;
hasUpdate: boolean;
}
interface FeatureToggles {
transformations: boolean;
inspect: boolean;
expressions: boolean;
newEdit: boolean;
meta: boolean;
}
interface LicenseInfo {
hasLicense: boolean;
expiry: number;
licenseUrl: string;
stateInfo: string;
}
export class GrafanaBootConfig {
datasources: { [str: string]: DataSourceInstanceSettings } = {};
panels: { [key: string]: PanelPluginMeta } = {};
appSubUrl = '';
windowTitlePrefix = '';
buildInfo: BuildInfo = {} as BuildInfo;
newPanelTitle = '';
bootData: any;
externalUserMngLinkUrl = '';
externalUserMngLinkName = '';
externalUserMngInfo = '';
allowOrgCreate = false;
disableLoginForm = false;
defaultDatasource = '';
alertingEnabled = false;
alertingErrorOrTimeout = '';
alertingNoDataOrNullValues = '';
alertingMinInterval = 1;
authProxyEnabled = false;
exploreEnabled = false;
ldapEnabled = false;
samlEnabled = false;
oauth: any;
disableUserSignUp = false;
loginHint: any;
passwordHint: any;
loginError: any;
viewersCanEdit = false;
editorsCanAdmin = false;
disableSanitizeHtml = false;
theme: GrafanaTheme;
pluginsToPreload: string[] = [];
featureToggles: FeatureToggles = {
transformations: false,
inspect: false,
expressions: false,
newEdit: false,
meta: false,
};
licenseInfo: LicenseInfo = {} as LicenseInfo;
constructor(options: GrafanaBootConfig) {
this.theme = options.bootData.user.lightTheme ? getTheme(GrafanaThemeType.Light) : getTheme(GrafanaThemeType.Dark);
const defaults = {
datasources: {},
windowTitlePrefix: 'Grafana - ',
panels: {},
newPanelTitle: 'Panel Title',
playlist_timespan: '1m',
unsaved_changes_warning: true,
appSubUrl: '',
buildInfo: {
version: 'v1.0',
commit: '1',
env: 'production',
isEnterprise: false,
},
viewersCanEdit: false,
editorsCanAdmin: false,
disableSanitizeHtml: false,
};
extend(this, defaults, options);
}
}
const bootData = (window as any).grafanaBootData || {
settings: {},
user: {},
};
const options = bootData.settings;
options.bootData = bootData;
export const config = new GrafanaBootConfig(options);
| packages/grafana-runtime/src/config.ts | 1 | https://github.com/grafana/grafana/commit/6e80315531a0184b60021af3557a2b155a43b036 | [
0.0018364262068644166,
0.0004534289182629436,
0.0001665331656113267,
0.00017094284703489393,
0.0005763922235928476
] |
{
"id": 1,
"code_window": [
"import (\n",
"\t\"strconv\"\n",
"\n",
"\t\"github.com/grafana/grafana/pkg/components/simplejson\"\n",
"\t\"github.com/grafana/grafana/pkg/util\"\n",
"\n",
"\t\"github.com/grafana/grafana/pkg/bus\"\n",
"\t\"github.com/grafana/grafana/pkg/infra/log\"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\"github.com/grafana/grafana/pkg/services/rendering\"\n",
"\n"
],
"file_path": "pkg/api/frontendsettings.go",
"type": "add",
"edit_start_line_idx": 5
} | // cgo -godefs types_netbsd.go | go run mkpost.go
// Code generated by the command above; see README.md. DO NOT EDIT.
// +build amd64,netbsd
package unix
const (
SizeofPtr = 0x8
SizeofShort = 0x2
SizeofInt = 0x4
SizeofLong = 0x8
SizeofLongLong = 0x8
)
type (
_C_short int16
_C_int int32
_C_long int64
_C_long_long int64
)
type Timespec struct {
Sec int64
Nsec int64
}
type Timeval struct {
Sec int64
Usec int32
Pad_cgo_0 [4]byte
}
type Rusage struct {
Utime Timeval
Stime Timeval
Maxrss int64
Ixrss int64
Idrss int64
Isrss int64
Minflt int64
Majflt int64
Nswap int64
Inblock int64
Oublock int64
Msgsnd int64
Msgrcv int64
Nsignals int64
Nvcsw int64
Nivcsw int64
}
type Rlimit struct {
Cur uint64
Max uint64
}
type _Gid_t uint32
type Stat_t struct {
Dev uint64
Mode uint32
_ [4]byte
Ino uint64
Nlink uint32
Uid uint32
Gid uint32
_ [4]byte
Rdev uint64
Atim Timespec
Mtim Timespec
Ctim Timespec
Btim Timespec
Size int64
Blocks int64
Blksize uint32
Flags uint32
Gen uint32
Spare [2]uint32
_ [4]byte
}
type Statfs_t [0]byte
type Statvfs_t struct {
Flag uint64
Bsize uint64
Frsize uint64
Iosize uint64
Blocks uint64
Bfree uint64
Bavail uint64
Bresvd uint64
Files uint64
Ffree uint64
Favail uint64
Fresvd uint64
Syncreads uint64
Syncwrites uint64
Asyncreads uint64
Asyncwrites uint64
Fsidx Fsid
Fsid uint64
Namemax uint64
Owner uint32
Spare [4]uint32
Fstypename [32]byte
Mntonname [1024]byte
Mntfromname [1024]byte
_ [4]byte
}
type Flock_t struct {
Start int64
Len int64
Pid int32
Type int16
Whence int16
}
type Dirent struct {
Fileno uint64
Reclen uint16
Namlen uint16
Type uint8
Name [512]int8
Pad_cgo_0 [3]byte
}
type Fsid struct {
X__fsid_val [2]int32
}
const (
PathMax = 0x400
)
const (
ST_WAIT = 0x1
ST_NOWAIT = 0x2
)
const (
FADV_NORMAL = 0x0
FADV_RANDOM = 0x1
FADV_SEQUENTIAL = 0x2
FADV_WILLNEED = 0x3
FADV_DONTNEED = 0x4
FADV_NOREUSE = 0x5
)
type RawSockaddrInet4 struct {
Len uint8
Family uint8
Port uint16
Addr [4]byte /* in_addr */
Zero [8]int8
}
type RawSockaddrInet6 struct {
Len uint8
Family uint8
Port uint16
Flowinfo uint32
Addr [16]byte /* in6_addr */
Scope_id uint32
}
type RawSockaddrUnix struct {
Len uint8
Family uint8
Path [104]int8
}
type RawSockaddrDatalink struct {
Len uint8
Family uint8
Index uint16
Type uint8
Nlen uint8
Alen uint8
Slen uint8
Data [12]int8
}
type RawSockaddr struct {
Len uint8
Family uint8
Data [14]int8
}
type RawSockaddrAny struct {
Addr RawSockaddr
Pad [92]int8
}
type _Socklen uint32
type Linger struct {
Onoff int32
Linger int32
}
type Iovec struct {
Base *byte
Len uint64
}
type IPMreq struct {
Multiaddr [4]byte /* in_addr */
Interface [4]byte /* in_addr */
}
type IPv6Mreq struct {
Multiaddr [16]byte /* in6_addr */
Interface uint32
}
type Msghdr struct {
Name *byte
Namelen uint32
Pad_cgo_0 [4]byte
Iov *Iovec
Iovlen int32
Pad_cgo_1 [4]byte
Control *byte
Controllen uint32
Flags int32
}
type Cmsghdr struct {
Len uint32
Level int32
Type int32
}
type Inet6Pktinfo struct {
Addr [16]byte /* in6_addr */
Ifindex uint32
}
type IPv6MTUInfo struct {
Addr RawSockaddrInet6
Mtu uint32
}
type ICMPv6Filter struct {
Filt [8]uint32
}
const (
SizeofSockaddrInet4 = 0x10
SizeofSockaddrInet6 = 0x1c
SizeofSockaddrAny = 0x6c
SizeofSockaddrUnix = 0x6a
SizeofSockaddrDatalink = 0x14
SizeofLinger = 0x8
SizeofIPMreq = 0x8
SizeofIPv6Mreq = 0x14
SizeofMsghdr = 0x30
SizeofCmsghdr = 0xc
SizeofInet6Pktinfo = 0x14
SizeofIPv6MTUInfo = 0x20
SizeofICMPv6Filter = 0x20
)
const (
PTRACE_TRACEME = 0x0
PTRACE_CONT = 0x7
PTRACE_KILL = 0x8
)
type Kevent_t struct {
Ident uint64
Filter uint32
Flags uint32
Fflags uint32
Pad_cgo_0 [4]byte
Data int64
Udata int64
}
type FdSet struct {
Bits [8]uint32
}
const (
SizeofIfMsghdr = 0x98
SizeofIfData = 0x88
SizeofIfaMsghdr = 0x18
SizeofIfAnnounceMsghdr = 0x18
SizeofRtMsghdr = 0x78
SizeofRtMetrics = 0x50
)
type IfMsghdr struct {
Msglen uint16
Version uint8
Type uint8
Addrs int32
Flags int32
Index uint16
Pad_cgo_0 [2]byte
Data IfData
}
type IfData struct {
Type uint8
Addrlen uint8
Hdrlen uint8
Pad_cgo_0 [1]byte
Link_state int32
Mtu uint64
Metric uint64
Baudrate uint64
Ipackets uint64
Ierrors uint64
Opackets uint64
Oerrors uint64
Collisions uint64
Ibytes uint64
Obytes uint64
Imcasts uint64
Omcasts uint64
Iqdrops uint64
Noproto uint64
Lastchange Timespec
}
type IfaMsghdr struct {
Msglen uint16
Version uint8
Type uint8
Addrs int32
Flags int32
Metric int32
Index uint16
Pad_cgo_0 [6]byte
}
type IfAnnounceMsghdr struct {
Msglen uint16
Version uint8
Type uint8
Index uint16
Name [16]int8
What uint16
}
type RtMsghdr struct {
Msglen uint16
Version uint8
Type uint8
Index uint16
Pad_cgo_0 [2]byte
Flags int32
Addrs int32
Pid int32
Seq int32
Errno int32
Use int32
Inits int32
Pad_cgo_1 [4]byte
Rmx RtMetrics
}
type RtMetrics struct {
Locks uint64
Mtu uint64
Hopcount uint64
Recvpipe uint64
Sendpipe uint64
Ssthresh uint64
Rtt uint64
Rttvar uint64
Expire int64
Pksent int64
}
type Mclpool [0]byte
const (
SizeofBpfVersion = 0x4
SizeofBpfStat = 0x80
SizeofBpfProgram = 0x10
SizeofBpfInsn = 0x8
SizeofBpfHdr = 0x20
)
type BpfVersion struct {
Major uint16
Minor uint16
}
type BpfStat struct {
Recv uint64
Drop uint64
Capt uint64
Padding [13]uint64
}
type BpfProgram struct {
Len uint32
Pad_cgo_0 [4]byte
Insns *BpfInsn
}
type BpfInsn struct {
Code uint16
Jt uint8
Jf uint8
K uint32
}
type BpfHdr struct {
Tstamp BpfTimeval
Caplen uint32
Datalen uint32
Hdrlen uint16
Pad_cgo_0 [6]byte
}
type BpfTimeval struct {
Sec int64
Usec int64
}
type Termios struct {
Iflag uint32
Oflag uint32
Cflag uint32
Lflag uint32
Cc [20]uint8
Ispeed int32
Ospeed int32
}
type Winsize struct {
Row uint16
Col uint16
Xpixel uint16
Ypixel uint16
}
type Ptmget struct {
Cfd int32
Sfd int32
Cn [1024]byte
Sn [1024]byte
}
const (
AT_FDCWD = -0x64
AT_SYMLINK_FOLLOW = 0x400
AT_SYMLINK_NOFOLLOW = 0x200
)
type PollFd struct {
Fd int32
Events int16
Revents int16
}
const (
POLLERR = 0x8
POLLHUP = 0x10
POLLIN = 0x1
POLLNVAL = 0x20
POLLOUT = 0x4
POLLPRI = 0x2
POLLRDBAND = 0x80
POLLRDNORM = 0x40
POLLWRBAND = 0x100
POLLWRNORM = 0x4
)
type Sysctlnode struct {
Flags uint32
Num int32
Name [32]int8
Ver uint32
X__rsvd uint32
Un [16]byte
X_sysctl_size [8]byte
X_sysctl_func [8]byte
X_sysctl_parent [8]byte
X_sysctl_desc [8]byte
}
type Utsname struct {
Sysname [256]byte
Nodename [256]byte
Release [256]byte
Version [256]byte
Machine [256]byte
}
const SizeofClockinfo = 0x14
type Clockinfo struct {
Hz int32
Tick int32
Tickadj int32
Stathz int32
Profhz int32
}
| vendor/golang.org/x/sys/unix/ztypes_netbsd_amd64.go | 0 | https://github.com/grafana/grafana/commit/6e80315531a0184b60021af3557a2b155a43b036 | [
0.0009405732853338122,
0.0002202807372668758,
0.00016244742437265813,
0.0001712593511911109,
0.0001450325216865167
] |
{
"id": 1,
"code_window": [
"import (\n",
"\t\"strconv\"\n",
"\n",
"\t\"github.com/grafana/grafana/pkg/components/simplejson\"\n",
"\t\"github.com/grafana/grafana/pkg/util\"\n",
"\n",
"\t\"github.com/grafana/grafana/pkg/bus\"\n",
"\t\"github.com/grafana/grafana/pkg/infra/log\"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\"github.com/grafana/grafana/pkg/services/rendering\"\n",
"\n"
],
"file_path": "pkg/api/frontendsettings.go",
"type": "add",
"edit_start_line_idx": 5
} | import config from 'app/core/config';
import 'app/features/plugins/datasource_srv';
import { DatasourceSrv } from 'app/features/plugins/datasource_srv';
import { PluginMeta, DataSourcePluginMeta } from '@grafana/data';
// Datasource variable $datasource with current value 'BBB'
const templateSrv: any = {
variables: [
{
type: 'datasource',
name: 'datasource',
current: {
value: 'BBB',
},
},
],
};
describe('datasource_srv', () => {
const _datasourceSrv = new DatasourceSrv({} as any, {} as any, templateSrv);
describe('when loading external datasources', () => {
beforeEach(() => {
config.datasources = {
buildInDs: {
id: 1,
type: 'b',
name: 'buildIn',
meta: { builtIn: true } as DataSourcePluginMeta,
jsonData: {},
},
nonBuildIn: {
id: 2,
type: 'e',
name: 'external1',
meta: { builtIn: false } as DataSourcePluginMeta,
jsonData: {},
},
nonExplore: {
id: 3,
type: 'e2',
name: 'external2',
meta: {} as PluginMeta,
jsonData: {},
},
};
});
it('should return list of explore sources', () => {
const externalSources = _datasourceSrv.getExternal();
expect(externalSources.length).toBe(2);
expect(externalSources[0].name).toBe('external1');
expect(externalSources[1].name).toBe('external2');
});
});
describe('when loading metric sources', () => {
let metricSources: any;
const unsortedDatasources = {
mmm: {
type: 'test-db',
meta: { metrics: { m: 1 } },
},
'--Grafana--': {
type: 'grafana',
meta: { builtIn: true, metrics: { m: 1 }, id: 'grafana' },
},
'--Mixed--': {
type: 'test-db',
meta: { builtIn: true, metrics: { m: 1 }, id: 'mixed' },
},
ZZZ: {
type: 'test-db',
meta: { metrics: { m: 1 } },
},
aaa: {
type: 'test-db',
meta: { metrics: { m: 1 } },
},
BBB: {
type: 'test-db',
meta: { metrics: { m: 1 } },
},
};
beforeEach(() => {
config.datasources = unsortedDatasources as any;
metricSources = _datasourceSrv.getMetricSources({});
config.defaultDatasource = 'BBB';
});
it('should return a list of sources sorted case insensitively with builtin sources last', () => {
expect(metricSources[1].name).toBe('aaa');
expect(metricSources[2].name).toBe('BBB');
expect(metricSources[3].name).toBe('mmm');
expect(metricSources[4].name).toBe('ZZZ');
expect(metricSources[5].name).toBe('--Grafana--');
expect(metricSources[6].name).toBe('--Mixed--');
});
it('should set default data source', () => {
expect(metricSources[3].name).toBe('default');
expect(metricSources[3].sort).toBe('BBB');
});
it('should set default inject the variable datasources', () => {
expect(metricSources[0].name).toBe('$datasource');
expect(metricSources[0].sort).toBe('$datasource');
});
});
});
| public/app/features/plugins/specs/datasource_srv.test.ts | 0 | https://github.com/grafana/grafana/commit/6e80315531a0184b60021af3557a2b155a43b036 | [
0.0002013830526266247,
0.00017594434029888362,
0.00016683514695614576,
0.00017298775492236018,
0.000010078755622089375
] |
{
"id": 1,
"code_window": [
"import (\n",
"\t\"strconv\"\n",
"\n",
"\t\"github.com/grafana/grafana/pkg/components/simplejson\"\n",
"\t\"github.com/grafana/grafana/pkg/util\"\n",
"\n",
"\t\"github.com/grafana/grafana/pkg/bus\"\n",
"\t\"github.com/grafana/grafana/pkg/infra/log\"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\"github.com/grafana/grafana/pkg/services/rendering\"\n",
"\n"
],
"file_path": "pkg/api/frontendsettings.go",
"type": "add",
"edit_start_line_idx": 5
} | package util
import (
"fmt"
"net"
"strings"
"github.com/grafana/grafana/pkg/util/errutil"
)
// ParseIPAddress parses an IP address and removes port and/or IPV6 format
func ParseIPAddress(input string) (string, error) {
addr, err := SplitHostPort(input)
if err != nil {
return "", errutil.Wrapf(err, "Failed to split network address '%s' by host and port",
input)
}
ip := net.ParseIP(addr.Host)
if ip == nil {
return addr.Host, nil
}
if ip.IsLoopback() {
if strings.Contains(addr.Host, ":") {
// IPv6
return "::1", nil
}
return "127.0.0.1", nil
}
return ip.String(), nil
}
type NetworkAddress struct {
Host string
Port string
}
// SplitHostPortDefault splits ip address/hostname string by host and port. Defaults used if no match found
func SplitHostPortDefault(input, defaultHost, defaultPort string) (NetworkAddress, error) {
addr := NetworkAddress{
Host: defaultHost,
Port: defaultPort,
}
if len(input) == 0 {
return addr, nil
}
start := 0
// Determine if IPv6 address, in which case IP address will be enclosed in square brackets
if strings.Index(input, "[") == 0 {
addrEnd := strings.LastIndex(input, "]")
if addrEnd < 0 {
// Malformed address
return addr, fmt.Errorf("Malformed IPv6 address: '%s'", input)
}
start = addrEnd
}
if strings.LastIndex(input[start:], ":") < 0 {
// There's no port section of the input
// It's still useful to call net.SplitHostPort though, since it removes IPv6
// square brackets from the address
input = fmt.Sprintf("%s:%s", input, defaultPort)
}
host, port, err := net.SplitHostPort(input)
if err != nil {
return addr, errutil.Wrapf(err, "net.SplitHostPort failed for '%s'", input)
}
if len(host) > 0 {
addr.Host = host
}
if len(port) > 0 {
addr.Port = port
}
return addr, nil
}
// SplitHostPort splits ip address/hostname string by host and port
func SplitHostPort(input string) (NetworkAddress, error) {
if len(input) == 0 {
return NetworkAddress{}, fmt.Errorf("Input is empty")
}
return SplitHostPortDefault(input, "", "")
}
| pkg/util/ip_address.go | 0 | https://github.com/grafana/grafana/commit/6e80315531a0184b60021af3557a2b155a43b036 | [
0.005730248987674713,
0.0008881532703526318,
0.00016543004312552512,
0.0001695185201242566,
0.0017185704782605171
] |
{
"id": 2,
"code_window": [
"\t\t\t\"expiry\": hs.License.Expiry(),\n",
"\t\t\t\"stateInfo\": hs.License.StateInfo(),\n",
"\t\t\t\"licenseUrl\": hs.License.LicenseURL(c.SignedInUser),\n",
"\t\t},\n",
"\t\t\"featureToggles\": hs.Cfg.FeatureToggles,\n",
"\t}\n",
"\n",
"\treturn jsonObj, nil\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\"featureToggles\": hs.Cfg.FeatureToggles,\n",
"\t\t\"phantomJSRenderer\": rendering.IsPhantomJSEnabled,\n"
],
"file_path": "pkg/api/frontendsettings.go",
"type": "replace",
"edit_start_line_idx": 208
} | package rendering
import (
"context"
"fmt"
"net/url"
"os"
"path/filepath"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/middleware"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/plugins"
"github.com/grafana/grafana/pkg/registry"
"github.com/grafana/grafana/pkg/setting"
"github.com/grafana/grafana/pkg/util"
)
func init() {
registry.RegisterService(&RenderingService{})
}
type RenderingService struct {
log log.Logger
pluginInfo *plugins.RendererPlugin
renderAction renderFunc
domain string
inProgressCount int
Cfg *setting.Cfg `inject:""`
}
func (rs *RenderingService) Init() error {
rs.log = log.New("rendering")
// ensure ImagesDir exists
err := os.MkdirAll(rs.Cfg.ImagesDir, 0700)
if err != nil {
return err
}
// set value used for domain attribute of renderKey cookie
if rs.Cfg.RendererUrl != "" {
// RendererCallbackUrl has already been passed, it won't generate an error.
u, _ := url.Parse(rs.Cfg.RendererCallbackUrl)
rs.domain = u.Hostname()
} else if setting.HttpAddr != setting.DEFAULT_HTTP_ADDR {
rs.domain = setting.HttpAddr
} else {
rs.domain = "localhost"
}
return nil
}
func (rs *RenderingService) Run(ctx context.Context) error {
if rs.Cfg.RendererUrl != "" {
rs.log = rs.log.New("renderer", "http")
rs.log.Info("Backend rendering via external http server")
rs.renderAction = rs.renderViaHttp
<-ctx.Done()
return nil
}
if plugins.Renderer == nil {
rs.log = rs.log.New("renderer", "phantomJS")
rs.log.Info("Backend rendering via phantomJS")
rs.log.Warn("phantomJS is deprecated and will be removed in a future release. " +
"You should consider migrating from phantomJS to grafana-image-renderer plugin. " +
"Read more at https://grafana.com/docs/grafana/latest/administration/image_rendering/")
rs.renderAction = rs.renderViaPhantomJS
<-ctx.Done()
return nil
}
rs.log = rs.log.New("renderer", "plugin")
rs.pluginInfo = plugins.Renderer
if err := rs.startPlugin(ctx); err != nil {
return err
}
rs.renderAction = rs.renderViaPlugin
<-ctx.Done()
return nil
}
func (rs *RenderingService) RenderErrorImage(err error) (*RenderResult, error) {
imgUrl := "public/img/rendering_error.png"
return &RenderResult{
FilePath: filepath.Join(setting.HomePath, imgUrl),
}, nil
}
func (rs *RenderingService) Render(ctx context.Context, opts Opts) (*RenderResult, error) {
if rs.inProgressCount > opts.ConcurrentLimit {
return &RenderResult{
FilePath: filepath.Join(setting.HomePath, "public/img/rendering_limit.png"),
}, nil
}
defer func() {
rs.inProgressCount -= 1
}()
rs.inProgressCount += 1
if rs.renderAction != nil {
rs.log.Info("Rendering", "path", opts.Path)
return rs.renderAction(ctx, opts)
}
return nil, fmt.Errorf("No renderer found")
}
func (rs *RenderingService) getFilePathForNewImage() (string, error) {
rand, err := util.GetRandomString(20)
if err != nil {
return "", err
}
pngPath, err := filepath.Abs(filepath.Join(rs.Cfg.ImagesDir, rand))
if err != nil {
return "", err
}
return pngPath + ".png", nil
}
func (rs *RenderingService) getURL(path string) string {
if rs.Cfg.RendererUrl != "" {
// The backend rendering service can potentially be remote.
// So we need to use the root_url to ensure the rendering service
// can reach this Grafana instance.
// &render=1 signals to the legacy redirect layer to
return fmt.Sprintf("%s%s&render=1", rs.Cfg.RendererCallbackUrl, path)
}
protocol := setting.Protocol
switch setting.Protocol {
case setting.HTTP:
protocol = "http"
case setting.HTTP2, setting.HTTPS:
protocol = "https"
}
// &render=1 signals to the legacy redirect layer to
return fmt.Sprintf("%s://%s:%s/%s&render=1", protocol, rs.domain, setting.HttpPort, path)
}
func (rs *RenderingService) getRenderKey(orgId, userId int64, orgRole models.RoleType) (string, error) {
return middleware.AddRenderAuthKey(orgId, userId, orgRole)
}
| pkg/services/rendering/rendering.go | 1 | https://github.com/grafana/grafana/commit/6e80315531a0184b60021af3557a2b155a43b036 | [
0.00021136454597581178,
0.00017480943643022329,
0.0001648686738917604,
0.0001722147862892598,
0.00001017099930322729
] |
{
"id": 2,
"code_window": [
"\t\t\t\"expiry\": hs.License.Expiry(),\n",
"\t\t\t\"stateInfo\": hs.License.StateInfo(),\n",
"\t\t\t\"licenseUrl\": hs.License.LicenseURL(c.SignedInUser),\n",
"\t\t},\n",
"\t\t\"featureToggles\": hs.Cfg.FeatureToggles,\n",
"\t}\n",
"\n",
"\treturn jsonObj, nil\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\"featureToggles\": hs.Cfg.FeatureToggles,\n",
"\t\t\"phantomJSRenderer\": rendering.IsPhantomJSEnabled,\n"
],
"file_path": "pkg/api/frontendsettings.go",
"type": "replace",
"edit_start_line_idx": 208
} | Jinja2>=2.10
MarkupSafe>=1.1.0
wget>=3.2
| scripts/build/ci-msi-build/msigenerator/requirements.txt | 0 | https://github.com/grafana/grafana/commit/6e80315531a0184b60021af3557a2b155a43b036 | [
0.00017754272266756743,
0.00017754272266756743,
0.00017754272266756743,
0.00017754272266756743,
0
] |
{
"id": 2,
"code_window": [
"\t\t\t\"expiry\": hs.License.Expiry(),\n",
"\t\t\t\"stateInfo\": hs.License.StateInfo(),\n",
"\t\t\t\"licenseUrl\": hs.License.LicenseURL(c.SignedInUser),\n",
"\t\t},\n",
"\t\t\"featureToggles\": hs.Cfg.FeatureToggles,\n",
"\t}\n",
"\n",
"\treturn jsonObj, nil\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\"featureToggles\": hs.Cfg.FeatureToggles,\n",
"\t\t\"phantomJSRenderer\": rendering.IsPhantomJSEnabled,\n"
],
"file_path": "pkg/api/frontendsettings.go",
"type": "replace",
"edit_start_line_idx": 208
} | package hclog
import (
"bytes"
"strings"
)
// Provides a io.Writer to shim the data out of *log.Logger
// and back into our Logger. This is basically the only way to
// build upon *log.Logger.
type stdlogAdapter struct {
log Logger
inferLevels bool
}
// Take the data, infer the levels if configured, and send it through
// a regular Logger.
func (s *stdlogAdapter) Write(data []byte) (int, error) {
str := string(bytes.TrimRight(data, " \t\n"))
if s.inferLevels {
level, str := s.pickLevel(str)
switch level {
case Trace:
s.log.Trace(str)
case Debug:
s.log.Debug(str)
case Info:
s.log.Info(str)
case Warn:
s.log.Warn(str)
case Error:
s.log.Error(str)
default:
s.log.Info(str)
}
} else {
s.log.Info(str)
}
return len(data), nil
}
// Detect, based on conventions, what log level this is.
func (s *stdlogAdapter) pickLevel(str string) (Level, string) {
switch {
case strings.HasPrefix(str, "[DEBUG]"):
return Debug, strings.TrimSpace(str[7:])
case strings.HasPrefix(str, "[TRACE]"):
return Trace, strings.TrimSpace(str[7:])
case strings.HasPrefix(str, "[INFO]"):
return Info, strings.TrimSpace(str[6:])
case strings.HasPrefix(str, "[WARN]"):
return Warn, strings.TrimSpace(str[7:])
case strings.HasPrefix(str, "[ERROR]"):
return Error, strings.TrimSpace(str[7:])
case strings.HasPrefix(str, "[ERR]"):
return Error, strings.TrimSpace(str[5:])
default:
return Info, str
}
}
| vendor/github.com/hashicorp/go-hclog/stdlog.go | 0 | https://github.com/grafana/grafana/commit/6e80315531a0184b60021af3557a2b155a43b036 | [
0.00017988437321037054,
0.00017492298502475023,
0.0001700339635135606,
0.00017540287808515131,
0.0000034179154226876562
] |
{
"id": 2,
"code_window": [
"\t\t\t\"expiry\": hs.License.Expiry(),\n",
"\t\t\t\"stateInfo\": hs.License.StateInfo(),\n",
"\t\t\t\"licenseUrl\": hs.License.LicenseURL(c.SignedInUser),\n",
"\t\t},\n",
"\t\t\"featureToggles\": hs.Cfg.FeatureToggles,\n",
"\t}\n",
"\n",
"\treturn jsonObj, nil\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\"featureToggles\": hs.Cfg.FeatureToggles,\n",
"\t\t\"phantomJSRenderer\": rendering.IsPhantomJSEnabled,\n"
],
"file_path": "pkg/api/frontendsettings.go",
"type": "replace",
"edit_start_line_idx": 208
} | // Copyright (C) 2018 G.J.R. Timmer <[email protected]>.
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
package sqlite3
import (
"crypto/sha1"
"crypto/sha256"
"crypto/sha512"
)
// This file provides several different implementations for the
// default embedded sqlite_crypt function.
// This function is uses a caesar-cypher by default
// and is used within the UserAuthentication module to encode
// the password.
//
// The provided functions can be used as an overload to the sqlite_crypt
// function through the use of the RegisterFunc on the connection.
//
// Because the functions can serv a purpose to an end-user
// without using the UserAuthentication module
// the functions are default compiled in.
//
// From SQLITE3 - user-auth.txt
// The sqlite_user.pw field is encoded by a built-in SQL function
// "sqlite_crypt(X,Y)". The two arguments are both BLOBs. The first argument
// is the plaintext password supplied to the sqlite3_user_authenticate()
// interface. The second argument is the sqlite_user.pw value and is supplied
// so that the function can extract the "salt" used by the password encoder.
// The result of sqlite_crypt(X,Y) is another blob which is the value that
// ends up being stored in sqlite_user.pw. To verify credentials X supplied
// by the sqlite3_user_authenticate() routine, SQLite runs:
//
// sqlite_user.pw == sqlite_crypt(X, sqlite_user.pw)
//
// To compute an appropriate sqlite_user.pw value from a new or modified
// password X, sqlite_crypt(X,NULL) is run. A new random salt is selected
// when the second argument is NULL.
//
// The built-in version of of sqlite_crypt() uses a simple Caesar-cypher
// which prevents passwords from being revealed by searching the raw database
// for ASCII text, but is otherwise trivally broken. For better password
// security, the database should be encrypted using the SQLite Encryption
// Extension or similar technology. Or, the application can use the
// sqlite3_create_function() interface to provide an alternative
// implementation of sqlite_crypt() that computes a stronger password hash,
// perhaps using a cryptographic hash function like SHA1.
// CryptEncoderSHA1 encodes a password with SHA1
func CryptEncoderSHA1(pass []byte, hash interface{}) []byte {
h := sha1.Sum(pass)
return h[:]
}
// CryptEncoderSSHA1 encodes a password with SHA1 with the
// configured salt.
func CryptEncoderSSHA1(salt string) func(pass []byte, hash interface{}) []byte {
return func(pass []byte, hash interface{}) []byte {
s := []byte(salt)
p := append(pass, s...)
h := sha1.Sum(p)
return h[:]
}
}
// CryptEncoderSHA256 encodes a password with SHA256
func CryptEncoderSHA256(pass []byte, hash interface{}) []byte {
h := sha256.Sum256(pass)
return h[:]
}
// CryptEncoderSSHA256 encodes a password with SHA256
// with the configured salt
func CryptEncoderSSHA256(salt string) func(pass []byte, hash interface{}) []byte {
return func(pass []byte, hash interface{}) []byte {
s := []byte(salt)
p := append(pass, s...)
h := sha256.Sum256(p)
return h[:]
}
}
// CryptEncoderSHA384 encodes a password with SHA384
func CryptEncoderSHA384(pass []byte, hash interface{}) []byte {
h := sha512.Sum384(pass)
return h[:]
}
// CryptEncoderSSHA384 encodes a password with SHA384
// with the configured salt
func CryptEncoderSSHA384(salt string) func(pass []byte, hash interface{}) []byte {
return func(pass []byte, hash interface{}) []byte {
s := []byte(salt)
p := append(pass, s...)
h := sha512.Sum384(p)
return h[:]
}
}
// CryptEncoderSHA512 encodes a password with SHA512
func CryptEncoderSHA512(pass []byte, hash interface{}) []byte {
h := sha512.Sum512(pass)
return h[:]
}
// CryptEncoderSSHA512 encodes a password with SHA512
// with the configured salt
func CryptEncoderSSHA512(salt string) func(pass []byte, hash interface{}) []byte {
return func(pass []byte, hash interface{}) []byte {
s := []byte(salt)
p := append(pass, s...)
h := sha512.Sum512(p)
return h[:]
}
}
// EOF
| vendor/github.com/mattn/go-sqlite3/sqlite3_func_crypt.go | 0 | https://github.com/grafana/grafana/commit/6e80315531a0184b60021af3557a2b155a43b036 | [
0.0003875869733747095,
0.0002072271890938282,
0.00016360254085157067,
0.00017737400776240975,
0.00006197689799591899
] |
{
"id": 3,
"code_window": [
"\tregistry.RegisterService(&RenderingService{})\n",
"}\n",
"\n",
"type RenderingService struct {\n",
"\tlog log.Logger\n",
"\tpluginInfo *plugins.RendererPlugin\n",
"\trenderAction renderFunc\n",
"\tdomain string\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"var IsPhantomJSEnabled = false\n",
"\n"
],
"file_path": "pkg/services/rendering/rendering.go",
"type": "add",
"edit_start_line_idx": 22
} | // Libraries
import _ from 'lodash';
import $ from 'jquery';
// @ts-ignore
import Drop from 'tether-drop';
// Utils and servies
import { colors } from '@grafana/ui';
import { setBackendSrv, setDataSourceSrv } from '@grafana/runtime';
import config from 'app/core/config';
import coreModule from 'app/core/core_module';
import { profiler } from 'app/core/profiler';
import appEvents from 'app/core/app_events';
import { TimeSrv, setTimeSrv } from 'app/features/dashboard/services/TimeSrv';
import { DatasourceSrv } from 'app/features/plugins/datasource_srv';
import { KeybindingSrv, setKeybindingSrv } from 'app/core/services/keybindingSrv';
import { AngularLoader, setAngularLoader } from 'app/core/services/AngularLoader';
import { configureStore } from 'app/store/configureStore';
import { LocationUpdate, setLocationSrv } from '@grafana/runtime';
import { updateLocation } from 'app/core/actions';
// Types
import { KioskUrlValue, CoreEvents, AppEventEmitter, AppEventConsumer } from 'app/types';
import { setLinkSrv, LinkSrv } from 'app/features/panel/panellinks/link_srv';
import { UtilSrv } from 'app/core/services/util_srv';
import { ContextSrv } from 'app/core/services/context_srv';
import { BridgeSrv } from 'app/core/services/bridge_srv';
import { PlaylistSrv } from 'app/features/playlist/playlist_srv';
import { DashboardSrv, setDashboardSrv } from 'app/features/dashboard/services/DashboardSrv';
import { ILocationService, ITimeoutService, IRootScopeService, IAngularEvent } from 'angular';
import { AppEvent, AppEvents } from '@grafana/data';
import { backendSrv } from 'app/core/services/backend_srv';
export type GrafanaRootScope = IRootScopeService & AppEventEmitter & AppEventConsumer & { colors: string[] };
export class GrafanaCtrl {
/** @ngInject */
constructor(
$scope: any,
utilSrv: UtilSrv,
$rootScope: GrafanaRootScope,
contextSrv: ContextSrv,
bridgeSrv: BridgeSrv,
timeSrv: TimeSrv,
linkSrv: LinkSrv,
datasourceSrv: DatasourceSrv,
keybindingSrv: KeybindingSrv,
dashboardSrv: DashboardSrv,
angularLoader: AngularLoader
) {
// make angular loader service available to react components
setAngularLoader(angularLoader);
setBackendSrv(backendSrv);
setDataSourceSrv(datasourceSrv);
setTimeSrv(timeSrv);
setLinkSrv(linkSrv);
setKeybindingSrv(keybindingSrv);
setDashboardSrv(dashboardSrv);
const store = configureStore();
setLocationSrv({
update: (opt: LocationUpdate) => {
store.dispatch(updateLocation(opt));
},
});
$scope.init = () => {
$scope.contextSrv = contextSrv;
$scope.appSubUrl = config.appSubUrl;
$scope._ = _;
profiler.init(config, $rootScope);
utilSrv.init();
bridgeSrv.init();
};
$rootScope.colors = colors;
$rootScope.onAppEvent = function<T>(
event: AppEvent<T> | string,
callback: (event: IAngularEvent, ...args: any[]) => void,
localScope?: any
) {
let unbind;
if (typeof event === 'string') {
unbind = $rootScope.$on(event, callback);
} else {
unbind = $rootScope.$on(event.name, callback);
}
let callerScope = this;
if (callerScope.$id === 1 && !localScope) {
console.log('warning rootScope onAppEvent called without localscope');
}
if (localScope) {
callerScope = localScope;
}
callerScope.$on('$destroy', unbind);
};
$rootScope.appEvent = <T>(event: AppEvent<T> | string, payload?: T | any) => {
if (typeof event === 'string') {
$rootScope.$emit(event, payload);
appEvents.emit(event, payload);
} else {
$rootScope.$emit(event.name, payload);
appEvents.emit(event, payload);
}
};
$scope.init();
}
}
function setViewModeBodyClass(body: JQuery, mode: KioskUrlValue) {
body.removeClass('view-mode--tv');
body.removeClass('view-mode--kiosk');
body.removeClass('view-mode--inactive');
switch (mode) {
case 'tv': {
body.addClass('view-mode--tv');
break;
}
// 1 & true for legacy states
case '1':
case true: {
body.addClass('view-mode--kiosk');
break;
}
}
}
/** @ngInject */
export function grafanaAppDirective(
playlistSrv: PlaylistSrv,
contextSrv: ContextSrv,
$timeout: ITimeoutService,
$rootScope: IRootScopeService,
$location: ILocationService
) {
return {
restrict: 'E',
controller: GrafanaCtrl,
link: (scope: IRootScopeService & AppEventEmitter, elem: JQuery) => {
const body = $('body');
// see https://github.com/zenorocha/clipboard.js/issues/155
$.fn.modal.Constructor.prototype.enforceFocus = () => {};
$('.preloader').remove();
appEvents.on(CoreEvents.toggleSidemenuMobile, () => {
body.toggleClass('sidemenu-open--xs');
});
appEvents.on(CoreEvents.toggleSidemenuHidden, () => {
body.toggleClass('sidemenu-hidden');
});
appEvents.on(CoreEvents.playlistStarted, () => {
elem.toggleClass('view-mode--playlist', true);
});
appEvents.on(CoreEvents.playlistStopped, () => {
elem.toggleClass('view-mode--playlist', false);
});
// check if we are in server side render
if (document.cookie.indexOf('renderKey') !== -1) {
body.addClass('body--phantomjs');
}
// tooltip removal fix
// manage page classes
let pageClass: string;
scope.$on('$routeChangeSuccess', (evt: any, data: any) => {
if (pageClass) {
body.removeClass(pageClass);
}
if (data.$$route) {
pageClass = data.$$route.pageClass;
if (pageClass) {
body.addClass(pageClass);
}
}
// clear body class sidemenu states
body.removeClass('sidemenu-open--xs');
$('#tooltip, .tooltip').remove();
// check for kiosk url param
setViewModeBodyClass(body, data.params.kiosk);
// close all drops
for (const drop of Drop.drops) {
drop.destroy();
}
appEvents.emit(CoreEvents.hideDashSearch);
});
// handle kiosk mode
appEvents.on(CoreEvents.toggleKioskMode, (options: { exit?: boolean }) => {
const search: { kiosk?: KioskUrlValue } = $location.search();
if (options && options.exit) {
search.kiosk = '1';
}
switch (search.kiosk) {
case 'tv': {
search.kiosk = true;
appEvents.emit(AppEvents.alertSuccess, ['Press ESC to exit Kiosk mode']);
break;
}
case '1':
case true: {
delete search.kiosk;
break;
}
default: {
search.kiosk = 'tv';
}
}
$timeout(() => $location.search(search));
setViewModeBodyClass(body, search.kiosk!);
});
// handle in active view state class
let lastActivity = new Date().getTime();
let activeUser = true;
const inActiveTimeLimit = 60 * 5000;
function checkForInActiveUser() {
if (!activeUser) {
return;
}
// only go to activity low mode on dashboard page
if (!body.hasClass('page-dashboard')) {
return;
}
if (new Date().getTime() - lastActivity > inActiveTimeLimit) {
activeUser = false;
body.addClass('view-mode--inactive');
}
}
function userActivityDetected() {
lastActivity = new Date().getTime();
if (!activeUser) {
activeUser = true;
body.removeClass('view-mode--inactive');
}
}
// mouse and keyboard is user activity
body.mousemove(userActivityDetected);
body.keydown(userActivityDetected);
// set useCapture = true to catch event here
document.addEventListener('wheel', userActivityDetected, { capture: true, passive: true });
// treat tab change as activity
document.addEventListener('visibilitychange', userActivityDetected);
// check every 2 seconds
setInterval(checkForInActiveUser, 2000);
appEvents.on(CoreEvents.toggleViewMode, () => {
lastActivity = 0;
checkForInActiveUser();
});
// handle document clicks that should hide things
body.click(evt => {
const target = $(evt.target);
if (target.parents().length === 0) {
return;
}
// ensure dropdown menu doesn't impact on z-index
body.find('.dropdown-menu-open').removeClass('dropdown-menu-open');
// for stuff that animates, slides out etc, clicking it needs to
// hide it right away
const clickAutoHide = target.closest('[data-click-hide]');
if (clickAutoHide.length) {
const clickAutoHideParent = clickAutoHide.parent();
clickAutoHide.detach();
setTimeout(() => {
clickAutoHideParent.append(clickAutoHide);
}, 100);
}
// hide search
if (body.find('.search-container').length > 0) {
if (target.parents('.search-results-container, .search-field-wrapper').length === 0) {
scope.$apply(() => {
scope.appEvent(CoreEvents.hideDashSearch);
});
}
}
// hide popovers
const popover = elem.find('.popover');
if (popover.length > 0 && target.parents('.graph-legend').length === 0) {
popover.hide();
}
});
},
};
}
coreModule.directive('grafanaApp', grafanaAppDirective);
| public/app/routes/GrafanaCtrl.ts | 1 | https://github.com/grafana/grafana/commit/6e80315531a0184b60021af3557a2b155a43b036 | [
0.0001986696879612282,
0.0001747367496136576,
0.00016857942682690918,
0.00017448572907596827,
0.000004955807526130229
] |
{
"id": 3,
"code_window": [
"\tregistry.RegisterService(&RenderingService{})\n",
"}\n",
"\n",
"type RenderingService struct {\n",
"\tlog log.Logger\n",
"\tpluginInfo *plugins.RendererPlugin\n",
"\trenderAction renderFunc\n",
"\tdomain string\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"var IsPhantomJSEnabled = false\n",
"\n"
],
"file_path": "pkg/services/rendering/rendering.go",
"type": "add",
"edit_start_line_idx": 22
} | package dtos
import (
"github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/plugins"
)
type PluginSetting struct {
Name string `json:"name"`
Type string `json:"type"`
Id string `json:"id"`
Enabled bool `json:"enabled"`
Pinned bool `json:"pinned"`
Module string `json:"module"`
BaseUrl string `json:"baseUrl"`
Info *plugins.PluginInfo `json:"info"`
Includes []*plugins.PluginInclude `json:"includes"`
Dependencies *plugins.PluginDependencies `json:"dependencies"`
JsonData map[string]interface{} `json:"jsonData"`
DefaultNavUrl string `json:"defaultNavUrl"`
LatestVersion string `json:"latestVersion"`
HasUpdate bool `json:"hasUpdate"`
State plugins.PluginState `json:"state"`
}
type PluginListItem struct {
Name string `json:"name"`
Type string `json:"type"`
Id string `json:"id"`
Enabled bool `json:"enabled"`
Pinned bool `json:"pinned"`
Info *plugins.PluginInfo `json:"info"`
LatestVersion string `json:"latestVersion"`
HasUpdate bool `json:"hasUpdate"`
DefaultNavUrl string `json:"defaultNavUrl"`
Category string `json:"category"`
State plugins.PluginState `json:"state"`
}
type PluginList []PluginListItem
func (slice PluginList) Len() int {
return len(slice)
}
func (slice PluginList) Less(i, j int) bool {
return slice[i].Name < slice[j].Name
}
func (slice PluginList) Swap(i, j int) {
slice[i], slice[j] = slice[j], slice[i]
}
type ImportDashboardCommand struct {
PluginId string `json:"pluginId"`
Path string `json:"path"`
Overwrite bool `json:"overwrite"`
Dashboard *simplejson.Json `json:"dashboard"`
Inputs []plugins.ImportDashboardInput `json:"inputs"`
FolderId int64 `json:"folderId"`
}
| pkg/api/dtos/plugins.go | 0 | https://github.com/grafana/grafana/commit/6e80315531a0184b60021af3557a2b155a43b036 | [
0.0009913636604323983,
0.0005374588654376566,
0.00016790871450211853,
0.0005120474961586297,
0.0003188096743542701
] |
{
"id": 3,
"code_window": [
"\tregistry.RegisterService(&RenderingService{})\n",
"}\n",
"\n",
"type RenderingService struct {\n",
"\tlog log.Logger\n",
"\tpluginInfo *plugins.RendererPlugin\n",
"\trenderAction renderFunc\n",
"\tdomain string\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"var IsPhantomJSEnabled = false\n",
"\n"
],
"file_path": "pkg/services/rendering/rendering.go",
"type": "add",
"edit_start_line_idx": 22
} | import React from 'react';
import Loadable from 'react-loadable';
import { LoadingChunkPlaceHolder } from './LoadingChunkPlaceHolder';
import { ErrorLoadingChunk } from './ErrorLoadingChunk';
export const loadComponentHandler = (props: { error: Error; pastDelay: boolean }) => {
const { error, pastDelay } = props;
if (error) {
return <ErrorLoadingChunk error={error} />;
}
if (pastDelay) {
return <LoadingChunkPlaceHolder />;
}
return null;
};
export const SafeDynamicImport = (importStatement: Promise<any>) => ({ ...props }) => {
const LoadableComponent = Loadable({
loader: () => importStatement,
loading: loadComponentHandler,
});
return <LoadableComponent {...props} />;
};
| public/app/core/components/DynamicImports/SafeDynamicImport.tsx | 0 | https://github.com/grafana/grafana/commit/6e80315531a0184b60021af3557a2b155a43b036 | [
0.00017618197307456285,
0.00017472973559051752,
0.00017375375318806618,
0.00017425348050892353,
0.0000010469566404935904
] |
{
"id": 3,
"code_window": [
"\tregistry.RegisterService(&RenderingService{})\n",
"}\n",
"\n",
"type RenderingService struct {\n",
"\tlog log.Logger\n",
"\tpluginInfo *plugins.RendererPlugin\n",
"\trenderAction renderFunc\n",
"\tdomain string\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"var IsPhantomJSEnabled = false\n",
"\n"
],
"file_path": "pkg/services/rendering/rendering.go",
"type": "add",
"edit_start_line_idx": 22
} | import tinycolor from 'tinycolor2';
import { css } from 'emotion';
import { selectThemeVariant, stylesFactory } from '../../themes';
import { StyleDeps, ButtonSize } from './types';
import { GrafanaTheme } from '@grafana/data';
const buttonVariantStyles = (
from: string,
to: string,
textColor: string,
textShadowColor = 'rgba(0, 0, 0, 0.1)',
invert = false
) => css`
background: linear-gradient(to bottom, ${from}, ${to});
color: ${textColor};
text-shadow: 0 ${invert ? '1px' : '-1px'} ${textShadowColor};
&:hover {
background: ${from};
color: ${textColor};
}
&:focus {
background: ${from};
outline: none;
}
`;
export const getButtonStyles = stylesFactory(({ theme, size, variant, textAndIcon }: StyleDeps) => {
const borderRadius = theme.border.radius.sm;
const { padding, fontSize, height, fontWeight } = calculateMeasures(theme, size, !!textAndIcon);
let background;
switch (variant) {
case 'primary':
background = buttonVariantStyles(theme.colors.greenBase, theme.colors.greenShade, theme.colors.white);
break;
case 'secondary':
background = buttonVariantStyles(theme.colors.blueBase, theme.colors.blueShade, theme.colors.white);
break;
case 'danger':
background = buttonVariantStyles(theme.colors.redBase, theme.colors.redShade, theme.colors.white);
break;
case 'inverse':
const from = selectThemeVariant({ light: theme.colors.gray5, dark: theme.colors.dark6 }, theme.type) as string;
const to = selectThemeVariant(
{
light: tinycolor(from)
.darken(5)
.toString(),
dark: tinycolor(from)
.lighten(4)
.toString(),
},
theme.type
) as string;
background = buttonVariantStyles(from, to, theme.colors.link, 'rgba(0, 0, 0, 0.1)', true);
break;
case 'transparent':
background = css`
${buttonVariantStyles('', '', theme.colors.link, 'rgba(0, 0, 0, 0.1)', true)};
background: transparent;
`;
break;
case 'link':
background = css`
${buttonVariantStyles('', '', theme.colors.linkExternal, 'rgba(0, 0, 0, 0.1)', true)};
background: transparent;
`;
break;
}
return {
button: css`
label: button;
display: inline-flex;
align-items: center;
font-weight: ${fontWeight};
font-size: ${fontSize};
font-family: ${theme.typography.fontFamily.sansSerif};
line-height: ${theme.typography.lineHeight.xs};
padding: ${padding};
vertical-align: middle;
cursor: pointer;
border: none;
height: ${height};
border-radius: ${borderRadius};
${background};
&[disabled],
&:disabled {
cursor: not-allowed;
opacity: 0.65;
box-shadow: none;
}
`,
iconWrap: css`
label: button-icon-wrap;
& + * {
margin-left: ${theme.spacing.sm};
}
`,
};
});
type ButtonMeasures = {
padding: string;
fontSize: string;
height: string;
fontWeight: number;
};
const calculateMeasures = (theme: GrafanaTheme, size: ButtonSize, textAndIcon: boolean): ButtonMeasures => {
switch (size) {
case 'sm': {
return {
padding: `${theme.spacing.xs} ${theme.spacing.sm}`,
fontSize: theme.typography.size.sm,
height: theme.height.sm,
fontWeight: theme.typography.weight.semibold,
};
}
case 'md': {
const leftPadding = textAndIcon ? theme.spacing.sm : theme.spacing.md;
return {
padding: `${theme.spacing.sm} ${theme.spacing.md} ${theme.spacing.sm} ${leftPadding}`,
fontSize: theme.typography.size.md,
height: theme.height.md,
fontWeight: theme.typography.weight.semibold,
};
}
case 'lg': {
const leftPadding = textAndIcon ? theme.spacing.md : theme.spacing.lg;
return {
padding: `${theme.spacing.md} ${theme.spacing.lg} ${theme.spacing.md} ${leftPadding}`,
fontSize: theme.typography.size.lg,
height: theme.height.lg,
fontWeight: theme.typography.weight.regular,
};
}
default: {
const leftPadding = textAndIcon ? theme.spacing.sm : theme.spacing.md;
return {
padding: `${theme.spacing.sm} ${theme.spacing.md} ${theme.spacing.sm} ${leftPadding}`,
fontSize: theme.typography.size.base,
height: theme.height.md,
fontWeight: theme.typography.weight.regular,
};
}
}
};
| packages/grafana-ui/src/components/Button/styles.ts | 0 | https://github.com/grafana/grafana/commit/6e80315531a0184b60021af3557a2b155a43b036 | [
0.0011433009058237076,
0.000258753658272326,
0.0001685144961811602,
0.00017603956803213805,
0.0002449250896461308
] |
{
"id": 4,
"code_window": [
"\t\trs.log.Info(\"Backend rendering via phantomJS\")\n",
"\t\trs.log.Warn(\"phantomJS is deprecated and will be removed in a future release. \" +\n",
"\t\t\t\"You should consider migrating from phantomJS to grafana-image-renderer plugin. \" +\n",
"\t\t\t\"Read more at https://grafana.com/docs/grafana/latest/administration/image_rendering/\")\n",
"\t\trs.renderAction = rs.renderViaPhantomJS\n",
"\t\t<-ctx.Done()\n",
"\t\treturn nil\n",
"\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tIsPhantomJSEnabled = true\n"
],
"file_path": "pkg/services/rendering/rendering.go",
"type": "add",
"edit_start_line_idx": 71
} | package rendering
import (
"context"
"fmt"
"net/url"
"os"
"path/filepath"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/middleware"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/plugins"
"github.com/grafana/grafana/pkg/registry"
"github.com/grafana/grafana/pkg/setting"
"github.com/grafana/grafana/pkg/util"
)
func init() {
registry.RegisterService(&RenderingService{})
}
type RenderingService struct {
log log.Logger
pluginInfo *plugins.RendererPlugin
renderAction renderFunc
domain string
inProgressCount int
Cfg *setting.Cfg `inject:""`
}
func (rs *RenderingService) Init() error {
rs.log = log.New("rendering")
// ensure ImagesDir exists
err := os.MkdirAll(rs.Cfg.ImagesDir, 0700)
if err != nil {
return err
}
// set value used for domain attribute of renderKey cookie
if rs.Cfg.RendererUrl != "" {
// RendererCallbackUrl has already been passed, it won't generate an error.
u, _ := url.Parse(rs.Cfg.RendererCallbackUrl)
rs.domain = u.Hostname()
} else if setting.HttpAddr != setting.DEFAULT_HTTP_ADDR {
rs.domain = setting.HttpAddr
} else {
rs.domain = "localhost"
}
return nil
}
func (rs *RenderingService) Run(ctx context.Context) error {
if rs.Cfg.RendererUrl != "" {
rs.log = rs.log.New("renderer", "http")
rs.log.Info("Backend rendering via external http server")
rs.renderAction = rs.renderViaHttp
<-ctx.Done()
return nil
}
if plugins.Renderer == nil {
rs.log = rs.log.New("renderer", "phantomJS")
rs.log.Info("Backend rendering via phantomJS")
rs.log.Warn("phantomJS is deprecated and will be removed in a future release. " +
"You should consider migrating from phantomJS to grafana-image-renderer plugin. " +
"Read more at https://grafana.com/docs/grafana/latest/administration/image_rendering/")
rs.renderAction = rs.renderViaPhantomJS
<-ctx.Done()
return nil
}
rs.log = rs.log.New("renderer", "plugin")
rs.pluginInfo = plugins.Renderer
if err := rs.startPlugin(ctx); err != nil {
return err
}
rs.renderAction = rs.renderViaPlugin
<-ctx.Done()
return nil
}
func (rs *RenderingService) RenderErrorImage(err error) (*RenderResult, error) {
imgUrl := "public/img/rendering_error.png"
return &RenderResult{
FilePath: filepath.Join(setting.HomePath, imgUrl),
}, nil
}
func (rs *RenderingService) Render(ctx context.Context, opts Opts) (*RenderResult, error) {
if rs.inProgressCount > opts.ConcurrentLimit {
return &RenderResult{
FilePath: filepath.Join(setting.HomePath, "public/img/rendering_limit.png"),
}, nil
}
defer func() {
rs.inProgressCount -= 1
}()
rs.inProgressCount += 1
if rs.renderAction != nil {
rs.log.Info("Rendering", "path", opts.Path)
return rs.renderAction(ctx, opts)
}
return nil, fmt.Errorf("No renderer found")
}
func (rs *RenderingService) getFilePathForNewImage() (string, error) {
rand, err := util.GetRandomString(20)
if err != nil {
return "", err
}
pngPath, err := filepath.Abs(filepath.Join(rs.Cfg.ImagesDir, rand))
if err != nil {
return "", err
}
return pngPath + ".png", nil
}
func (rs *RenderingService) getURL(path string) string {
if rs.Cfg.RendererUrl != "" {
// The backend rendering service can potentially be remote.
// So we need to use the root_url to ensure the rendering service
// can reach this Grafana instance.
// &render=1 signals to the legacy redirect layer to
return fmt.Sprintf("%s%s&render=1", rs.Cfg.RendererCallbackUrl, path)
}
protocol := setting.Protocol
switch setting.Protocol {
case setting.HTTP:
protocol = "http"
case setting.HTTP2, setting.HTTPS:
protocol = "https"
}
// &render=1 signals to the legacy redirect layer to
return fmt.Sprintf("%s://%s:%s/%s&render=1", protocol, rs.domain, setting.HttpPort, path)
}
func (rs *RenderingService) getRenderKey(orgId, userId int64, orgRole models.RoleType) (string, error) {
return middleware.AddRenderAuthKey(orgId, userId, orgRole)
}
| pkg/services/rendering/rendering.go | 1 | https://github.com/grafana/grafana/commit/6e80315531a0184b60021af3557a2b155a43b036 | [
0.9933537244796753,
0.07591624557971954,
0.000169719394762069,
0.0025759954005479813,
0.24038918316364288
] |
{
"id": 4,
"code_window": [
"\t\trs.log.Info(\"Backend rendering via phantomJS\")\n",
"\t\trs.log.Warn(\"phantomJS is deprecated and will be removed in a future release. \" +\n",
"\t\t\t\"You should consider migrating from phantomJS to grafana-image-renderer plugin. \" +\n",
"\t\t\t\"Read more at https://grafana.com/docs/grafana/latest/administration/image_rendering/\")\n",
"\t\trs.renderAction = rs.renderViaPhantomJS\n",
"\t\t<-ctx.Done()\n",
"\t\treturn nil\n",
"\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tIsPhantomJSEnabled = true\n"
],
"file_path": "pkg/services/rendering/rendering.go",
"type": "add",
"edit_start_line_idx": 71
} | package migrations
import . "github.com/grafana/grafana/pkg/services/sqlstore/migrator"
func addDashboardVersionMigration(mg *Migrator) {
dashboardVersionV1 := Table{
Name: "dashboard_version",
Columns: []*Column{
{Name: "id", Type: DB_BigInt, IsPrimaryKey: true, IsAutoIncrement: true},
{Name: "dashboard_id", Type: DB_BigInt},
{Name: "parent_version", Type: DB_Int, Nullable: false},
{Name: "restored_from", Type: DB_Int, Nullable: false},
{Name: "version", Type: DB_Int, Nullable: false},
{Name: "created", Type: DB_DateTime, Nullable: false},
{Name: "created_by", Type: DB_BigInt, Nullable: false},
{Name: "message", Type: DB_Text, Nullable: false},
{Name: "data", Type: DB_Text, Nullable: false},
},
Indices: []*Index{
{Cols: []string{"dashboard_id"}},
{Cols: []string{"dashboard_id", "version"}, Type: UniqueIndex},
},
}
mg.AddMigration("create dashboard_version table v1", NewAddTableMigration(dashboardVersionV1))
mg.AddMigration("add index dashboard_version.dashboard_id", NewAddIndexMigration(dashboardVersionV1, dashboardVersionV1.Indices[0]))
mg.AddMigration("add unique index dashboard_version.dashboard_id and dashboard_version.version", NewAddIndexMigration(dashboardVersionV1, dashboardVersionV1.Indices[1]))
// before new dashboards where created with version 0, now they are always inserted with version 1
const setVersionTo1WhereZeroSQL = `UPDATE dashboard SET version = 1 WHERE version = 0`
mg.AddMigration("Set dashboard version to 1 where 0", NewRawSqlMigration(setVersionTo1WhereZeroSQL))
const rawSQL = `INSERT INTO dashboard_version
(
dashboard_id,
version,
parent_version,
restored_from,
created,
created_by,
message,
data
)
SELECT
dashboard.id,
dashboard.version,
dashboard.version,
dashboard.version,
dashboard.updated,
COALESCE(dashboard.updated_by, -1),
'',
dashboard.data
FROM dashboard;`
mg.AddMigration("save existing dashboard data in dashboard_version table v1", NewRawSqlMigration(rawSQL))
// change column type of dashboard_version.data
mg.AddMigration("alter dashboard_version.data to mediumtext v1", NewRawSqlMigration("").
Mysql("ALTER TABLE dashboard_version MODIFY data MEDIUMTEXT;"))
}
| pkg/services/sqlstore/migrations/dashboard_version_mig.go | 0 | https://github.com/grafana/grafana/commit/6e80315531a0184b60021af3557a2b155a43b036 | [
0.0009697620407678187,
0.000303751410683617,
0.00016745607717894018,
0.0001717449922580272,
0.00029785564402118325
] |
{
"id": 4,
"code_window": [
"\t\trs.log.Info(\"Backend rendering via phantomJS\")\n",
"\t\trs.log.Warn(\"phantomJS is deprecated and will be removed in a future release. \" +\n",
"\t\t\t\"You should consider migrating from phantomJS to grafana-image-renderer plugin. \" +\n",
"\t\t\t\"Read more at https://grafana.com/docs/grafana/latest/administration/image_rendering/\")\n",
"\t\trs.renderAction = rs.renderViaPhantomJS\n",
"\t\t<-ctx.Done()\n",
"\t\treturn nil\n",
"\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tIsPhantomJSEnabled = true\n"
],
"file_path": "pkg/services/rendering/rendering.go",
"type": "add",
"edit_start_line_idx": 71
} | packages/grafana-toolkit/src/config/mocks/stylesheetsSupport/ok/src/styles/light.css | 0 | https://github.com/grafana/grafana/commit/6e80315531a0184b60021af3557a2b155a43b036 | [
0.0001691178185865283,
0.0001691178185865283,
0.0001691178185865283,
0.0001691178185865283,
0
] |
|
{
"id": 4,
"code_window": [
"\t\trs.log.Info(\"Backend rendering via phantomJS\")\n",
"\t\trs.log.Warn(\"phantomJS is deprecated and will be removed in a future release. \" +\n",
"\t\t\t\"You should consider migrating from phantomJS to grafana-image-renderer plugin. \" +\n",
"\t\t\t\"Read more at https://grafana.com/docs/grafana/latest/administration/image_rendering/\")\n",
"\t\trs.renderAction = rs.renderViaPhantomJS\n",
"\t\t<-ctx.Done()\n",
"\t\treturn nil\n",
"\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tIsPhantomJSEnabled = true\n"
],
"file_path": "pkg/services/rendering/rendering.go",
"type": "add",
"edit_start_line_idx": 71
} | package match
import (
"fmt"
"github.com/gobwas/glob/util/runes"
"unicode/utf8"
)
// single represents ?
type Single struct {
Separators []rune
}
func NewSingle(s []rune) Single {
return Single{s}
}
func (self Single) Match(s string) bool {
r, w := utf8.DecodeRuneInString(s)
if len(s) > w {
return false
}
return runes.IndexRune(self.Separators, r) == -1
}
func (self Single) Len() int {
return lenOne
}
func (self Single) Index(s string) (int, []int) {
for i, r := range s {
if runes.IndexRune(self.Separators, r) == -1 {
return i, segmentsByRuneLength[utf8.RuneLen(r)]
}
}
return -1, nil
}
func (self Single) String() string {
return fmt.Sprintf("<single:![%s]>", string(self.Separators))
}
| vendor/github.com/gobwas/glob/match/single.go | 0 | https://github.com/grafana/grafana/commit/6e80315531a0184b60021af3557a2b155a43b036 | [
0.00017143238801509142,
0.00016548755229450762,
0.00015840389824006706,
0.00016450151451863348,
0.00000518196475240984
] |
{
"id": 5,
"code_window": [
" elem.toggleClass('view-mode--playlist', false);\n",
" });\n",
"\n",
" // check if we are in server side render\n",
" if (document.cookie.indexOf('renderKey') !== -1) {\n",
" body.addClass('body--phantomjs');\n",
" }\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (config.phantomJSRenderer && document.cookie.indexOf('renderKey') !== -1) {\n"
],
"file_path": "public/app/routes/GrafanaCtrl.ts",
"type": "replace",
"edit_start_line_idx": 169
} | // Libraries
import _ from 'lodash';
import $ from 'jquery';
// @ts-ignore
import Drop from 'tether-drop';
// Utils and servies
import { colors } from '@grafana/ui';
import { setBackendSrv, setDataSourceSrv } from '@grafana/runtime';
import config from 'app/core/config';
import coreModule from 'app/core/core_module';
import { profiler } from 'app/core/profiler';
import appEvents from 'app/core/app_events';
import { TimeSrv, setTimeSrv } from 'app/features/dashboard/services/TimeSrv';
import { DatasourceSrv } from 'app/features/plugins/datasource_srv';
import { KeybindingSrv, setKeybindingSrv } from 'app/core/services/keybindingSrv';
import { AngularLoader, setAngularLoader } from 'app/core/services/AngularLoader';
import { configureStore } from 'app/store/configureStore';
import { LocationUpdate, setLocationSrv } from '@grafana/runtime';
import { updateLocation } from 'app/core/actions';
// Types
import { KioskUrlValue, CoreEvents, AppEventEmitter, AppEventConsumer } from 'app/types';
import { setLinkSrv, LinkSrv } from 'app/features/panel/panellinks/link_srv';
import { UtilSrv } from 'app/core/services/util_srv';
import { ContextSrv } from 'app/core/services/context_srv';
import { BridgeSrv } from 'app/core/services/bridge_srv';
import { PlaylistSrv } from 'app/features/playlist/playlist_srv';
import { DashboardSrv, setDashboardSrv } from 'app/features/dashboard/services/DashboardSrv';
import { ILocationService, ITimeoutService, IRootScopeService, IAngularEvent } from 'angular';
import { AppEvent, AppEvents } from '@grafana/data';
import { backendSrv } from 'app/core/services/backend_srv';
export type GrafanaRootScope = IRootScopeService & AppEventEmitter & AppEventConsumer & { colors: string[] };
export class GrafanaCtrl {
/** @ngInject */
constructor(
$scope: any,
utilSrv: UtilSrv,
$rootScope: GrafanaRootScope,
contextSrv: ContextSrv,
bridgeSrv: BridgeSrv,
timeSrv: TimeSrv,
linkSrv: LinkSrv,
datasourceSrv: DatasourceSrv,
keybindingSrv: KeybindingSrv,
dashboardSrv: DashboardSrv,
angularLoader: AngularLoader
) {
// make angular loader service available to react components
setAngularLoader(angularLoader);
setBackendSrv(backendSrv);
setDataSourceSrv(datasourceSrv);
setTimeSrv(timeSrv);
setLinkSrv(linkSrv);
setKeybindingSrv(keybindingSrv);
setDashboardSrv(dashboardSrv);
const store = configureStore();
setLocationSrv({
update: (opt: LocationUpdate) => {
store.dispatch(updateLocation(opt));
},
});
$scope.init = () => {
$scope.contextSrv = contextSrv;
$scope.appSubUrl = config.appSubUrl;
$scope._ = _;
profiler.init(config, $rootScope);
utilSrv.init();
bridgeSrv.init();
};
$rootScope.colors = colors;
$rootScope.onAppEvent = function<T>(
event: AppEvent<T> | string,
callback: (event: IAngularEvent, ...args: any[]) => void,
localScope?: any
) {
let unbind;
if (typeof event === 'string') {
unbind = $rootScope.$on(event, callback);
} else {
unbind = $rootScope.$on(event.name, callback);
}
let callerScope = this;
if (callerScope.$id === 1 && !localScope) {
console.log('warning rootScope onAppEvent called without localscope');
}
if (localScope) {
callerScope = localScope;
}
callerScope.$on('$destroy', unbind);
};
$rootScope.appEvent = <T>(event: AppEvent<T> | string, payload?: T | any) => {
if (typeof event === 'string') {
$rootScope.$emit(event, payload);
appEvents.emit(event, payload);
} else {
$rootScope.$emit(event.name, payload);
appEvents.emit(event, payload);
}
};
$scope.init();
}
}
function setViewModeBodyClass(body: JQuery, mode: KioskUrlValue) {
body.removeClass('view-mode--tv');
body.removeClass('view-mode--kiosk');
body.removeClass('view-mode--inactive');
switch (mode) {
case 'tv': {
body.addClass('view-mode--tv');
break;
}
// 1 & true for legacy states
case '1':
case true: {
body.addClass('view-mode--kiosk');
break;
}
}
}
/** @ngInject */
export function grafanaAppDirective(
playlistSrv: PlaylistSrv,
contextSrv: ContextSrv,
$timeout: ITimeoutService,
$rootScope: IRootScopeService,
$location: ILocationService
) {
return {
restrict: 'E',
controller: GrafanaCtrl,
link: (scope: IRootScopeService & AppEventEmitter, elem: JQuery) => {
const body = $('body');
// see https://github.com/zenorocha/clipboard.js/issues/155
$.fn.modal.Constructor.prototype.enforceFocus = () => {};
$('.preloader').remove();
appEvents.on(CoreEvents.toggleSidemenuMobile, () => {
body.toggleClass('sidemenu-open--xs');
});
appEvents.on(CoreEvents.toggleSidemenuHidden, () => {
body.toggleClass('sidemenu-hidden');
});
appEvents.on(CoreEvents.playlistStarted, () => {
elem.toggleClass('view-mode--playlist', true);
});
appEvents.on(CoreEvents.playlistStopped, () => {
elem.toggleClass('view-mode--playlist', false);
});
// check if we are in server side render
if (document.cookie.indexOf('renderKey') !== -1) {
body.addClass('body--phantomjs');
}
// tooltip removal fix
// manage page classes
let pageClass: string;
scope.$on('$routeChangeSuccess', (evt: any, data: any) => {
if (pageClass) {
body.removeClass(pageClass);
}
if (data.$$route) {
pageClass = data.$$route.pageClass;
if (pageClass) {
body.addClass(pageClass);
}
}
// clear body class sidemenu states
body.removeClass('sidemenu-open--xs');
$('#tooltip, .tooltip').remove();
// check for kiosk url param
setViewModeBodyClass(body, data.params.kiosk);
// close all drops
for (const drop of Drop.drops) {
drop.destroy();
}
appEvents.emit(CoreEvents.hideDashSearch);
});
// handle kiosk mode
appEvents.on(CoreEvents.toggleKioskMode, (options: { exit?: boolean }) => {
const search: { kiosk?: KioskUrlValue } = $location.search();
if (options && options.exit) {
search.kiosk = '1';
}
switch (search.kiosk) {
case 'tv': {
search.kiosk = true;
appEvents.emit(AppEvents.alertSuccess, ['Press ESC to exit Kiosk mode']);
break;
}
case '1':
case true: {
delete search.kiosk;
break;
}
default: {
search.kiosk = 'tv';
}
}
$timeout(() => $location.search(search));
setViewModeBodyClass(body, search.kiosk!);
});
// handle in active view state class
let lastActivity = new Date().getTime();
let activeUser = true;
const inActiveTimeLimit = 60 * 5000;
function checkForInActiveUser() {
if (!activeUser) {
return;
}
// only go to activity low mode on dashboard page
if (!body.hasClass('page-dashboard')) {
return;
}
if (new Date().getTime() - lastActivity > inActiveTimeLimit) {
activeUser = false;
body.addClass('view-mode--inactive');
}
}
function userActivityDetected() {
lastActivity = new Date().getTime();
if (!activeUser) {
activeUser = true;
body.removeClass('view-mode--inactive');
}
}
// mouse and keyboard is user activity
body.mousemove(userActivityDetected);
body.keydown(userActivityDetected);
// set useCapture = true to catch event here
document.addEventListener('wheel', userActivityDetected, { capture: true, passive: true });
// treat tab change as activity
document.addEventListener('visibilitychange', userActivityDetected);
// check every 2 seconds
setInterval(checkForInActiveUser, 2000);
appEvents.on(CoreEvents.toggleViewMode, () => {
lastActivity = 0;
checkForInActiveUser();
});
// handle document clicks that should hide things
body.click(evt => {
const target = $(evt.target);
if (target.parents().length === 0) {
return;
}
// ensure dropdown menu doesn't impact on z-index
body.find('.dropdown-menu-open').removeClass('dropdown-menu-open');
// for stuff that animates, slides out etc, clicking it needs to
// hide it right away
const clickAutoHide = target.closest('[data-click-hide]');
if (clickAutoHide.length) {
const clickAutoHideParent = clickAutoHide.parent();
clickAutoHide.detach();
setTimeout(() => {
clickAutoHideParent.append(clickAutoHide);
}, 100);
}
// hide search
if (body.find('.search-container').length > 0) {
if (target.parents('.search-results-container, .search-field-wrapper').length === 0) {
scope.$apply(() => {
scope.appEvent(CoreEvents.hideDashSearch);
});
}
}
// hide popovers
const popover = elem.find('.popover');
if (popover.length > 0 && target.parents('.graph-legend').length === 0) {
popover.hide();
}
});
},
};
}
coreModule.directive('grafanaApp', grafanaAppDirective);
| public/app/routes/GrafanaCtrl.ts | 1 | https://github.com/grafana/grafana/commit/6e80315531a0184b60021af3557a2b155a43b036 | [
0.9802708625793457,
0.03610988333821297,
0.00017241893510799855,
0.0002037557278526947,
0.1699833869934082
] |
{
"id": 5,
"code_window": [
" elem.toggleClass('view-mode--playlist', false);\n",
" });\n",
"\n",
" // check if we are in server side render\n",
" if (document.cookie.indexOf('renderKey') !== -1) {\n",
" body.addClass('body--phantomjs');\n",
" }\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (config.phantomJSRenderer && document.cookie.indexOf('renderKey') !== -1) {\n"
],
"file_path": "public/app/routes/GrafanaCtrl.ts",
"type": "replace",
"edit_start_line_idx": 169
} | <div class="gf-form-inline">
<div class="gf-form">
<span class="gf-form-label">Mode</span>
<span class="gf-form-select-wrapper">
<select class="gf-form-input" ng-model="ctrl.panel.mode" ng-options="f for f in ['html','markdown']"></select>
</span>
</div>
</div>
<div class="gf-form-inline">
<div class="gf-form gf-form--grow">
<code-editor content="ctrl.panel.content" on-change="ctrl.render()" data-mode="markdown" data-max-lines=20>
</code-editor>
</div>
</div>
| public/app/plugins/panel/text/editor.html | 0 | https://github.com/grafana/grafana/commit/6e80315531a0184b60021af3557a2b155a43b036 | [
0.00017010838200803846,
0.00016713188961148262,
0.00016415538266301155,
0.00016713188961148262,
0.000002976499672513455
] |
{
"id": 5,
"code_window": [
" elem.toggleClass('view-mode--playlist', false);\n",
" });\n",
"\n",
" // check if we are in server side render\n",
" if (document.cookie.indexOf('renderKey') !== -1) {\n",
" body.addClass('body--phantomjs');\n",
" }\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (config.phantomJSRenderer && document.cookie.indexOf('renderKey') !== -1) {\n"
],
"file_path": "public/app/routes/GrafanaCtrl.ts",
"type": "replace",
"edit_start_line_idx": 169
} | // Copyright 2019 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build darwin,go1.12,!go1.13
package unix
import (
"unsafe"
)
func Getdirentries(fd int, buf []byte, basep *uintptr) (n int, err error) {
// To implement this using libSystem we'd need syscall_syscallPtr for
// fdopendir. However, syscallPtr was only added in Go 1.13, so we fall
// back to raw syscalls for this func on Go 1.12.
var p unsafe.Pointer
if len(buf) > 0 {
p = unsafe.Pointer(&buf[0])
} else {
p = unsafe.Pointer(&_zero)
}
r0, _, e1 := Syscall6(SYS_GETDIRENTRIES64, uintptr(fd), uintptr(p), uintptr(len(buf)), uintptr(unsafe.Pointer(basep)), 0, 0)
n = int(r0)
if e1 != 0 {
return n, errnoErr(e1)
}
return n, nil
}
| vendor/golang.org/x/sys/unix/syscall_darwin.1_12.go | 0 | https://github.com/grafana/grafana/commit/6e80315531a0184b60021af3557a2b155a43b036 | [
0.00017797492910176516,
0.00017286867660004646,
0.0001648694451432675,
0.0001757616555551067,
0.000005728025826101657
] |
{
"id": 5,
"code_window": [
" elem.toggleClass('view-mode--playlist', false);\n",
" });\n",
"\n",
" // check if we are in server side render\n",
" if (document.cookie.indexOf('renderKey') !== -1) {\n",
" body.addClass('body--phantomjs');\n",
" }\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (config.phantomJSRenderer && document.cookie.indexOf('renderKey') !== -1) {\n"
],
"file_path": "public/app/routes/GrafanaCtrl.ts",
"type": "replace",
"edit_start_line_idx": 169
} | {
"annotations": {
"list": [
{
"builtIn": 1,
"datasource": "-- Grafana --",
"enable": true,
"hide": true,
"iconColor": "rgba(0, 211, 255, 1)",
"name": "Annotations & Alerts",
"type": "dashboard"
}
]
},
"editable": true,
"gnetId": null,
"graphTooltip": 0,
"links": [],
"panels": [
{
"cacheTimeout": null,
"colorBackground": false,
"colorValue": true,
"colors": ["#299c46", "rgba(237, 129, 40, 0.89)", "#d44a3a"],
"datasource": "gdev-testdata",
"decimals": null,
"description": "",
"format": "ms",
"gauge": {
"maxValue": 100,
"minValue": 0,
"show": false,
"thresholdLabels": false,
"thresholdMarkers": true
},
"gridPos": {
"h": 7,
"w": 8,
"x": 0,
"y": 0
},
"id": 2,
"interval": null,
"links": [],
"mappingType": 1,
"mappingTypes": [
{
"name": "value to text",
"value": 1
},
{
"name": "range to text",
"value": 2
}
],
"maxDataPoints": 100,
"nullPointMode": "connected",
"nullText": null,
"postfix": "postfix",
"postfixFontSize": "50%",
"prefix": "prefix",
"prefixFontSize": "50%",
"rangeMaps": [
{
"from": "null",
"text": "N/A",
"to": "null"
}
],
"sparkline": {
"fillColor": "rgba(31, 118, 189, 0.18)",
"full": false,
"lineColor": "rgb(31, 120, 193)",
"show": true
},
"tableColumn": "",
"targets": [
{
"expr": "",
"format": "time_series",
"intervalFactor": 1,
"refId": "A",
"scenarioId": "csv_metric_values",
"stringInput": "1,2,3,4,5"
}
],
"thresholds": "5,10",
"title": "prefix 3 ms (green) postfixt + sparkline",
"type": "singlestat",
"valueFontSize": "80%",
"valueMaps": [
{
"op": "=",
"text": "N/A",
"value": "null"
}
],
"valueName": "avg"
},
{
"cacheTimeout": null,
"colorBackground": false,
"colorPrefix": false,
"colorValue": true,
"colors": ["#d44a3a", "rgba(237, 129, 40, 0.89)", "#299c46"],
"datasource": "gdev-testdata",
"decimals": null,
"description": "",
"format": "ms",
"gauge": {
"maxValue": 100,
"minValue": 0,
"show": false,
"thresholdLabels": false,
"thresholdMarkers": true
},
"gridPos": {
"h": 7,
"w": 8,
"x": 8,
"y": 0
},
"id": 3,
"interval": null,
"links": [],
"mappingType": 1,
"mappingTypes": [
{
"name": "value to text",
"value": 1
},
{
"name": "range to text",
"value": 2
}
],
"maxDataPoints": 100,
"nullPointMode": "connected",
"nullText": null,
"postfix": "",
"postfixFontSize": "50%",
"prefix": "",
"prefixFontSize": "50%",
"rangeMaps": [
{
"from": "null",
"text": "N/A",
"to": "null"
}
],
"sparkline": {
"fillColor": "rgba(31, 118, 189, 0.18)",
"full": true,
"lineColor": "rgb(31, 120, 193)",
"show": true
},
"tableColumn": "",
"targets": [
{
"expr": "",
"format": "time_series",
"intervalFactor": 1,
"refId": "A",
"scenarioId": "csv_metric_values",
"stringInput": "1,2,3,4,5"
}
],
"thresholds": "5,10",
"title": "3 ms (red) + full height sparkline",
"type": "singlestat",
"valueFontSize": "200%",
"valueMaps": [
{
"op": "=",
"text": "N/A",
"value": "null"
}
],
"valueName": "avg"
},
{
"cacheTimeout": null,
"colorBackground": true,
"colorPrefix": false,
"colorValue": false,
"colors": ["#d44a3a", "rgba(237, 129, 40, 0.89)", "#299c46"],
"datasource": "gdev-testdata",
"decimals": null,
"description": "",
"format": "ms",
"gauge": {
"maxValue": 100,
"minValue": 0,
"show": false,
"thresholdLabels": false,
"thresholdMarkers": true
},
"gridPos": {
"h": 7,
"w": 8,
"x": 16,
"y": 0
},
"id": 4,
"interval": null,
"links": [],
"mappingType": 1,
"mappingTypes": [
{
"name": "value to text",
"value": 1
},
{
"name": "range to text",
"value": 2
}
],
"maxDataPoints": 100,
"nullPointMode": "connected",
"nullText": null,
"postfix": "",
"postfixFontSize": "50%",
"prefix": "",
"prefixFontSize": "50%",
"rangeMaps": [
{
"from": "null",
"text": "N/A",
"to": "null"
}
],
"sparkline": {
"fillColor": "rgba(31, 118, 189, 0.18)",
"full": true,
"lineColor": "rgb(31, 120, 193)",
"show": false
},
"tableColumn": "",
"targets": [
{
"expr": "",
"format": "time_series",
"intervalFactor": 1,
"refId": "A",
"scenarioId": "csv_metric_values",
"stringInput": "1,2,3,4,5"
}
],
"thresholds": "5,10",
"title": "3 ms + red background",
"type": "singlestat",
"valueFontSize": "200%",
"valueMaps": [
{
"op": "=",
"text": "N/A",
"value": "null"
}
],
"valueName": "avg"
},
{
"cacheTimeout": null,
"colorBackground": false,
"colorPrefix": false,
"colorValue": true,
"colors": ["#299c46", "rgba(237, 129, 40, 0.89)", "#d44a3a"],
"datasource": "gdev-testdata",
"decimals": null,
"description": "",
"format": "ms",
"gauge": {
"maxValue": 150,
"minValue": 0,
"show": true,
"thresholdLabels": true,
"thresholdMarkers": true
},
"gridPos": {
"h": 7,
"w": 8,
"x": 0,
"y": 7
},
"id": 5,
"interval": null,
"links": [],
"mappingType": 1,
"mappingTypes": [
{
"name": "value to text",
"value": 1
},
{
"name": "range to text",
"value": 2
}
],
"maxDataPoints": 100,
"nullPointMode": "connected",
"nullText": null,
"postfix": "",
"postfixFontSize": "50%",
"prefix": "",
"prefixFontSize": "50%",
"rangeMaps": [
{
"from": "null",
"text": "N/A",
"to": "null"
}
],
"sparkline": {
"fillColor": "rgba(31, 118, 189, 0.18)",
"full": true,
"lineColor": "rgb(31, 120, 193)",
"show": false
},
"tableColumn": "",
"targets": [
{
"expr": "",
"format": "time_series",
"intervalFactor": 1,
"refId": "A",
"scenarioId": "csv_metric_values",
"stringInput": "10,20,80"
}
],
"thresholds": "81,90",
"title": "80 ms green gauge, thresholds 81, 90",
"type": "singlestat",
"valueFontSize": "80%",
"valueMaps": [
{
"op": "=",
"text": "N/A",
"value": "null"
}
],
"valueName": "current"
},
{
"cacheTimeout": null,
"colorBackground": false,
"colorPrefix": false,
"colorValue": true,
"colors": ["#299c46", "rgba(237, 129, 40, 0.89)", "#d44a3a"],
"datasource": "gdev-testdata",
"decimals": null,
"description": "",
"format": "ms",
"gauge": {
"maxValue": 150,
"minValue": 0,
"show": true,
"thresholdLabels": false,
"thresholdMarkers": true
},
"gridPos": {
"h": 7,
"w": 8,
"x": 8,
"y": 7
},
"id": 6,
"interval": null,
"links": [],
"mappingType": 1,
"mappingTypes": [
{
"name": "value to text",
"value": 1
},
{
"name": "range to text",
"value": 2
}
],
"maxDataPoints": 100,
"nullPointMode": "connected",
"nullText": null,
"postfix": "",
"postfixFontSize": "50%",
"prefix": "",
"prefixFontSize": "50%",
"rangeMaps": [
{
"from": "null",
"text": "N/A",
"to": "null"
}
],
"sparkline": {
"fillColor": "rgba(31, 118, 189, 0.18)",
"full": true,
"lineColor": "rgb(31, 120, 193)",
"show": false
},
"tableColumn": "",
"targets": [
{
"expr": "",
"format": "time_series",
"intervalFactor": 1,
"refId": "A",
"scenarioId": "csv_metric_values",
"stringInput": "10,20,80"
}
],
"thresholds": "81,90",
"title": "80 ms green gauge, thresholds 81, 90, no labels",
"type": "singlestat",
"valueFontSize": "80%",
"valueMaps": [
{
"op": "=",
"text": "N/A",
"value": "null"
}
],
"valueName": "current"
},
{
"cacheTimeout": null,
"colorBackground": false,
"colorPrefix": false,
"colorValue": true,
"colors": ["#299c46", "rgba(237, 129, 40, 0.89)", "#d44a3a"],
"datasource": "gdev-testdata",
"decimals": null,
"description": "",
"format": "ms",
"gauge": {
"maxValue": 150,
"minValue": 0,
"show": true,
"thresholdLabels": false,
"thresholdMarkers": false
},
"gridPos": {
"h": 7,
"w": 8,
"x": 16,
"y": 7
},
"id": 7,
"interval": null,
"links": [],
"mappingType": 1,
"mappingTypes": [
{
"name": "value to text",
"value": 1
},
{
"name": "range to text",
"value": 2
}
],
"maxDataPoints": 100,
"nullPointMode": "connected",
"nullText": null,
"postfix": "",
"postfixFontSize": "50%",
"prefix": "",
"prefixFontSize": "50%",
"rangeMaps": [
{
"from": "null",
"text": "N/A",
"to": "null"
}
],
"sparkline": {
"fillColor": "rgba(31, 118, 189, 0.18)",
"full": true,
"lineColor": "rgb(31, 120, 193)",
"show": false
},
"tableColumn": "",
"targets": [
{
"expr": "",
"format": "time_series",
"intervalFactor": 1,
"refId": "A",
"scenarioId": "csv_metric_values",
"stringInput": "10,20,80"
}
],
"thresholds": "81,90",
"title": "80 ms green gauge, thresholds 81, 90, no markers or labels",
"type": "singlestat",
"valueFontSize": "80%",
"valueMaps": [
{
"op": "=",
"text": "N/A",
"value": "null"
}
],
"valueName": "current"
},
{
"cacheTimeout": null,
"colorBackground": false,
"colorPrefix": false,
"colorValue": false,
"colors": ["#299c46", "rgba(237, 129, 40, 0.89)", "#d44a3a"],
"datasource": "gdev-testdata",
"decimals": null,
"description": "",
"format": "none",
"gauge": {
"maxValue": 150,
"minValue": 0,
"show": false,
"thresholdLabels": false,
"thresholdMarkers": true
},
"gridPos": {
"h": 4,
"w": 8,
"x": 0,
"y": 14
},
"id": 8,
"interval": null,
"links": [],
"mappingType": 1,
"mappingTypes": [
{
"name": "value to text",
"value": 1
},
{
"name": "range to text",
"value": 2
}
],
"maxDataPoints": 100,
"nullPointMode": "connected",
"nullText": null,
"options": {},
"postfix": "",
"postfixFontSize": "50%",
"prefix": "",
"prefixFontSize": "50%",
"rangeMaps": [
{
"from": "null",
"text": "N/A",
"to": "null"
}
],
"sparkline": {
"fillColor": "rgba(31, 118, 189, 0.18)",
"full": true,
"lineColor": "rgb(31, 120, 193)",
"show": false
},
"tableColumn": "Info",
"targets": [
{
"alias": "",
"expr": "",
"format": "time_series",
"intervalFactor": 1,
"refId": "A",
"scenarioId": "random_walk_table",
"stringInput": ""
}
],
"thresholds": "81,90",
"title": "TableData 'Info' string Column",
"type": "singlestat",
"valueFontSize": "80%",
"valueMaps": [],
"valueName": "current"
},
{
"cacheTimeout": null,
"colorBackground": false,
"colorPrefix": false,
"colorValue": false,
"colors": ["#299c46", "rgba(237, 129, 40, 0.89)", "#d44a3a"],
"datasource": "gdev-testdata",
"decimals": 2,
"description": "",
"format": "celsius",
"gauge": {
"maxValue": 150,
"minValue": 0,
"show": false,
"thresholdLabels": false,
"thresholdMarkers": true
},
"gridPos": {
"h": 4,
"w": 8,
"x": 8,
"y": 14
},
"id": 9,
"interval": null,
"links": [],
"mappingType": 1,
"mappingTypes": [
{
"name": "value to text",
"value": 1
},
{
"name": "range to text",
"value": 2
}
],
"maxDataPoints": 100,
"nullPointMode": "connected",
"nullText": null,
"options": {},
"postfix": "",
"postfixFontSize": "50%",
"prefix": "",
"prefixFontSize": "50%",
"rangeMaps": [
{
"from": "null",
"text": "N/A",
"to": "null"
}
],
"sparkline": {
"fillColor": "rgba(31, 118, 189, 0.18)",
"full": true,
"lineColor": "rgb(31, 120, 193)",
"show": false
},
"tableColumn": "Min",
"targets": [
{
"alias": "",
"expr": "",
"format": "time_series",
"intervalFactor": 1,
"refId": "A",
"scenarioId": "random_walk_table",
"stringInput": ""
}
],
"thresholds": "81,90",
"title": "TableData 'Value' as temp Column",
"type": "singlestat",
"valueFontSize": "80%",
"valueMaps": [],
"valueName": "current"
},
{
"cacheTimeout": null,
"colorBackground": false,
"colorPrefix": false,
"colorValue": false,
"colors": ["#299c46", "rgba(237, 129, 40, 0.89)", "#d44a3a"],
"datasource": "gdev-testdata",
"decimals": null,
"description": "",
"format": "dateTimeFromNow",
"gauge": {
"maxValue": 150,
"minValue": 0,
"show": false,
"thresholdLabels": false,
"thresholdMarkers": true
},
"gridPos": {
"h": 4,
"w": 8,
"x": 16,
"y": 14
},
"id": 10,
"interval": null,
"links": [],
"mappingType": 1,
"mappingTypes": [
{
"name": "value to text",
"value": 1
},
{
"name": "range to text",
"value": 2
}
],
"maxDataPoints": 100,
"nullPointMode": "connected",
"nullText": null,
"options": {},
"postfix": "",
"postfixFontSize": "50%",
"prefix": "",
"prefixFontSize": "50%",
"rangeMaps": [
{
"from": "null",
"text": "N/A",
"to": "null"
}
],
"sparkline": {
"fillColor": "rgba(31, 118, 189, 0.18)",
"full": true,
"lineColor": "rgb(31, 120, 193)",
"show": false
},
"tableColumn": "time",
"targets": [
{
"alias": "",
"expr": "",
"format": "time_series",
"intervalFactor": 1,
"refId": "A",
"scenarioId": "random_walk",
"stringInput": ""
}
],
"thresholds": "81,90",
"title": "last_time display (a few seconds ago)",
"type": "singlestat",
"valueFontSize": "80%",
"valueMaps": [],
"valueName": "last_time"
}
],
"refresh": false,
"revision": 8,
"schemaVersion": 16,
"style": "dark",
"tags": ["gdev", "panel-tests"],
"templating": {
"list": []
},
"time": {
"from": "now-1h",
"to": "now"
},
"timepicker": {
"refresh_intervals": ["5s", "10s", "30s", "1m", "5m", "15m", "30m", "1h", "2h", "1d"],
"time_options": ["5m", "15m", "1h", "6h", "12h", "24h", "2d", "7d", "30d"]
},
"timezone": "browser",
"title": "Panel Tests - Singlestat",
"uid": "singlestat",
"version": 14
}
| devenv/dev-dashboards/panel-singlestat/singlestat_test.json | 0 | https://github.com/grafana/grafana/commit/6e80315531a0184b60021af3557a2b155a43b036 | [
0.00017846093396656215,
0.0001749587681842968,
0.00017264513007830828,
0.00017478916561231017,
0.000001216781015500601
] |
{
"id": 0,
"code_window": [
"import { DataSourceSettings, PluginType, PluginInclude, NavModel, NavModelItem } from '@grafana/data';\n",
"import config from 'app/core/config';\n",
"import { GenericDataSourcePlugin } from '../settings/PluginSettings';\n",
"\n",
"export function buildNavModel(dataSource: DataSourceSettings, plugin: GenericDataSourcePlugin): NavModelItem {\n",
" const pluginMeta = plugin.meta;\n",
"\n"
],
"labels": [
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { contextSrv } from 'app/core/core';\n",
"import { AccessControlAction } from 'app/types';\n"
],
"file_path": "public/app/features/datasources/state/navModel.ts",
"type": "add",
"edit_start_line_idx": 2
} | import { DataSourceSettings, PluginType, PluginInclude, NavModel, NavModelItem } from '@grafana/data';
import config from 'app/core/config';
import { GenericDataSourcePlugin } from '../settings/PluginSettings';
export function buildNavModel(dataSource: DataSourceSettings, plugin: GenericDataSourcePlugin): NavModelItem {
const pluginMeta = plugin.meta;
const navModel: NavModelItem = {
img: pluginMeta.info.logos.large,
id: 'datasource-' + dataSource.uid,
subTitle: `Type: ${pluginMeta.name}`,
url: '',
text: dataSource.name,
breadcrumbs: [{ title: 'Data Sources', url: 'datasources' }],
children: [
{
active: false,
icon: 'sliders-v-alt',
id: `datasource-settings-${dataSource.uid}`,
text: 'Settings',
url: `datasources/edit/${dataSource.uid}/`,
},
],
};
if (plugin.configPages) {
for (const page of plugin.configPages) {
navModel.children!.push({
active: false,
text: page.title,
icon: page.icon,
url: `datasources/edit/${dataSource.uid}/?page=${page.id}`,
id: `datasource-page-${page.id}`,
});
}
}
if (pluginMeta.includes && hasDashboards(pluginMeta.includes)) {
navModel.children!.push({
active: false,
icon: 'apps',
id: `datasource-dashboards-${dataSource.uid}`,
text: 'Dashboards',
url: `datasources/edit/${dataSource.uid}/dashboards`,
});
}
if (config.licenseInfo.hasLicense) {
navModel.children!.push({
active: false,
icon: 'lock',
id: `datasource-permissions-${dataSource.id}`,
text: 'Permissions',
url: `datasources/edit/${dataSource.id}/permissions`,
});
navModel.children!.push({
active: false,
icon: 'info-circle',
id: `datasource-insights-${dataSource.id}`,
text: 'Insights',
url: `datasources/edit/${dataSource.id}/insights`,
});
navModel.children!.push({
active: false,
icon: 'database',
id: `datasource-cache-${dataSource.id}`,
text: 'Cache',
url: `datasources/edit/${dataSource.id}/cache`,
hideFromTabs: !pluginMeta.isBackend || !config.caching.enabled,
});
}
return navModel;
}
export function getDataSourceNav(main: NavModelItem, pageName: string): NavModel {
let node: NavModelItem;
// find active page
for (const child of main.children!) {
if (child.id!.indexOf(pageName) > 0) {
child.active = true;
node = child;
break;
}
}
return {
main: main,
node: node!,
};
}
export function getDataSourceLoadingNav(pageName: string): NavModel {
const main = buildNavModel(
{
access: '',
basicAuth: false,
basicAuthUser: '',
basicAuthPassword: '',
withCredentials: false,
database: '',
id: 1,
uid: 'x',
isDefault: false,
jsonData: { authType: 'credentials', defaultRegion: 'eu-west-2' },
name: 'Loading',
orgId: 1,
password: '',
readOnly: false,
type: 'Loading',
typeName: 'Loading',
typeLogoUrl: 'public/img/icn-datasource.svg',
url: '',
user: '',
secureJsonFields: {},
},
{
meta: {
id: '1',
type: PluginType.datasource,
name: '',
info: {
author: {
name: '',
url: '',
},
description: '',
links: [{ name: '', url: '' }],
logos: {
large: '',
small: '',
},
screenshots: [],
updated: '',
version: '',
},
includes: [],
module: '',
baseUrl: '',
},
} as any
);
return getDataSourceNav(main, pageName);
}
function hasDashboards(includes: PluginInclude[]): boolean {
return (
includes.find((include) => {
return include.type === 'dashboard';
}) !== undefined
);
}
| public/app/features/datasources/state/navModel.ts | 1 | https://github.com/grafana/grafana/commit/cf7034ee50569ee6b68f4f8ca47bbfd03b2af224 | [
0.9991505146026611,
0.25004997849464417,
0.00016840366879478097,
0.00026699641603045166,
0.43114301562309265
] |
{
"id": 0,
"code_window": [
"import { DataSourceSettings, PluginType, PluginInclude, NavModel, NavModelItem } from '@grafana/data';\n",
"import config from 'app/core/config';\n",
"import { GenericDataSourcePlugin } from '../settings/PluginSettings';\n",
"\n",
"export function buildNavModel(dataSource: DataSourceSettings, plugin: GenericDataSourcePlugin): NavModelItem {\n",
" const pluginMeta = plugin.meta;\n",
"\n"
],
"labels": [
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { contextSrv } from 'app/core/core';\n",
"import { AccessControlAction } from 'app/types';\n"
],
"file_path": "public/app/features/datasources/state/navModel.ts",
"type": "add",
"edit_start_line_idx": 2
} | import { DataFrame, NodeGraphDataFrameFieldNames as Fields } from '@grafana/data';
import { ZipkinSpan } from '../types';
import { getNonOverlappingDuration, getStats, makeFrames, makeSpanMap } from '../../../../core/utils/tracing';
interface Node {
[Fields.id]: string;
[Fields.title]: string;
[Fields.subTitle]: string;
[Fields.mainStat]: string;
[Fields.secondaryStat]: string;
[Fields.color]: number;
}
interface Edge {
[Fields.id]: string;
[Fields.target]: string;
[Fields.source]: string;
}
export function createGraphFrames(data: ZipkinSpan[]): DataFrame[] {
const { nodes, edges } = convertTraceToGraph(data);
const [nodesFrame, edgesFrame] = makeFrames();
for (const node of nodes) {
nodesFrame.add(node);
}
for (const edge of edges) {
edgesFrame.add(edge);
}
return [nodesFrame, edgesFrame];
}
function convertTraceToGraph(spans: ZipkinSpan[]): { nodes: Node[]; edges: Edge[] } {
const nodes: Node[] = [];
const edges: Edge[] = [];
const traceDuration = findTraceDuration(spans);
const spanMap = makeSpanMap((index) => {
if (index >= spans.length) {
return undefined;
}
return {
span: spans[index],
id: spans[index].id,
parentIds: spans[index].parentId ? [spans[index].parentId!] : [],
};
});
for (const span of spans) {
const ranges: Array<[number, number]> = spanMap[span.id].children.map((c) => {
const span = spanMap[c].span;
return [span.timestamp, span.timestamp + span.duration];
});
const childrenDuration = getNonOverlappingDuration(ranges);
const selfDuration = span.duration - childrenDuration;
const stats = getStats(span.duration / 1000, traceDuration / 1000, selfDuration / 1000);
nodes.push({
[Fields.id]: span.id,
[Fields.title]: span.localEndpoint?.serviceName || span.remoteEndpoint?.serviceName || 'unknown',
[Fields.subTitle]: span.name,
[Fields.mainStat]: stats.main,
[Fields.secondaryStat]: stats.secondary,
[Fields.color]: selfDuration / traceDuration,
});
if (span.parentId && spanMap[span.parentId].span) {
edges.push({
[Fields.id]: span.parentId + '--' + span.id,
[Fields.target]: span.id,
[Fields.source]: span.parentId,
});
}
}
return { nodes, edges };
}
/**
* Get the duration of the whole trace as it isn't a part of the response data.
* Note: Seems like this should be the same as just longest span, but this is probably safer.
*/
function findTraceDuration(spans: ZipkinSpan[]): number {
let traceEndTime = 0;
let traceStartTime = Infinity;
for (const span of spans) {
if (span.timestamp < traceStartTime) {
traceStartTime = span.timestamp;
}
if (span.timestamp + span.duration > traceEndTime) {
traceEndTime = span.timestamp + span.duration;
}
}
return traceEndTime - traceStartTime;
}
| public/app/plugins/datasource/zipkin/utils/graphTransform.ts | 0 | https://github.com/grafana/grafana/commit/cf7034ee50569ee6b68f4f8ca47bbfd03b2af224 | [
0.00017991472850553691,
0.00017569442570675164,
0.00016822842007968575,
0.00017601207946427166,
0.000003272342610216583
] |
{
"id": 0,
"code_window": [
"import { DataSourceSettings, PluginType, PluginInclude, NavModel, NavModelItem } from '@grafana/data';\n",
"import config from 'app/core/config';\n",
"import { GenericDataSourcePlugin } from '../settings/PluginSettings';\n",
"\n",
"export function buildNavModel(dataSource: DataSourceSettings, plugin: GenericDataSourcePlugin): NavModelItem {\n",
" const pluginMeta = plugin.meta;\n",
"\n"
],
"labels": [
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { contextSrv } from 'app/core/core';\n",
"import { AccessControlAction } from 'app/types';\n"
],
"file_path": "public/app/features/datasources/state/navModel.ts",
"type": "add",
"edit_start_line_idx": 2
} | package social
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"strings"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/util/errutil"
"github.com/jmespath/go-jmespath"
)
var (
errMissingGroupMembership = Error{"user not a member of one of the required groups"}
)
type httpGetResponse struct {
Body []byte
Headers http.Header
}
func (s *SocialBase) IsEmailAllowed(email string) bool {
return isEmailAllowed(email, s.allowedDomains)
}
func (s *SocialBase) IsSignupAllowed() bool {
return s.allowSignup
}
func isEmailAllowed(email string, allowedDomains []string) bool {
if len(allowedDomains) == 0 {
return true
}
valid := false
for _, domain := range allowedDomains {
emailSuffix := fmt.Sprintf("@%s", domain)
valid = valid || strings.HasSuffix(email, emailSuffix)
}
return valid
}
func (s *SocialBase) httpGet(client *http.Client, url string) (response httpGetResponse, err error) {
r, err := client.Get(url)
if err != nil {
return
}
defer func() {
if err := r.Body.Close(); err != nil {
s.log.Warn("Failed to close response body", "err", err)
}
}()
body, err := ioutil.ReadAll(r.Body)
if err != nil {
return
}
response = httpGetResponse{body, r.Header}
if r.StatusCode >= 300 {
err = fmt.Errorf(string(response.Body))
return
}
log.Tracef("HTTP GET %s: %s %s", url, r.Status, string(response.Body))
err = nil
return
}
func (s *SocialBase) searchJSONForAttr(attributePath string, data []byte) (interface{}, error) {
if attributePath == "" {
return "", errors.New("no attribute path specified")
}
if len(data) == 0 {
return "", errors.New("empty user info JSON response provided")
}
var buf interface{}
if err := json.Unmarshal(data, &buf); err != nil {
return "", errutil.Wrap("failed to unmarshal user info JSON response", err)
}
val, err := jmespath.Search(attributePath, buf)
if err != nil {
return "", errutil.Wrapf(err, "failed to search user info JSON response with provided path: %q", attributePath)
}
return val, nil
}
func (s *SocialBase) searchJSONForStringAttr(attributePath string, data []byte) (string, error) {
val, err := s.searchJSONForAttr(attributePath, data)
if err != nil {
return "", err
}
strVal, ok := val.(string)
if ok {
return strVal, nil
}
return "", nil
}
func (s *SocialBase) searchJSONForStringArrayAttr(attributePath string, data []byte) ([]string, error) {
val, err := s.searchJSONForAttr(attributePath, data)
if err != nil {
return []string{}, err
}
ifArr, ok := val.([]interface{})
if !ok {
return []string{}, nil
}
result := []string{}
for _, v := range ifArr {
if strVal, ok := v.(string); ok {
result = append(result, strVal)
}
}
return result, nil
}
| pkg/login/social/common.go | 0 | https://github.com/grafana/grafana/commit/cf7034ee50569ee6b68f4f8ca47bbfd03b2af224 | [
0.00017688050866127014,
0.00017264251073356718,
0.0001674763479968533,
0.00017314363503828645,
0.0000025875287974486127
] |
{
"id": 0,
"code_window": [
"import { DataSourceSettings, PluginType, PluginInclude, NavModel, NavModelItem } from '@grafana/data';\n",
"import config from 'app/core/config';\n",
"import { GenericDataSourcePlugin } from '../settings/PluginSettings';\n",
"\n",
"export function buildNavModel(dataSource: DataSourceSettings, plugin: GenericDataSourcePlugin): NavModelItem {\n",
" const pluginMeta = plugin.meta;\n",
"\n"
],
"labels": [
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { contextSrv } from 'app/core/core';\n",
"import { AccessControlAction } from 'app/types';\n"
],
"file_path": "public/app/features/datasources/state/navModel.ts",
"type": "add",
"edit_start_line_idx": 2
} | package azuremonitor
import (
"testing"
. "github.com/smartystreets/goconvey/convey"
)
func TestURLBuilder(t *testing.T) {
Convey("AzureMonitor URL Builder", t, func() {
Convey("when metric definition is in the short form", func() {
ub := &urlBuilder{
DefaultSubscription: "default-sub",
ResourceGroup: "rg",
MetricDefinition: "Microsoft.Compute/virtualMachines",
ResourceName: "rn",
}
url := ub.Build()
So(url, ShouldEqual, "default-sub/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/rn/providers/microsoft.insights/metrics")
})
Convey("when metric definition is in the short form and a subscription is defined", func() {
ub := &urlBuilder{
DefaultSubscription: "default-sub",
Subscription: "specified-sub",
ResourceGroup: "rg",
MetricDefinition: "Microsoft.Compute/virtualMachines",
ResourceName: "rn",
}
url := ub.Build()
So(url, ShouldEqual, "specified-sub/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/rn/providers/microsoft.insights/metrics")
})
Convey("when metric definition is Microsoft.Storage/storageAccounts/blobServices", func() {
ub := &urlBuilder{
DefaultSubscription: "default-sub",
ResourceGroup: "rg",
MetricDefinition: "Microsoft.Storage/storageAccounts/blobServices",
ResourceName: "rn1/default",
}
url := ub.Build()
So(url, ShouldEqual, "default-sub/resourceGroups/rg/providers/Microsoft.Storage/storageAccounts/rn1/blobServices/default/providers/microsoft.insights/metrics")
})
Convey("when metric definition is Microsoft.Storage/storageAccounts/fileServices", func() {
ub := &urlBuilder{
DefaultSubscription: "default-sub",
ResourceGroup: "rg",
MetricDefinition: "Microsoft.Storage/storageAccounts/fileServices",
ResourceName: "rn1/default",
}
url := ub.Build()
So(url, ShouldEqual, "default-sub/resourceGroups/rg/providers/Microsoft.Storage/storageAccounts/rn1/fileServices/default/providers/microsoft.insights/metrics")
})
Convey("when metric definition is Microsoft.NetApp/netAppAccounts/capacityPools/volumes", func() {
ub := &urlBuilder{
DefaultSubscription: "default-sub",
ResourceGroup: "rg",
MetricDefinition: "Microsoft.NetApp/netAppAccounts/capacityPools/volumes",
ResourceName: "rn1/rn2/rn3",
}
url := ub.Build()
So(url, ShouldEqual, "default-sub/resourceGroups/rg/providers/Microsoft.NetApp/netAppAccounts/rn1/capacityPools/rn2/volumes/rn3/providers/microsoft.insights/metrics")
})
})
}
| pkg/tsdb/azuremonitor/url-builder_test.go | 0 | https://github.com/grafana/grafana/commit/cf7034ee50569ee6b68f4f8ca47bbfd03b2af224 | [
0.0001770691596902907,
0.00017525165458209813,
0.0001731883967295289,
0.00017557921819388866,
0.0000012064100474162842
] |
{
"id": 1,
"code_window": [
" url: `datasources/edit/${dataSource.uid}/dashboards`,\n",
" });\n",
" }\n",
"\n",
" if (config.licenseInfo.hasLicense) {\n",
" navModel.children!.push({\n",
" active: false,\n",
" icon: 'lock',\n",
" id: `datasource-permissions-${dataSource.id}`,\n",
" text: 'Permissions',\n",
" url: `datasources/edit/${dataSource.id}/permissions`,\n",
" });\n",
"\n",
" navModel.children!.push({\n",
" active: false,\n",
" icon: 'info-circle',\n",
" id: `datasource-insights-${dataSource.id}`,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (contextSrv.hasPermission(AccessControlAction.DataSourcesPermissionsRead)) {\n",
" navModel.children!.push({\n",
" active: false,\n",
" icon: 'lock',\n",
" id: `datasource-permissions-${dataSource.id}`,\n",
" text: 'Permissions',\n",
" url: `datasources/edit/${dataSource.id}/permissions`,\n",
" });\n",
" }\n"
],
"file_path": "public/app/features/datasources/state/navModel.ts",
"type": "replace",
"edit_start_line_idx": 48
} | import { DataSourceSettings, PluginType, PluginInclude, NavModel, NavModelItem } from '@grafana/data';
import config from 'app/core/config';
import { GenericDataSourcePlugin } from '../settings/PluginSettings';
export function buildNavModel(dataSource: DataSourceSettings, plugin: GenericDataSourcePlugin): NavModelItem {
const pluginMeta = plugin.meta;
const navModel: NavModelItem = {
img: pluginMeta.info.logos.large,
id: 'datasource-' + dataSource.uid,
subTitle: `Type: ${pluginMeta.name}`,
url: '',
text: dataSource.name,
breadcrumbs: [{ title: 'Data Sources', url: 'datasources' }],
children: [
{
active: false,
icon: 'sliders-v-alt',
id: `datasource-settings-${dataSource.uid}`,
text: 'Settings',
url: `datasources/edit/${dataSource.uid}/`,
},
],
};
if (plugin.configPages) {
for (const page of plugin.configPages) {
navModel.children!.push({
active: false,
text: page.title,
icon: page.icon,
url: `datasources/edit/${dataSource.uid}/?page=${page.id}`,
id: `datasource-page-${page.id}`,
});
}
}
if (pluginMeta.includes && hasDashboards(pluginMeta.includes)) {
navModel.children!.push({
active: false,
icon: 'apps',
id: `datasource-dashboards-${dataSource.uid}`,
text: 'Dashboards',
url: `datasources/edit/${dataSource.uid}/dashboards`,
});
}
if (config.licenseInfo.hasLicense) {
navModel.children!.push({
active: false,
icon: 'lock',
id: `datasource-permissions-${dataSource.id}`,
text: 'Permissions',
url: `datasources/edit/${dataSource.id}/permissions`,
});
navModel.children!.push({
active: false,
icon: 'info-circle',
id: `datasource-insights-${dataSource.id}`,
text: 'Insights',
url: `datasources/edit/${dataSource.id}/insights`,
});
navModel.children!.push({
active: false,
icon: 'database',
id: `datasource-cache-${dataSource.id}`,
text: 'Cache',
url: `datasources/edit/${dataSource.id}/cache`,
hideFromTabs: !pluginMeta.isBackend || !config.caching.enabled,
});
}
return navModel;
}
export function getDataSourceNav(main: NavModelItem, pageName: string): NavModel {
let node: NavModelItem;
// find active page
for (const child of main.children!) {
if (child.id!.indexOf(pageName) > 0) {
child.active = true;
node = child;
break;
}
}
return {
main: main,
node: node!,
};
}
export function getDataSourceLoadingNav(pageName: string): NavModel {
const main = buildNavModel(
{
access: '',
basicAuth: false,
basicAuthUser: '',
basicAuthPassword: '',
withCredentials: false,
database: '',
id: 1,
uid: 'x',
isDefault: false,
jsonData: { authType: 'credentials', defaultRegion: 'eu-west-2' },
name: 'Loading',
orgId: 1,
password: '',
readOnly: false,
type: 'Loading',
typeName: 'Loading',
typeLogoUrl: 'public/img/icn-datasource.svg',
url: '',
user: '',
secureJsonFields: {},
},
{
meta: {
id: '1',
type: PluginType.datasource,
name: '',
info: {
author: {
name: '',
url: '',
},
description: '',
links: [{ name: '', url: '' }],
logos: {
large: '',
small: '',
},
screenshots: [],
updated: '',
version: '',
},
includes: [],
module: '',
baseUrl: '',
},
} as any
);
return getDataSourceNav(main, pageName);
}
function hasDashboards(includes: PluginInclude[]): boolean {
return (
includes.find((include) => {
return include.type === 'dashboard';
}) !== undefined
);
}
| public/app/features/datasources/state/navModel.ts | 1 | https://github.com/grafana/grafana/commit/cf7034ee50569ee6b68f4f8ca47bbfd03b2af224 | [
0.9472187161445618,
0.1044934093952179,
0.00016824832709971815,
0.0013225595466792583,
0.274246484041214
] |
{
"id": 1,
"code_window": [
" url: `datasources/edit/${dataSource.uid}/dashboards`,\n",
" });\n",
" }\n",
"\n",
" if (config.licenseInfo.hasLicense) {\n",
" navModel.children!.push({\n",
" active: false,\n",
" icon: 'lock',\n",
" id: `datasource-permissions-${dataSource.id}`,\n",
" text: 'Permissions',\n",
" url: `datasources/edit/${dataSource.id}/permissions`,\n",
" });\n",
"\n",
" navModel.children!.push({\n",
" active: false,\n",
" icon: 'info-circle',\n",
" id: `datasource-insights-${dataSource.id}`,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (contextSrv.hasPermission(AccessControlAction.DataSourcesPermissionsRead)) {\n",
" navModel.children!.push({\n",
" active: false,\n",
" icon: 'lock',\n",
" id: `datasource-permissions-${dataSource.id}`,\n",
" text: 'Permissions',\n",
" url: `datasources/edit/${dataSource.id}/permissions`,\n",
" });\n",
" }\n"
],
"file_path": "public/app/features/datasources/state/navModel.ts",
"type": "replace",
"edit_start_line_idx": 48
} | <source>
@type forward
port 24224
bind 0.0.0.0
</source>
<filter grafana>
@type parser
<parse>
@type json
json_parser json
</parse>
replace_invalid_sequence true
emit_invalid_record_to_error false
key_name log
reserve_data true
remove_key_name_field true
</filter>
<filter nginx>
@type parser
format /^.*m(?<host>[^ ]*) (?<remote>[^ ]*) \- \- \[(?<time>[^\]]*)\] \"(?<method>\S+)(?: +(?<path>[^\"]*) +\S*)?\" (?<code>[^ ]*) (?<size>[^ ]*)(?: \"(?<referer>[^\"]*)\" \"(?<agent>[^\"]*)\")?$/
time_format %d/%b/%Y:%H:%M:%S %z
key_name log
reserve_data true
remove_key_name_field true
</filter>
<filter **>
@type record_transformer
remove_keys "source,t"
</filter>
<match grafana>
@type copy
<store>
@type stdout
output_type json
</store>
<store>
@type loki
url "http://loki:3100"
extra_labels {"app":"grafana"}
label_keys "container_name,container_id,logger"
flush_interval 10s
flush_at_shutdown true
buffer_chunk_limit 1m
</store>
</match>
<filter nginx>
@type record_transformer
<record>
lvl "info"
</record>
</filter>
<match nginx>
@type copy
<store>
@type stdout
output_type json
</store>
<store>
@type loki
url "http://loki:3100"
extra_labels {"app":"nginx"}
label_keys "container_name,container_id"
flush_interval 10s
flush_at_shutdown true
buffer_chunk_limit 1m
</store>
</match> | devenv/docker/ha_test/fluentd/fluentd.conf | 0 | https://github.com/grafana/grafana/commit/cf7034ee50569ee6b68f4f8ca47bbfd03b2af224 | [
0.0001774799166014418,
0.0001736392150633037,
0.0001704933965811506,
0.00017309522081632167,
0.0000021562009351328015
] |
{
"id": 1,
"code_window": [
" url: `datasources/edit/${dataSource.uid}/dashboards`,\n",
" });\n",
" }\n",
"\n",
" if (config.licenseInfo.hasLicense) {\n",
" navModel.children!.push({\n",
" active: false,\n",
" icon: 'lock',\n",
" id: `datasource-permissions-${dataSource.id}`,\n",
" text: 'Permissions',\n",
" url: `datasources/edit/${dataSource.id}/permissions`,\n",
" });\n",
"\n",
" navModel.children!.push({\n",
" active: false,\n",
" icon: 'info-circle',\n",
" id: `datasource-insights-${dataSource.id}`,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (contextSrv.hasPermission(AccessControlAction.DataSourcesPermissionsRead)) {\n",
" navModel.children!.push({\n",
" active: false,\n",
" icon: 'lock',\n",
" id: `datasource-permissions-${dataSource.id}`,\n",
" text: 'Permissions',\n",
" url: `datasources/edit/${dataSource.id}/permissions`,\n",
" });\n",
" }\n"
],
"file_path": "public/app/features/datasources/state/navModel.ts",
"type": "replace",
"edit_start_line_idx": 48
} | # Should not be included
apiVersion: 1
#datasources:
# - name: name
# type: type
# access: proxy
# orgId: 2
# url: url
# password: password
# user: user
# database: database
# basicAuth: true
# basicAuthUser: basic_auth_user
# basicAuthPassword: basic_auth_password
# withCredentials: true
# jsonData:
# graphiteVersion: "1.1"
# tlsAuth: true
# tlsAuthWithCACert: true
# secureJsonData:
# tlsCACert: "MjNOcW9RdkbUDHZmpco2HCYzVq9dE+i6Yi+gmUJotq5CDA=="
# tlsClientCert: "ckN0dGlyMXN503YNfjTcf9CV+GGQneN+xmAclQ=="
# tlsClientKey: "ZkN4aG1aNkja/gKAB1wlnKFIsy2SRDq4slrM0A=="
# editable: true
# version: 10
#
#deleteDatasources:
# - name: old-graphite3
# orgId: 2
| pkg/services/provisioning/datasources/testdata/all-properties/sample.yaml | 0 | https://github.com/grafana/grafana/commit/cf7034ee50569ee6b68f4f8ca47bbfd03b2af224 | [
0.0001949056750163436,
0.00017977389506995678,
0.0001692935184109956,
0.00017744817887432873,
0.000010252431820845231
] |
{
"id": 1,
"code_window": [
" url: `datasources/edit/${dataSource.uid}/dashboards`,\n",
" });\n",
" }\n",
"\n",
" if (config.licenseInfo.hasLicense) {\n",
" navModel.children!.push({\n",
" active: false,\n",
" icon: 'lock',\n",
" id: `datasource-permissions-${dataSource.id}`,\n",
" text: 'Permissions',\n",
" url: `datasources/edit/${dataSource.id}/permissions`,\n",
" });\n",
"\n",
" navModel.children!.push({\n",
" active: false,\n",
" icon: 'info-circle',\n",
" id: `datasource-insights-${dataSource.id}`,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (contextSrv.hasPermission(AccessControlAction.DataSourcesPermissionsRead)) {\n",
" navModel.children!.push({\n",
" active: false,\n",
" icon: 'lock',\n",
" id: `datasource-permissions-${dataSource.id}`,\n",
" text: 'Permissions',\n",
" url: `datasources/edit/${dataSource.id}/permissions`,\n",
" });\n",
" }\n"
],
"file_path": "public/app/features/datasources/state/navModel.ts",
"type": "replace",
"edit_start_line_idx": 48
} | import { DashboardModel } from '../../state/DashboardModel';
import { PanelModel } from '../../state/PanelModel';
import { setContextSrv } from '../../../../core/services/context_srv';
import { hasChanges, ignoreChanges } from './DashboardPrompt';
function getDefaultDashboardModel(): DashboardModel {
return new DashboardModel({
refresh: false,
panels: [
{
id: 1,
type: 'graph',
gridPos: { x: 0, y: 0, w: 24, h: 6 },
legend: { sortDesc: false },
},
{
id: 2,
type: 'row',
gridPos: { x: 0, y: 6, w: 24, h: 2 },
collapsed: true,
panels: [
{ id: 3, type: 'graph', gridPos: { x: 0, y: 6, w: 12, h: 2 } },
{ id: 4, type: 'graph', gridPos: { x: 12, y: 6, w: 12, h: 2 } },
],
},
{ id: 5, type: 'row', gridPos: { x: 0, y: 6, w: 1, h: 1 } },
],
});
}
function getTestContext() {
const contextSrv: any = { isSignedIn: true, isEditor: true };
setContextSrv(contextSrv);
const dash: any = getDefaultDashboardModel();
const original: any = dash.getSaveModelClone();
return { dash, original, contextSrv };
}
describe('DashboardPrompt', () => {
it('No changes should not have changes', () => {
const { original, dash } = getTestContext();
expect(hasChanges(dash, original)).toBe(false);
});
it('Simple change should be registered', () => {
const { original, dash } = getTestContext();
dash.title = 'google';
expect(hasChanges(dash, original)).toBe(true);
});
it('Should ignore a lot of changes', () => {
const { original, dash } = getTestContext();
dash.time = { from: '1h' };
dash.refresh = true;
dash.schemaVersion = 10;
expect(hasChanges(dash, original)).toBe(false);
});
it('Should ignore .iteration changes', () => {
const { original, dash } = getTestContext();
dash.iteration = new Date().getTime() + 1;
expect(hasChanges(dash, original)).toBe(false);
});
it('Should ignore row collapse change', () => {
const { original, dash } = getTestContext();
dash.toggleRow(dash.panels[1]);
expect(hasChanges(dash, original)).toBe(false);
});
it('Should ignore panel legend changes', () => {
const { original, dash } = getTestContext();
dash.panels[0].legend.sortDesc = true;
dash.panels[0].legend.sort = 'avg';
expect(hasChanges(dash, original)).toBe(false);
});
it('Should ignore panel repeats', () => {
const { original, dash } = getTestContext();
dash.panels.push(new PanelModel({ repeatPanelId: 10 }));
expect(hasChanges(dash, original)).toBe(false);
});
describe('ignoreChanges', () => {
describe('when called without original dashboard', () => {
it('then it should return true', () => {
const { dash } = getTestContext();
expect(ignoreChanges(dash, null)).toBe(true);
});
});
describe('when called without current dashboard', () => {
it('then it should return true', () => {
const { original } = getTestContext();
expect(ignoreChanges((null as unknown) as DashboardModel, original)).toBe(true);
});
});
describe('when called without meta in current dashboard', () => {
it('then it should return true', () => {
const { original, dash } = getTestContext();
expect(ignoreChanges({ ...dash, meta: undefined }, original)).toBe(true);
});
});
describe('when called for a viewer without save permissions', () => {
it('then it should return true', () => {
const { original, dash, contextSrv } = getTestContext();
contextSrv.isEditor = false;
expect(ignoreChanges({ ...dash, meta: { canSave: false } }, original)).toBe(true);
});
});
describe('when called for a viewer with save permissions', () => {
it('then it should return undefined', () => {
const { original, dash, contextSrv } = getTestContext();
contextSrv.isEditor = false;
expect(ignoreChanges({ ...dash, meta: { canSave: true } }, original)).toBe(undefined);
});
});
describe('when called for an user that is not signed in', () => {
it('then it should return true', () => {
const { original, dash, contextSrv } = getTestContext();
contextSrv.isSignedIn = false;
expect(ignoreChanges({ ...dash, meta: { canSave: true } }, original)).toBe(true);
});
});
describe('when called with fromScript', () => {
it('then it should return true', () => {
const { original, dash } = getTestContext();
expect(
ignoreChanges({ ...dash, meta: { canSave: true, fromScript: true, fromFile: undefined } }, original)
).toBe(true);
});
});
describe('when called with fromFile', () => {
it('then it should return true', () => {
const { original, dash } = getTestContext();
expect(
ignoreChanges({ ...dash, meta: { canSave: true, fromScript: undefined, fromFile: true } }, original)
).toBe(true);
});
});
describe('when called with canSave but without fromScript and fromFile', () => {
it('then it should return false', () => {
const { original, dash } = getTestContext();
expect(
ignoreChanges({ ...dash, meta: { canSave: true, fromScript: undefined, fromFile: undefined } }, original)
).toBe(undefined);
});
});
});
});
| public/app/features/dashboard/components/DashboardPrompt/DashboardPrompt.test.tsx | 0 | https://github.com/grafana/grafana/commit/cf7034ee50569ee6b68f4f8ca47bbfd03b2af224 | [
0.0001791235845303163,
0.00017408482381142676,
0.00016604430857114494,
0.00017524806025903672,
0.000003573751428120886
] |
{
"id": 2,
"code_window": [
" DataSourcesExplore = 'datasources:explore',\n",
" DataSourcesRead = 'datasources:read',\n",
" DataSourcesCreate = 'datasources:create',\n",
" DataSourcesWrite = 'datasources:write',\n",
" DataSourcesDelete = 'datasources:delete',\n",
"\n",
" ActionServerStatsRead = 'server.stats:read',\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" DataSourcesPermissionsRead = 'datasources.permissions:read',\n"
],
"file_path": "public/app/types/accessControl.ts",
"type": "add",
"edit_start_line_idx": 41
} | /**
* UserPermission is a map storing permissions in a form of
* {
* action: { scope: scope }
* }
*/
export type UserPermission = {
[key: string]: { [key: string]: string };
};
// Permission actions
export enum AccessControlAction {
UsersRead = 'users:read',
UsersWrite = 'users:write',
UsersTeamRead = 'users.teams:read',
UsersAuthTokenList = 'users.authtoken:list',
UsersAuthTokenUpdate = 'users.authtoken:update',
UsersPasswordUpdate = 'users.password:update',
UsersDelete = 'users:delete',
UsersCreate = 'users:create',
UsersEnable = 'users:enable',
UsersDisable = 'users:disable',
UsersPermissionsUpdate = 'users.permissions:update',
UsersLogout = 'users:logout',
UsersQuotasList = 'users.quotas:list',
UsersQuotasUpdate = 'users.quotas:update',
OrgUsersRead = 'org.users:read',
OrgUsersAdd = 'org.users:add',
OrgUsersRemove = 'org.users:remove',
OrgUsersRoleUpdate = 'org.users.role:update',
LDAPUsersRead = 'ldap.user:read',
LDAPUsersSync = 'ldap.user:sync',
LDAPStatusRead = 'ldap.status:read',
DataSourcesExplore = 'datasources:explore',
DataSourcesRead = 'datasources:read',
DataSourcesCreate = 'datasources:create',
DataSourcesWrite = 'datasources:write',
DataSourcesDelete = 'datasources:delete',
ActionServerStatsRead = 'server.stats:read',
}
| public/app/types/accessControl.ts | 1 | https://github.com/grafana/grafana/commit/cf7034ee50569ee6b68f4f8ca47bbfd03b2af224 | [
0.9976844787597656,
0.20394611358642578,
0.00017299891624134034,
0.00034699845127761364,
0.3969534635543823
] |
{
"id": 2,
"code_window": [
" DataSourcesExplore = 'datasources:explore',\n",
" DataSourcesRead = 'datasources:read',\n",
" DataSourcesCreate = 'datasources:create',\n",
" DataSourcesWrite = 'datasources:write',\n",
" DataSourcesDelete = 'datasources:delete',\n",
"\n",
" ActionServerStatsRead = 'server.stats:read',\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" DataSourcesPermissionsRead = 'datasources.permissions:read',\n"
],
"file_path": "public/app/types/accessControl.ts",
"type": "add",
"edit_start_line_idx": 41
} | #!/bin/bash
set -e
WORKING_DIRECTORY=$(pwd)
DIST_DIRECTORY="$WORKING_DIRECTORY/enterprise-dist"
# copy zip file to /tmp/dist
mkdir -p /tmp/dist
cp ./enterprise-dist/*.zip /tmp/dist
echo "Contents of /tmp/dist"
ls -al /tmp/dist
# nssm download has been unreliable, use a cached copy of it
echo "Caching NSSM"
mkdir -p /tmp/cache
cp ./scripts/build/ci-msi-build/msigenerator/cache/nssm-2.24.zip /tmp/cache
cd ./scripts/build/ci-msi-build/msigenerator
echo "Building MSI"
python3 generator/build.py "$@"
chmod a+x /tmp/scratch/*.msi
echo "MSI: Copy to $DIST_DIRECTORY"
cp /tmp/scratch/*.msi "$DIST_DIRECTORY"
echo "MSI: Generate SHA256"
MSI_FILE=$(ls "${DIST_DIRECTORY}"/*.msi)
SHA256SUM=$(sha256sum "$MSI_FILE" | cut -f1 -d' ')
echo "$SHA256SUM" > "$MSI_FILE.sha256"
echo "MSI: SHA256 file content:"
cat "$MSI_FILE.sha256"
echo "MSI: contents of $DIST_DIRECTORY"
ls -al "$DIST_DIRECTORY"
| scripts/build/ci-msi-build/ci-msi-build-ee.sh | 0 | https://github.com/grafana/grafana/commit/cf7034ee50569ee6b68f4f8ca47bbfd03b2af224 | [
0.0001702794397715479,
0.00016995974874589592,
0.00016965986287686974,
0.00016993995814118534,
2.533282099648204e-7
] |
{
"id": 2,
"code_window": [
" DataSourcesExplore = 'datasources:explore',\n",
" DataSourcesRead = 'datasources:read',\n",
" DataSourcesCreate = 'datasources:create',\n",
" DataSourcesWrite = 'datasources:write',\n",
" DataSourcesDelete = 'datasources:delete',\n",
"\n",
" ActionServerStatsRead = 'server.stats:read',\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" DataSourcesPermissionsRead = 'datasources.permissions:read',\n"
],
"file_path": "public/app/types/accessControl.ts",
"type": "add",
"edit_start_line_idx": 41
} | import { InlineField, Input, QueryField } from '@grafana/ui';
import { css } from '@emotion/css';
import React, { useEffect } from 'react';
import { AddRemove } from '../../../../AddRemove';
import { useDispatch, useStatelessReducer } from '../../../../../hooks/useStatelessReducer';
import { Filters } from '../../aggregations';
import { changeBucketAggregationSetting } from '../../state/actions';
import { addFilter, changeFilter, removeFilter } from './state/actions';
import { reducer as filtersReducer } from './state/reducer';
interface Props {
bucketAgg: Filters;
}
export const FiltersSettingsEditor = ({ bucketAgg }: Props) => {
const upperStateDispatch = useDispatch();
const dispatch = useStatelessReducer(
(newValue) => upperStateDispatch(changeBucketAggregationSetting({ bucketAgg, settingName: 'filters', newValue })),
bucketAgg.settings?.filters,
filtersReducer
);
// The model might not have filters (or an empty array of filters) in it because of the way it was built in previous versions of the datasource.
// If this is the case we add a default one.
useEffect(() => {
if (!bucketAgg.settings?.filters?.length) {
dispatch(addFilter());
}
}, [dispatch, bucketAgg.settings?.filters?.length]);
return (
<>
<div
className={css`
display: flex;
flex-direction: column;
`}
>
{bucketAgg.settings?.filters!.map((filter, index) => (
<div
key={index}
className={css`
display: flex;
`}
>
<div
className={css`
width: 250px;
`}
>
<InlineField label="Query" labelWidth={10}>
<QueryField
placeholder="Lucene Query"
portalOrigin="elasticsearch"
onBlur={() => {}}
onChange={(query) => dispatch(changeFilter({ index, filter: { ...filter, query } }))}
query={filter.query}
/>
</InlineField>
</div>
<InlineField label="Label" labelWidth={10}>
<Input
placeholder="Label"
onBlur={(e) => dispatch(changeFilter({ index, filter: { ...filter, label: e.target.value } }))}
defaultValue={filter.label}
/>
</InlineField>
<AddRemove
index={index}
elements={bucketAgg.settings?.filters || []}
onAdd={() => dispatch(addFilter())}
onRemove={() => dispatch(removeFilter(index))}
/>
</div>
))}
</div>
</>
);
};
| public/app/plugins/datasource/elasticsearch/components/QueryEditor/BucketAggregationsEditor/SettingsEditor/FiltersSettingsEditor/index.tsx | 0 | https://github.com/grafana/grafana/commit/cf7034ee50569ee6b68f4f8ca47bbfd03b2af224 | [
0.00017934916832018644,
0.00017551673226989806,
0.00017102992569562048,
0.00017562731227371842,
0.000002158025836251909
] |
{
"id": 2,
"code_window": [
" DataSourcesExplore = 'datasources:explore',\n",
" DataSourcesRead = 'datasources:read',\n",
" DataSourcesCreate = 'datasources:create',\n",
" DataSourcesWrite = 'datasources:write',\n",
" DataSourcesDelete = 'datasources:delete',\n",
"\n",
" ActionServerStatsRead = 'server.stats:read',\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" DataSourcesPermissionsRead = 'datasources.permissions:read',\n"
],
"file_path": "public/app/types/accessControl.ts",
"type": "add",
"edit_start_line_idx": 41
} | ---
title: Select home dashboard list
---
1. In the **Home Dashboard** field, select the dashboard that you want to use for your home dashboard. Options include all starred dashboards.
1. Click **Save**.
| docs/sources/shared/preferences/select-home-dashboard-list.md | 0 | https://github.com/grafana/grafana/commit/cf7034ee50569ee6b68f4f8ca47bbfd03b2af224 | [
0.00017045748245436698,
0.00017045748245436698,
0.00017045748245436698,
0.00017045748245436698,
0
] |
{
"id": 0,
"code_window": [
" _polyfillHostRe.lastIndex = 0;\n",
"\n",
" if (_polyfillHostRe.test(selector)) {\n",
" const replaceBy = this.strictStyling ? `[${hostSelector}]` : scopeSelector;\n",
" return selector.replace(_polyfillHostNoCombinatorRe, (hnc, selector) => selector + replaceBy)\n",
" .replace(_polyfillHostRe, replaceBy + ' ');\n",
" }\n",
"\n",
" return scopeSelector + ' ' + selector;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" return selector\n",
" .replace(\n",
" _polyfillHostNoCombinatorRe,\n",
" (hnc, selector) => selector[0] === ':' ? replaceBy + selector : selector + replaceBy)\n"
],
"file_path": "modules/@angular/compiler/src/shadow_css.ts",
"type": "replace",
"edit_start_line_idx": 383
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {CssRule, ShadowCss, processRules} from '@angular/compiler/src/shadow_css';
import {normalizeCSS} from '@angular/platform-browser/testing/browser_util';
export function main() {
describe('ShadowCss', function() {
function s(css: string, contentAttr: string, hostAttr: string = '') {
const shadowCss = new ShadowCss();
const shim = shadowCss.shimCssText(css, contentAttr, hostAttr);
const nlRegexp = /\n/g;
return normalizeCSS(shim.replace(nlRegexp, ''));
}
it('should handle empty string', () => { expect(s('', 'a')).toEqual(''); });
it('should add an attribute to every rule', () => {
const css = 'one {color: red;}two {color: red;}';
const expected = 'one[a] {color:red;}two[a] {color:red;}';
expect(s(css, 'a')).toEqual(expected);
});
it('should handle invalid css', () => {
const css = 'one {color: red;}garbage';
const expected = 'one[a] {color:red;}garbage';
expect(s(css, 'a')).toEqual(expected);
});
it('should add an attribute to every selector', () => {
const css = 'one, two {color: red;}';
const expected = 'one[a], two[a] {color:red;}';
expect(s(css, 'a')).toEqual(expected);
});
it('should support newlines in the selector and content ', () => {
const css = 'one, \ntwo {\ncolor: red;}';
const expected = 'one[a], two[a] {color:red;}';
expect(s(css, 'a')).toEqual(expected);
});
it('should handle media rules', () => {
const css = '@media screen and (max-width:800px, max-height:100%) {div {font-size:50px;}}';
const expected =
'@media screen and (max-width:800px, max-height:100%) {div[a] {font-size:50px;}}';
expect(s(css, 'a')).toEqual(expected);
});
it('should handle page rules', () => {
const css = '@page {div {font-size:50px;}}';
const expected = '@page {div[a] {font-size:50px;}}';
expect(s(css, 'a')).toEqual(expected);
});
it('should handle document rules', () => {
const css = '@document url(http://www.w3.org/) {div {font-size:50px;}}';
const expected = '@document url(http://www.w3.org/) {div[a] {font-size:50px;}}';
expect(s(css, 'a')).toEqual(expected);
});
it('should handle media rules with simple rules', () => {
const css = '@media screen and (max-width: 800px) {div {font-size: 50px;}} div {}';
const expected = '@media screen and (max-width:800px) {div[a] {font-size:50px;}} div[a] {}';
expect(s(css, 'a')).toEqual(expected);
});
it('should handle support rules', () => {
const css = '@supports (display: flex) {section {display: flex;}}';
const expected = '@supports (display:flex) {section[a] {display:flex;}}';
expect(s(css, 'a')).toEqual(expected);
});
// Check that the browser supports unprefixed CSS animation
it('should handle keyframes rules', () => {
const css = '@keyframes foo {0% {transform:translate(-50%) scaleX(0);}}';
expect(s(css, 'a')).toEqual(css);
});
it('should handle -webkit-keyframes rules', () => {
const css = '@-webkit-keyframes foo {0% {-webkit-transform:translate(-50%) scaleX(0);}}';
expect(s(css, 'a')).toEqual(css);
});
it('should handle complicated selectors', () => {
expect(s('one::before {}', 'a')).toEqual('one[a]::before {}');
expect(s('one two {}', 'a')).toEqual('one[a] two[a] {}');
expect(s('one > two {}', 'a')).toEqual('one[a] > two[a] {}');
expect(s('one + two {}', 'a')).toEqual('one[a] + two[a] {}');
expect(s('one ~ two {}', 'a')).toEqual('one[a] ~ two[a] {}');
const res = s('.one.two > three {}', 'a'); // IE swap classes
expect(res == '.one.two[a] > three[a] {}' || res == '.two.one[a] > three[a] {}')
.toEqual(true);
expect(s('one[attr="value"] {}', 'a')).toEqual('one[attr="value"][a] {}');
expect(s('one[attr=value] {}', 'a')).toEqual('one[attr="value"][a] {}');
expect(s('one[attr^="value"] {}', 'a')).toEqual('one[attr^="value"][a] {}');
expect(s('one[attr$="value"] {}', 'a')).toEqual('one[attr$="value"][a] {}');
expect(s('one[attr*="value"] {}', 'a')).toEqual('one[attr*="value"][a] {}');
expect(s('one[attr|="value"] {}', 'a')).toEqual('one[attr|="value"][a] {}');
expect(s('one[attr~="value"] {}', 'a')).toEqual('one[attr~="value"][a] {}');
expect(s('one[attr="va lue"] {}', 'a')).toEqual('one[attr="va lue"][a] {}');
expect(s('one[attr] {}', 'a')).toEqual('one[attr][a] {}');
expect(s('[is="one"] {}', 'a')).toEqual('[is="one"][a] {}');
});
describe((':host'), () => {
it('should handle no context',
() => { expect(s(':host {}', 'a', 'a-host')).toEqual('[a-host] {}'); });
it('should handle tag selector', () => {
expect(s(':host(ul) {}', 'a', 'a-host')).toEqual('ul[a-host] {}');
});
it('should handle class selector',
() => { expect(s(':host(.x) {}', 'a', 'a-host')).toEqual('.x[a-host] {}'); });
it('should handle attribute selector', () => {
expect(s(':host([a="b"]) {}', 'a', 'a-host')).toEqual('[a="b"][a-host] {}');
expect(s(':host([a=b]) {}', 'a', 'a-host')).toEqual('[a="b"][a-host] {}');
});
it('should handle multiple tag selectors', () => {
expect(s(':host(ul,li) {}', 'a', 'a-host')).toEqual('ul[a-host], li[a-host] {}');
expect(s(':host(ul,li) > .z {}', 'a', 'a-host'))
.toEqual('ul[a-host] > .z[a], li[a-host] > .z[a] {}');
});
it('should handle multiple class selectors', () => {
expect(s(':host(.x,.y) {}', 'a', 'a-host')).toEqual('.x[a-host], .y[a-host] {}');
expect(s(':host(.x,.y) > .z {}', 'a', 'a-host'))
.toEqual('.x[a-host] > .z[a], .y[a-host] > .z[a] {}');
});
it('should handle multiple attribute selectors', () => {
expect(s(':host([a="b"],[c=d]) {}', 'a', 'a-host'))
.toEqual('[a="b"][a-host], [c="d"][a-host] {}');
});
});
describe((':host-context'), () => {
it('should handle tag selector', () => {
expect(s(':host-context(div) {}', 'a', 'a-host')).toEqual('div[a-host], div [a-host] {}');
expect(s(':host-context(ul) > .y {}', 'a', 'a-host'))
.toEqual('ul[a-host] > .y[a], ul [a-host] > .y[a] {}');
});
it('should handle class selector', () => {
expect(s(':host-context(.x) {}', 'a', 'a-host')).toEqual('.x[a-host], .x [a-host] {}');
expect(s(':host-context(.x) > .y {}', 'a', 'a-host'))
.toEqual('.x[a-host] > .y[a], .x [a-host] > .y[a] {}');
});
it('should handle attribute selector', () => {
expect(s(':host-context([a="b"]) {}', 'a', 'a-host'))
.toEqual('[a="b"][a-host], [a="b"] [a-host] {}');
expect(s(':host-context([a=b]) {}', 'a', 'a-host'))
.toEqual('[a=b][a-host], [a="b"] [a-host] {}');
});
});
it('should support polyfill-next-selector', () => {
let css = s('polyfill-next-selector {content: \'x > y\'} z {}', 'a');
expect(css).toEqual('x[a] > y[a]{}');
css = s('polyfill-next-selector {content: "x > y"} z {}', 'a');
expect(css).toEqual('x[a] > y[a]{}');
css = s(`polyfill-next-selector {content: 'button[priority="1"]'} z {}`, 'a');
expect(css).toEqual('button[priority="1"][a]{}');
});
it('should support polyfill-unscoped-rule', () => {
let css = s('polyfill-unscoped-rule {content: \'#menu > .bar\';color: blue;}', 'a');
expect(css).toContain('#menu > .bar {;color:blue;}');
css = s('polyfill-unscoped-rule {content: "#menu > .bar";color: blue;}', 'a');
expect(css).toContain('#menu > .bar {;color:blue;}');
css = s(`polyfill-unscoped-rule {content: 'button[priority="1"]'}`, 'a');
expect(css).toContain('button[priority="1"] {}');
});
it('should support multiple instances polyfill-unscoped-rule', () => {
const css =
s('polyfill-unscoped-rule {content: \'foo\';color: blue;}' +
'polyfill-unscoped-rule {content: \'bar\';color: blue;}',
'a');
expect(css).toContain('foo {;color:blue;}');
expect(css).toContain('bar {;color:blue;}');
});
it('should support polyfill-rule', () => {
let css = s('polyfill-rule {content: \':host.foo .bar\';color: blue;}', 'a', 'a-host');
expect(css).toEqual('.foo[a-host] .bar[a] {;color:blue;}');
css = s('polyfill-rule {content: ":host.foo .bar";color:blue;}', 'a', 'a-host');
expect(css).toEqual('.foo[a-host] .bar[a] {;color:blue;}');
css = s(`polyfill-rule {content: 'button[priority="1"]'}`, 'a', 'a-host');
expect(css).toEqual('button[priority="1"][a] {}');
});
it('should handle ::shadow', () => {
const css = s('x::shadow > y {}', 'a');
expect(css).toEqual('x[a] > y[a] {}');
});
it('should handle /deep/', () => {
const css = s('x /deep/ y {}', 'a');
expect(css).toEqual('x[a] y {}');
});
it('should handle >>>', () => {
const css = s('x >>> y {}', 'a');
expect(css).toEqual('x[a] y {}');
});
it('should pass through @import directives', () => {
const styleStr = '@import url("https://fonts.googleapis.com/css?family=Roboto");';
const css = s(styleStr, 'a');
expect(css).toEqual(styleStr);
});
it('should shim rules after @import', () => {
const styleStr = '@import url("a"); div {}';
const css = s(styleStr, 'a');
expect(css).toEqual('@import url("a"); div[a] {}');
});
it('should leave calc() unchanged', () => {
const styleStr = 'div {height:calc(100% - 55px);}';
const css = s(styleStr, 'a');
expect(css).toEqual('div[a] {height:calc(100% - 55px);}');
});
it('should strip comments', () => { expect(s('/* x */b {c}', 'a')).toEqual('b[a] {c}'); });
it('should ignore special characters in comments',
() => { expect(s('/* {;, */b {c}', 'a')).toEqual('b[a] {c}'); });
it('should support multiline comments',
() => { expect(s('/* \n */b {c}', 'a')).toEqual('b[a] {c}'); });
it('should keep sourceMappingURL comments', () => {
expect(s('b {c}/*# sourceMappingURL=data:x */', 'a'))
.toEqual('b[a] {c}/*# sourceMappingURL=data:x */');
expect(s('b {c}/* #sourceMappingURL=data:x */', 'a'))
.toEqual('b[a] {c}/* #sourceMappingURL=data:x */');
});
});
describe('processRules', () => {
describe('parse rules', () => {
function captureRules(input: string): CssRule[] {
const result: CssRule[] = [];
processRules(input, (cssRule) => {
result.push(cssRule);
return cssRule;
});
return result;
}
it('should work with empty css', () => { expect(captureRules('')).toEqual([]); });
it('should capture a rule without body',
() => { expect(captureRules('a;')).toEqual([new CssRule('a', '')]); });
it('should capture css rules with body',
() => { expect(captureRules('a {b}')).toEqual([new CssRule('a', 'b')]); });
it('should capture css rules with nested rules', () => {
expect(captureRules('a {b {c}} d {e}')).toEqual([
new CssRule('a', 'b {c}'), new CssRule('d', 'e')
]);
});
it('should capture multiple rules where some have no body', () => {
expect(captureRules('@import a ; b {c}')).toEqual([
new CssRule('@import a', ''), new CssRule('b', 'c')
]);
});
});
describe('modify rules', () => {
it('should allow to change the selector while preserving whitespaces', () => {
expect(processRules(
'@import a; b {c {d}} e {f}',
(cssRule: CssRule) => new CssRule(cssRule.selector + '2', cssRule.content)))
.toEqual('@import a2; b2 {c {d}} e2 {f}');
});
it('should allow to change the content', () => {
expect(processRules(
'a {b}',
(cssRule: CssRule) => new CssRule(cssRule.selector, cssRule.content + '2')))
.toEqual('a {b2}');
});
});
});
}
| modules/@angular/compiler/test/shadow_css_spec.ts | 1 | https://github.com/angular/angular/commit/aa92512ac6869a575e48a94e508411ec349fa3eb | [
0.00020266883075237274,
0.00017382290388923138,
0.0001607075537322089,
0.00017448027210775763,
0.000006927699359948747
] |
{
"id": 0,
"code_window": [
" _polyfillHostRe.lastIndex = 0;\n",
"\n",
" if (_polyfillHostRe.test(selector)) {\n",
" const replaceBy = this.strictStyling ? `[${hostSelector}]` : scopeSelector;\n",
" return selector.replace(_polyfillHostNoCombinatorRe, (hnc, selector) => selector + replaceBy)\n",
" .replace(_polyfillHostRe, replaceBy + ' ');\n",
" }\n",
"\n",
" return scopeSelector + ' ' + selector;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" return selector\n",
" .replace(\n",
" _polyfillHostNoCombinatorRe,\n",
" (hnc, selector) => selector[0] === ':' ? replaceBy + selector : selector + replaceBy)\n"
],
"file_path": "modules/@angular/compiler/src/shadow_css.ts",
"type": "replace",
"edit_start_line_idx": 383
} | #!/bin/bash
# This script prepares build artifacts for upload to NPM.
#
# Usage:
#
# scripts/publish/npm_prepare.sh PACKAGE_NAME
set -ex
shopt -s extglob
NAME=$1
ROOT_DIR=$(cd $(dirname $0)/../..; pwd)
cd $ROOT_DIR
NPM_DIR=$ROOT_DIR/dist/npm
FILES='!(test|e2e_test|docs)'
PUBLISH_DIR=$NPM_DIR/$NAME
rm -fr $PUBLISH_DIR
mkdir -p $PUBLISH_DIR
mkdir -p $PUBLISH_DIR/es6/dev
cp -r $ROOT_DIR/dist/js/dev/es6/$NAME/$FILES $PUBLISH_DIR/es6/dev
mkdir -p $PUBLISH_DIR/es6/prod
cp -r $ROOT_DIR/dist/js/prod/es6/$NAME/$FILES $PUBLISH_DIR/es6/prod
mkdir -p $PUBLISH_DIR/ts
cp -r $ROOT_DIR/modules/$NAME/$FILES $PUBLISH_DIR/ts
if [ $NAME = "angular2" ]; then
# Copy Bundles
mkdir -p $PUBLISH_DIR/bundles
cp -r $ROOT_DIR/dist/js/bundle/$FILES $PUBLISH_DIR/bundles
fi
if [ $NAME = "benchpress" ]; then
cp -r $ROOT_DIR/dist/build/benchpress_bundle/$FILES $PUBLISH_DIR
cp -r $ROOT_DIR/dist/js/cjs/benchpress/README.md $PUBLISH_DIR
cp -r $ROOT_DIR/dist/js/cjs/benchpress/LICENSE $PUBLISH_DIR
cp -r $ROOT_DIR/dist/js/cjs/benchpress/docs $PUBLISH_DIR
else
cp -r $ROOT_DIR/dist/js/cjs/$NAME/$FILES $PUBLISH_DIR
fi
# Remove all dart related files
rm -f $PUBLISH_DIR/{,**/}{*.dart,*.dart.md}
| scripts/publish/npm_prepare.sh | 0 | https://github.com/angular/angular/commit/aa92512ac6869a575e48a94e508411ec349fa3eb | [
0.00017423105600755662,
0.0001707768824417144,
0.00016610434977337718,
0.00017085338186006993,
0.0000028525307698146207
] |
{
"id": 0,
"code_window": [
" _polyfillHostRe.lastIndex = 0;\n",
"\n",
" if (_polyfillHostRe.test(selector)) {\n",
" const replaceBy = this.strictStyling ? `[${hostSelector}]` : scopeSelector;\n",
" return selector.replace(_polyfillHostNoCombinatorRe, (hnc, selector) => selector + replaceBy)\n",
" .replace(_polyfillHostRe, replaceBy + ' ');\n",
" }\n",
"\n",
" return scopeSelector + ' ' + selector;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" return selector\n",
" .replace(\n",
" _polyfillHostNoCombinatorRe,\n",
" (hnc, selector) => selector[0] === ':' ? replaceBy + selector : selector + replaceBy)\n"
],
"file_path": "modules/@angular/compiler/src/shadow_css.ts",
"type": "replace",
"edit_start_line_idx": 383
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
export class CliOptions {
public basePath: string;
constructor({basePath = null}: {basePath?: string}) { this.basePath = basePath; }
}
export class I18nExtractionCliOptions extends CliOptions {
public i18nFormat: string;
constructor({i18nFormat = null}: {i18nFormat?: string}) {
super({});
this.i18nFormat = i18nFormat;
}
}
export class NgcCliOptions extends CliOptions {
public i18nFormat: string;
public i18nFile: string;
public locale: string;
constructor({i18nFormat = null, i18nFile = null, locale = null, basePath = null}:
{i18nFormat?: string, i18nFile?: string, locale?: string, basePath?: string}) {
super({basePath: basePath});
this.i18nFormat = i18nFormat;
this.i18nFile = i18nFile;
this.locale = locale;
}
}
| tools/@angular/tsc-wrapped/src/cli_options.ts | 0 | https://github.com/angular/angular/commit/aa92512ac6869a575e48a94e508411ec349fa3eb | [
0.00017665601626504213,
0.0001715395483188331,
0.000167945065186359,
0.00017077855591196567,
0.0000033556775633769576
] |
{
"id": 0,
"code_window": [
" _polyfillHostRe.lastIndex = 0;\n",
"\n",
" if (_polyfillHostRe.test(selector)) {\n",
" const replaceBy = this.strictStyling ? `[${hostSelector}]` : scopeSelector;\n",
" return selector.replace(_polyfillHostNoCombinatorRe, (hnc, selector) => selector + replaceBy)\n",
" .replace(_polyfillHostRe, replaceBy + ' ');\n",
" }\n",
"\n",
" return scopeSelector + ' ' + selector;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" return selector\n",
" .replace(\n",
" _polyfillHostNoCombinatorRe,\n",
" (hnc, selector) => selector[0] === ':' ? replaceBy + selector : selector + replaceBy)\n"
],
"file_path": "modules/@angular/compiler/src/shadow_css.ts",
"type": "replace",
"edit_start_line_idx": 383
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Compiler, ComponentFactory, Injector, NgModule, NgModuleRef, NgZone, Provider, Testability, Type} from '@angular/core';
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
import * as angular from './angular_js';
import {NG1_COMPILE, NG1_INJECTOR, NG1_PARSE, NG1_ROOT_SCOPE, NG1_TESTABILITY, NG2_COMPILER, NG2_COMPONENT_FACTORY_REF_MAP, NG2_INJECTOR, NG2_ZONE, REQUIRE_INJECTOR} from './constants';
import {DowngradeNg2ComponentAdapter} from './downgrade_ng2_adapter';
import {ComponentInfo, getComponentInfo} from './metadata';
import {UpgradeNg1ComponentAdapterBuilder} from './upgrade_ng1_adapter';
import {controllerKey, onError} from './util';
var upgradeCount: number = 0;
/**
* Use `UpgradeAdapter` to allow AngularJS v1 and Angular v2 to coexist in a single application.
*
* The `UpgradeAdapter` allows:
* 1. creation of Angular v2 component from AngularJS v1 component directive
* (See [UpgradeAdapter#upgradeNg1Component()])
* 2. creation of AngularJS v1 directive from Angular v2 component.
* (See [UpgradeAdapter#downgradeNg2Component()])
* 3. Bootstrapping of a hybrid Angular application which contains both of the frameworks
* coexisting in a single application.
*
* ## Mental Model
*
* When reasoning about how a hybrid application works it is useful to have a mental model which
* describes what is happening and explains what is happening at the lowest level.
*
* 1. There are two independent frameworks running in a single application, each framework treats
* the other as a black box.
* 2. Each DOM element on the page is owned exactly by one framework. Whichever framework
* instantiated the element is the owner. Each framework only updates/interacts with its own
* DOM elements and ignores others.
* 3. AngularJS v1 directives always execute inside AngularJS v1 framework codebase regardless of
* where they are instantiated.
* 4. Angular v2 components always execute inside Angular v2 framework codebase regardless of
* where they are instantiated.
* 5. An AngularJS v1 component can be upgraded to an Angular v2 component. This creates an
* Angular v2 directive, which bootstraps the AngularJS v1 component directive in that location.
* 6. An Angular v2 component can be downgraded to an AngularJS v1 component directive. This creates
* an AngularJS v1 directive, which bootstraps the Angular v2 component in that location.
* 7. Whenever an adapter component is instantiated the host element is owned by the framework
* doing the instantiation. The other framework then instantiates and owns the view for that
* component. This implies that component bindings will always follow the semantics of the
* instantiation framework. The syntax is always that of Angular v2 syntax.
* 8. AngularJS v1 is always bootstrapped first and owns the bottom most view.
* 9. The new application is running in Angular v2 zone, and therefore it no longer needs calls to
* `$apply()`.
*
* ### Example
*
* ```
* var adapter = new UpgradeAdapter(forwardRef(() => MyNg2Module));
* var module = angular.module('myExample', []);
* module.directive('ng2Comp', adapter.downgradeNg2Component(Ng2Component));
*
* module.directive('ng1Hello', function() {
* return {
* scope: { title: '=' },
* template: 'ng1[Hello {{title}}!](<span ng-transclude></span>)'
* };
* });
*
*
* @Component({
* selector: 'ng2-comp',
* inputs: ['name'],
* template: 'ng2[<ng1-hello [title]="name">transclude</ng1-hello>](<ng-content></ng-content>)',
* directives:
* })
* class Ng2Component {
* }
*
* @NgModule({
* declarations: [Ng2Component, adapter.upgradeNg1Component('ng1Hello')],
* imports: [BrowserModule]
* })
* class MyNg2Module {}
*
*
* document.body.innerHTML = '<ng2-comp name="World">project</ng2-comp>';
*
* adapter.bootstrap(document.body, ['myExample']).ready(function() {
* expect(document.body.textContent).toEqual(
* "ng2[ng1[Hello World!](transclude)](project)");
* });
*
* ```
*
* @stable
*/
export class UpgradeAdapter {
/* @internal */
private idPrefix: string = `NG2_UPGRADE_${upgradeCount++}_`;
/* @internal */
private upgradedComponents: Type<any>[] = [];
/**
* An internal map of ng1 components which need to up upgraded to ng2.
*
* We can't upgrade until injector is instantiated and we can retrieve the component metadata.
* For this reason we keep a list of components to upgrade until ng1 injector is bootstrapped.
*
* @internal
*/
private ng1ComponentsToBeUpgraded: {[name: string]: UpgradeNg1ComponentAdapterBuilder} = {};
/* @internal */
private providers: Provider[] = [];
constructor(private ng2AppModule: Type<any>) {
if (!ng2AppModule) {
throw new Error(
'UpgradeAdapter cannot be instantiated without an NgModule of the Angular 2 app.');
}
}
/**
* Allows Angular v2 Component to be used from AngularJS v1.
*
* Use `downgradeNg2Component` to create an AngularJS v1 Directive Definition Factory from
* Angular v2 Component. The adapter will bootstrap Angular v2 component from within the
* AngularJS v1 template.
*
* ## Mental Model
*
* 1. The component is instantiated by being listed in AngularJS v1 template. This means that the
* host element is controlled by AngularJS v1, but the component's view will be controlled by
* Angular v2.
* 2. Even thought the component is instantiated in AngularJS v1, it will be using Angular v2
* syntax. This has to be done, this way because we must follow Angular v2 components do not
* declare how the attributes should be interpreted.
*
* ## Supported Features
*
* - Bindings:
* - Attribute: `<comp name="World">`
* - Interpolation: `<comp greeting="Hello {{name}}!">`
* - Expression: `<comp [name]="username">`
* - Event: `<comp (close)="doSomething()">`
* - Content projection: yes
*
* ### Example
*
* ```
* var adapter = new UpgradeAdapter(forwardRef(() => MyNg2Module));
* var module = angular.module('myExample', []);
* module.directive('greet', adapter.downgradeNg2Component(Greeter));
*
* @Component({
* selector: 'greet',
* template: '{{salutation}} {{name}}! - <ng-content></ng-content>'
* })
* class Greeter {
* @Input() salutation: string;
* @Input() name: string;
* }
*
* @NgModule({
* declarations: [Greeter],
* imports: [BrowserModule]
* })
* class MyNg2Module {}
*
* document.body.innerHTML =
* 'ng1 template: <greet salutation="Hello" [name]="world">text</greet>';
*
* adapter.bootstrap(document.body, ['myExample']).ready(function() {
* expect(document.body.textContent).toEqual("ng1 template: Hello world! - text");
* });
* ```
*/
downgradeNg2Component(type: Type<any>): Function {
this.upgradedComponents.push(type);
var info: ComponentInfo = getComponentInfo(type);
return ng1ComponentDirective(info, `${this.idPrefix}${info.selector}_c`);
}
/**
* Allows AngularJS v1 Component to be used from Angular v2.
*
* Use `upgradeNg1Component` to create an Angular v2 component from AngularJS v1 Component
* directive. The adapter will bootstrap AngularJS v1 component from within the Angular v2
* template.
*
* ## Mental Model
*
* 1. The component is instantiated by being listed in Angular v2 template. This means that the
* host element is controlled by Angular v2, but the component's view will be controlled by
* AngularJS v1.
*
* ## Supported Features
*
* - Bindings:
* - Attribute: `<comp name="World">`
* - Interpolation: `<comp greeting="Hello {{name}}!">`
* - Expression: `<comp [name]="username">`
* - Event: `<comp (close)="doSomething()">`
* - Transclusion: yes
* - Only some of the features of
* [Directive Definition Object](https://docs.angularjs.org/api/ng/service/$compile) are
* supported:
* - `compile`: not supported because the host element is owned by Angular v2, which does
* not allow modifying DOM structure during compilation.
* - `controller`: supported. (NOTE: injection of `$attrs` and `$transclude` is not supported.)
* - `controllerAs': supported.
* - `bindToController': supported.
* - `link': supported. (NOTE: only pre-link function is supported.)
* - `name': supported.
* - `priority': ignored.
* - `replace': not supported.
* - `require`: supported.
* - `restrict`: must be set to 'E'.
* - `scope`: supported.
* - `template`: supported.
* - `templateUrl`: supported.
* - `terminal`: ignored.
* - `transclude`: supported.
*
*
* ### Example
*
* ```
* var adapter = new UpgradeAdapter(forwardRef(() => MyNg2Module));
* var module = angular.module('myExample', []);
*
* module.directive('greet', function() {
* return {
* scope: {salutation: '=', name: '=' },
* template: '{{salutation}} {{name}}! - <span ng-transclude></span>'
* };
* });
*
* module.directive('ng2', adapter.downgradeNg2Component(Ng2Component));
*
* @Component({
* selector: 'ng2',
* template: 'ng2 template: <greet salutation="Hello" [name]="world">text</greet>'
* })
* class Ng2Component {
* }
*
* @NgModule({
* declarations: [Ng2Component, adapter.upgradeNg1Component('greet')],
* imports: [BrowserModule]
* })
* class MyNg2Module {}
*
* document.body.innerHTML = '<ng2></ng2>';
*
* adapter.bootstrap(document.body, ['myExample']).ready(function() {
* expect(document.body.textContent).toEqual("ng2 template: Hello world! - text");
* });
* ```
*/
upgradeNg1Component(name: string): Type<any> {
if ((<any>this.ng1ComponentsToBeUpgraded).hasOwnProperty(name)) {
return this.ng1ComponentsToBeUpgraded[name].type;
} else {
return (this.ng1ComponentsToBeUpgraded[name] = new UpgradeNg1ComponentAdapterBuilder(name))
.type;
}
}
/**
* Bootstrap a hybrid AngularJS v1 / Angular v2 application.
*
* This `bootstrap` method is a direct replacement (takes same arguments) for AngularJS v1
* [`bootstrap`](https://docs.angularjs.org/api/ng/function/angular.bootstrap) method. Unlike
* AngularJS v1, this bootstrap is asynchronous.
*
* ### Example
*
* ```
* var adapter = new UpgradeAdapter();
* var module = angular.module('myExample', []);
* module.directive('ng2', adapter.downgradeNg2Component(Ng2));
*
* module.directive('ng1', function() {
* return {
* scope: { title: '=' },
* template: 'ng1[Hello {{title}}!](<span ng-transclude></span>)'
* };
* });
*
*
* @Component({
* selector: 'ng2',
* inputs: ['name'],
* template: 'ng2[<ng1 [title]="name">transclude</ng1>](<ng-content></ng-content>)'
* })
* class Ng2 {
* }
*
* @NgModule({
* declarations: [Ng2, adapter.upgradeNg1Component('ng1')],
* imports: [BrowserModule]
* })
* class MyNg2Module {}
*
* document.body.innerHTML = '<ng2 name="World">project</ng2>';
*
* adapter.bootstrap(document.body, ['myExample']).ready(function() {
* expect(document.body.textContent).toEqual(
* "ng2[ng1[Hello World!](transclude)](project)");
* });
* ```
*/
bootstrap(element: Element, modules?: any[], config?: angular.IAngularBootstrapConfig):
UpgradeAdapterRef {
const ngZone =
new NgZone({enableLongStackTrace: Zone.hasOwnProperty('longStackTraceZoneSpec')});
var upgrade = new UpgradeAdapterRef();
var ng1Injector: angular.IInjectorService = null;
var moduleRef: NgModuleRef<any> = null;
var delayApplyExps: Function[] = [];
var original$applyFn: Function;
var rootScopePrototype: any;
var rootScope: angular.IRootScopeService;
var componentFactoryRefMap: ComponentFactoryRefMap = {};
var ng1Module = angular.module(this.idPrefix, modules);
var ng1BootstrapPromise: Promise<any>;
var ng1compilePromise: Promise<any>;
ng1Module.factory(NG2_INJECTOR, () => moduleRef.injector.get(Injector))
.value(NG2_ZONE, ngZone)
.factory(NG2_COMPILER, () => moduleRef.injector.get(Compiler))
.value(NG2_COMPONENT_FACTORY_REF_MAP, componentFactoryRefMap)
.config([
'$provide', '$injector',
(provide: any /** TODO #???? */, ng1Injector: angular.IInjectorService) => {
provide.decorator(NG1_ROOT_SCOPE, [
'$delegate',
function(rootScopeDelegate: angular.IRootScopeService) {
// Capture the root apply so that we can delay first call to $apply until we
// bootstrap Angular 2 and then we replay and restore the $apply.
rootScopePrototype = rootScopeDelegate.constructor.prototype;
if (rootScopePrototype.hasOwnProperty('$apply')) {
original$applyFn = rootScopePrototype.$apply;
rootScopePrototype.$apply = (exp: any) => delayApplyExps.push(exp);
} else {
throw new Error('Failed to find \'$apply\' on \'$rootScope\'!');
}
return rootScope = rootScopeDelegate;
}
]);
if (ng1Injector.has(NG1_TESTABILITY)) {
provide.decorator(NG1_TESTABILITY, [
'$delegate',
function(testabilityDelegate: angular.ITestabilityService) {
var originalWhenStable: Function = testabilityDelegate.whenStable;
var newWhenStable = (callback: Function): void => {
var whenStableContext: any = this;
originalWhenStable.call(this, function() {
var ng2Testability: Testability = moduleRef.injector.get(Testability);
if (ng2Testability.isStable()) {
callback.apply(this, arguments);
} else {
ng2Testability.whenStable(newWhenStable.bind(whenStableContext, callback));
}
});
};
testabilityDelegate.whenStable = newWhenStable;
return testabilityDelegate;
}
]);
}
}
]);
ng1compilePromise = new Promise((resolve, reject) => {
ng1Module.run([
'$injector', '$rootScope',
(injector: angular.IInjectorService, rootScope: angular.IRootScopeService) => {
ng1Injector = injector;
UpgradeNg1ComponentAdapterBuilder.resolve(this.ng1ComponentsToBeUpgraded, injector)
.then(() => {
// At this point we have ng1 injector and we have lifted ng1 components into ng2, we
// now can bootstrap ng2.
var DynamicNgUpgradeModule =
NgModule({
providers: [
{provide: NG1_INJECTOR, useFactory: () => ng1Injector},
{provide: NG1_COMPILE, useFactory: () => ng1Injector.get(NG1_COMPILE)},
this.providers
],
imports: [this.ng2AppModule]
}).Class({
constructor: function DynamicNgUpgradeModule() {},
ngDoBootstrap: function() {}
});
(platformBrowserDynamic() as any)
._bootstrapModuleWithZone(
DynamicNgUpgradeModule, undefined, ngZone,
(componentFactories: ComponentFactory<any>[]) => {
componentFactories.forEach((componentFactory: ComponentFactory<any>) => {
var type: Type<any> = componentFactory.componentType;
if (this.upgradedComponents.indexOf(type) !== -1) {
componentFactoryRefMap[getComponentInfo(type).selector] =
componentFactory;
}
});
})
.then((ref: NgModuleRef<any>) => {
moduleRef = ref;
angular.element(element).data(
controllerKey(NG2_INJECTOR), moduleRef.injector);
ngZone.onMicrotaskEmpty.subscribe({
next: (_: any) => ngZone.runOutsideAngular(() => rootScope.$evalAsync())
});
})
.then(resolve, reject);
});
}
]);
});
// Make sure resumeBootstrap() only exists if the current bootstrap is deferred
var windowAngular = (window as any /** TODO #???? */)['angular'];
windowAngular.resumeBootstrap = undefined;
ngZone.run(() => { angular.bootstrap(element, [this.idPrefix], config); });
ng1BootstrapPromise = new Promise((resolve) => {
if (windowAngular.resumeBootstrap) {
var originalResumeBootstrap: () => void = windowAngular.resumeBootstrap;
windowAngular.resumeBootstrap = function() {
windowAngular.resumeBootstrap = originalResumeBootstrap;
windowAngular.resumeBootstrap.apply(this, arguments);
resolve();
};
} else {
resolve();
}
});
Promise.all([ng1BootstrapPromise, ng1compilePromise]).then(() => {
moduleRef.injector.get(NgZone).run(() => {
if (rootScopePrototype) {
rootScopePrototype.$apply = original$applyFn; // restore original $apply
while (delayApplyExps.length) {
rootScope.$apply(delayApplyExps.shift());
}
(<any>upgrade)._bootstrapDone(moduleRef, ng1Injector);
rootScopePrototype = null;
}
});
}, onError);
return upgrade;
}
/**
* Allows AngularJS v1 service to be accessible from Angular v2.
*
*
* ### Example
*
* ```
* class Login { ... }
* class Server { ... }
*
* @Injectable()
* class Example {
* constructor(@Inject('server') server, login: Login) {
* ...
* }
* }
*
* var module = angular.module('myExample', []);
* module.service('server', Server);
* module.service('login', Login);
*
* var adapter = new UpgradeAdapter();
* adapter.upgradeNg1Provider('server');
* adapter.upgradeNg1Provider('login', {asToken: Login});
*
* adapter.bootstrap(document.body, ['myExample']).ready((ref) => {
* var example: Example = ref.ng2Injector.get(Example);
* });
*
* ```
*/
public upgradeNg1Provider(name: string, options?: {asToken: any}) {
var token = options && options.asToken || name;
this.providers.push({
provide: token,
useFactory: (ng1Injector: angular.IInjectorService) => ng1Injector.get(name),
deps: [NG1_INJECTOR]
});
}
/**
* Allows Angular v2 service to be accessible from AngularJS v1.
*
*
* ### Example
*
* ```
* class Example {
* }
*
* var adapter = new UpgradeAdapter();
*
* var module = angular.module('myExample', []);
* module.factory('example', adapter.downgradeNg2Provider(Example));
*
* adapter.bootstrap(document.body, ['myExample']).ready((ref) => {
* var example: Example = ref.ng1Injector.get('example');
* });
*
* ```
*/
public downgradeNg2Provider(token: any): Function {
var factory = function(injector: Injector) { return injector.get(token); };
(<any>factory).$inject = [NG2_INJECTOR];
return factory;
}
}
interface ComponentFactoryRefMap {
[selector: string]: ComponentFactory<any>;
}
function ng1ComponentDirective(info: ComponentInfo, idPrefix: string): Function {
(<any>directiveFactory).$inject = [NG1_INJECTOR, NG2_COMPONENT_FACTORY_REF_MAP, NG1_PARSE];
function directiveFactory(
ng1Injector: angular.IInjectorService, componentFactoryRefMap: ComponentFactoryRefMap,
parse: angular.IParseService): angular.IDirective {
var idCount = 0;
return {
restrict: 'E',
require: REQUIRE_INJECTOR,
link: {
post: (scope: angular.IScope, element: angular.IAugmentedJQuery, attrs: angular.IAttributes,
parentInjector: any, transclude: angular.ITranscludeFunction): void => {
var componentFactory: ComponentFactory<any> = componentFactoryRefMap[info.selector];
if (!componentFactory)
throw new Error('Expecting ComponentFactory for: ' + info.selector);
if (parentInjector === null) {
parentInjector = ng1Injector.get(NG2_INJECTOR);
}
var facade = new DowngradeNg2ComponentAdapter(
idPrefix + (idCount++), info, element, attrs, scope, <Injector>parentInjector, parse,
componentFactory);
facade.setupInputs();
facade.bootstrapNg2();
facade.projectContent();
facade.setupOutputs();
facade.registerCleanup();
}
}
};
}
return directiveFactory;
}
/**
* Use `UpgradeAdapterRef` to control a hybrid AngularJS v1 / Angular v2 application.
*
* @stable
*/
export class UpgradeAdapterRef {
/* @internal */
private _readyFn: (upgradeAdapterRef?: UpgradeAdapterRef) => void = null;
public ng1RootScope: angular.IRootScopeService = null;
public ng1Injector: angular.IInjectorService = null;
public ng2ModuleRef: NgModuleRef<any> = null;
public ng2Injector: Injector = null;
/* @internal */
private _bootstrapDone(ngModuleRef: NgModuleRef<any>, ng1Injector: angular.IInjectorService) {
this.ng2ModuleRef = ngModuleRef;
this.ng2Injector = ngModuleRef.injector;
this.ng1Injector = ng1Injector;
this.ng1RootScope = ng1Injector.get(NG1_ROOT_SCOPE);
this._readyFn && this._readyFn(this);
}
/**
* Register a callback function which is notified upon successful hybrid AngularJS v1 / Angular v2
* application has been bootstrapped.
*
* The `ready` callback function is invoked inside the Angular v2 zone, therefore it does not
* require a call to `$apply()`.
*/
public ready(fn: (upgradeAdapterRef?: UpgradeAdapterRef) => void) { this._readyFn = fn; }
/**
* Dispose of running hybrid AngularJS v1 / Angular v2 application.
*/
public dispose() {
this.ng1Injector.get(NG1_ROOT_SCOPE).$destroy();
this.ng2ModuleRef.destroy();
}
}
| modules/@angular/upgrade/src/upgrade_adapter.ts | 0 | https://github.com/angular/angular/commit/aa92512ac6869a575e48a94e508411ec349fa3eb | [
0.00017657196440268308,
0.0001693854428594932,
0.00016024605429265648,
0.00017015074263326824,
0.0000036710309814225184
] |
{
"id": 1,
"code_window": [
" it('should handle no context',\n",
" () => { expect(s(':host {}', 'a', 'a-host')).toEqual('[a-host] {}'); });\n",
"\n",
" it('should handle tag selector', () => {\n",
" expect(s(':host(ul) {}', 'a', 'a-host')).toEqual('ul[a-host] {}');\n",
"\n",
" });\n",
"\n",
" it('should handle class selector',\n",
" () => { expect(s(':host(.x) {}', 'a', 'a-host')).toEqual('.x[a-host] {}'); });\n",
"\n",
" it('should handle attribute selector', () => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" it('should handle tag selector',\n",
" () => { expect(s(':host(ul) {}', 'a', 'a-host')).toEqual('ul[a-host] {}'); });\n"
],
"file_path": "modules/@angular/compiler/test/shadow_css_spec.ts",
"type": "replace",
"edit_start_line_idx": 114
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {CssRule, ShadowCss, processRules} from '@angular/compiler/src/shadow_css';
import {normalizeCSS} from '@angular/platform-browser/testing/browser_util';
export function main() {
describe('ShadowCss', function() {
function s(css: string, contentAttr: string, hostAttr: string = '') {
const shadowCss = new ShadowCss();
const shim = shadowCss.shimCssText(css, contentAttr, hostAttr);
const nlRegexp = /\n/g;
return normalizeCSS(shim.replace(nlRegexp, ''));
}
it('should handle empty string', () => { expect(s('', 'a')).toEqual(''); });
it('should add an attribute to every rule', () => {
const css = 'one {color: red;}two {color: red;}';
const expected = 'one[a] {color:red;}two[a] {color:red;}';
expect(s(css, 'a')).toEqual(expected);
});
it('should handle invalid css', () => {
const css = 'one {color: red;}garbage';
const expected = 'one[a] {color:red;}garbage';
expect(s(css, 'a')).toEqual(expected);
});
it('should add an attribute to every selector', () => {
const css = 'one, two {color: red;}';
const expected = 'one[a], two[a] {color:red;}';
expect(s(css, 'a')).toEqual(expected);
});
it('should support newlines in the selector and content ', () => {
const css = 'one, \ntwo {\ncolor: red;}';
const expected = 'one[a], two[a] {color:red;}';
expect(s(css, 'a')).toEqual(expected);
});
it('should handle media rules', () => {
const css = '@media screen and (max-width:800px, max-height:100%) {div {font-size:50px;}}';
const expected =
'@media screen and (max-width:800px, max-height:100%) {div[a] {font-size:50px;}}';
expect(s(css, 'a')).toEqual(expected);
});
it('should handle page rules', () => {
const css = '@page {div {font-size:50px;}}';
const expected = '@page {div[a] {font-size:50px;}}';
expect(s(css, 'a')).toEqual(expected);
});
it('should handle document rules', () => {
const css = '@document url(http://www.w3.org/) {div {font-size:50px;}}';
const expected = '@document url(http://www.w3.org/) {div[a] {font-size:50px;}}';
expect(s(css, 'a')).toEqual(expected);
});
it('should handle media rules with simple rules', () => {
const css = '@media screen and (max-width: 800px) {div {font-size: 50px;}} div {}';
const expected = '@media screen and (max-width:800px) {div[a] {font-size:50px;}} div[a] {}';
expect(s(css, 'a')).toEqual(expected);
});
it('should handle support rules', () => {
const css = '@supports (display: flex) {section {display: flex;}}';
const expected = '@supports (display:flex) {section[a] {display:flex;}}';
expect(s(css, 'a')).toEqual(expected);
});
// Check that the browser supports unprefixed CSS animation
it('should handle keyframes rules', () => {
const css = '@keyframes foo {0% {transform:translate(-50%) scaleX(0);}}';
expect(s(css, 'a')).toEqual(css);
});
it('should handle -webkit-keyframes rules', () => {
const css = '@-webkit-keyframes foo {0% {-webkit-transform:translate(-50%) scaleX(0);}}';
expect(s(css, 'a')).toEqual(css);
});
it('should handle complicated selectors', () => {
expect(s('one::before {}', 'a')).toEqual('one[a]::before {}');
expect(s('one two {}', 'a')).toEqual('one[a] two[a] {}');
expect(s('one > two {}', 'a')).toEqual('one[a] > two[a] {}');
expect(s('one + two {}', 'a')).toEqual('one[a] + two[a] {}');
expect(s('one ~ two {}', 'a')).toEqual('one[a] ~ two[a] {}');
const res = s('.one.two > three {}', 'a'); // IE swap classes
expect(res == '.one.two[a] > three[a] {}' || res == '.two.one[a] > three[a] {}')
.toEqual(true);
expect(s('one[attr="value"] {}', 'a')).toEqual('one[attr="value"][a] {}');
expect(s('one[attr=value] {}', 'a')).toEqual('one[attr="value"][a] {}');
expect(s('one[attr^="value"] {}', 'a')).toEqual('one[attr^="value"][a] {}');
expect(s('one[attr$="value"] {}', 'a')).toEqual('one[attr$="value"][a] {}');
expect(s('one[attr*="value"] {}', 'a')).toEqual('one[attr*="value"][a] {}');
expect(s('one[attr|="value"] {}', 'a')).toEqual('one[attr|="value"][a] {}');
expect(s('one[attr~="value"] {}', 'a')).toEqual('one[attr~="value"][a] {}');
expect(s('one[attr="va lue"] {}', 'a')).toEqual('one[attr="va lue"][a] {}');
expect(s('one[attr] {}', 'a')).toEqual('one[attr][a] {}');
expect(s('[is="one"] {}', 'a')).toEqual('[is="one"][a] {}');
});
describe((':host'), () => {
it('should handle no context',
() => { expect(s(':host {}', 'a', 'a-host')).toEqual('[a-host] {}'); });
it('should handle tag selector', () => {
expect(s(':host(ul) {}', 'a', 'a-host')).toEqual('ul[a-host] {}');
});
it('should handle class selector',
() => { expect(s(':host(.x) {}', 'a', 'a-host')).toEqual('.x[a-host] {}'); });
it('should handle attribute selector', () => {
expect(s(':host([a="b"]) {}', 'a', 'a-host')).toEqual('[a="b"][a-host] {}');
expect(s(':host([a=b]) {}', 'a', 'a-host')).toEqual('[a="b"][a-host] {}');
});
it('should handle multiple tag selectors', () => {
expect(s(':host(ul,li) {}', 'a', 'a-host')).toEqual('ul[a-host], li[a-host] {}');
expect(s(':host(ul,li) > .z {}', 'a', 'a-host'))
.toEqual('ul[a-host] > .z[a], li[a-host] > .z[a] {}');
});
it('should handle multiple class selectors', () => {
expect(s(':host(.x,.y) {}', 'a', 'a-host')).toEqual('.x[a-host], .y[a-host] {}');
expect(s(':host(.x,.y) > .z {}', 'a', 'a-host'))
.toEqual('.x[a-host] > .z[a], .y[a-host] > .z[a] {}');
});
it('should handle multiple attribute selectors', () => {
expect(s(':host([a="b"],[c=d]) {}', 'a', 'a-host'))
.toEqual('[a="b"][a-host], [c="d"][a-host] {}');
});
});
describe((':host-context'), () => {
it('should handle tag selector', () => {
expect(s(':host-context(div) {}', 'a', 'a-host')).toEqual('div[a-host], div [a-host] {}');
expect(s(':host-context(ul) > .y {}', 'a', 'a-host'))
.toEqual('ul[a-host] > .y[a], ul [a-host] > .y[a] {}');
});
it('should handle class selector', () => {
expect(s(':host-context(.x) {}', 'a', 'a-host')).toEqual('.x[a-host], .x [a-host] {}');
expect(s(':host-context(.x) > .y {}', 'a', 'a-host'))
.toEqual('.x[a-host] > .y[a], .x [a-host] > .y[a] {}');
});
it('should handle attribute selector', () => {
expect(s(':host-context([a="b"]) {}', 'a', 'a-host'))
.toEqual('[a="b"][a-host], [a="b"] [a-host] {}');
expect(s(':host-context([a=b]) {}', 'a', 'a-host'))
.toEqual('[a=b][a-host], [a="b"] [a-host] {}');
});
});
it('should support polyfill-next-selector', () => {
let css = s('polyfill-next-selector {content: \'x > y\'} z {}', 'a');
expect(css).toEqual('x[a] > y[a]{}');
css = s('polyfill-next-selector {content: "x > y"} z {}', 'a');
expect(css).toEqual('x[a] > y[a]{}');
css = s(`polyfill-next-selector {content: 'button[priority="1"]'} z {}`, 'a');
expect(css).toEqual('button[priority="1"][a]{}');
});
it('should support polyfill-unscoped-rule', () => {
let css = s('polyfill-unscoped-rule {content: \'#menu > .bar\';color: blue;}', 'a');
expect(css).toContain('#menu > .bar {;color:blue;}');
css = s('polyfill-unscoped-rule {content: "#menu > .bar";color: blue;}', 'a');
expect(css).toContain('#menu > .bar {;color:blue;}');
css = s(`polyfill-unscoped-rule {content: 'button[priority="1"]'}`, 'a');
expect(css).toContain('button[priority="1"] {}');
});
it('should support multiple instances polyfill-unscoped-rule', () => {
const css =
s('polyfill-unscoped-rule {content: \'foo\';color: blue;}' +
'polyfill-unscoped-rule {content: \'bar\';color: blue;}',
'a');
expect(css).toContain('foo {;color:blue;}');
expect(css).toContain('bar {;color:blue;}');
});
it('should support polyfill-rule', () => {
let css = s('polyfill-rule {content: \':host.foo .bar\';color: blue;}', 'a', 'a-host');
expect(css).toEqual('.foo[a-host] .bar[a] {;color:blue;}');
css = s('polyfill-rule {content: ":host.foo .bar";color:blue;}', 'a', 'a-host');
expect(css).toEqual('.foo[a-host] .bar[a] {;color:blue;}');
css = s(`polyfill-rule {content: 'button[priority="1"]'}`, 'a', 'a-host');
expect(css).toEqual('button[priority="1"][a] {}');
});
it('should handle ::shadow', () => {
const css = s('x::shadow > y {}', 'a');
expect(css).toEqual('x[a] > y[a] {}');
});
it('should handle /deep/', () => {
const css = s('x /deep/ y {}', 'a');
expect(css).toEqual('x[a] y {}');
});
it('should handle >>>', () => {
const css = s('x >>> y {}', 'a');
expect(css).toEqual('x[a] y {}');
});
it('should pass through @import directives', () => {
const styleStr = '@import url("https://fonts.googleapis.com/css?family=Roboto");';
const css = s(styleStr, 'a');
expect(css).toEqual(styleStr);
});
it('should shim rules after @import', () => {
const styleStr = '@import url("a"); div {}';
const css = s(styleStr, 'a');
expect(css).toEqual('@import url("a"); div[a] {}');
});
it('should leave calc() unchanged', () => {
const styleStr = 'div {height:calc(100% - 55px);}';
const css = s(styleStr, 'a');
expect(css).toEqual('div[a] {height:calc(100% - 55px);}');
});
it('should strip comments', () => { expect(s('/* x */b {c}', 'a')).toEqual('b[a] {c}'); });
it('should ignore special characters in comments',
() => { expect(s('/* {;, */b {c}', 'a')).toEqual('b[a] {c}'); });
it('should support multiline comments',
() => { expect(s('/* \n */b {c}', 'a')).toEqual('b[a] {c}'); });
it('should keep sourceMappingURL comments', () => {
expect(s('b {c}/*# sourceMappingURL=data:x */', 'a'))
.toEqual('b[a] {c}/*# sourceMappingURL=data:x */');
expect(s('b {c}/* #sourceMappingURL=data:x */', 'a'))
.toEqual('b[a] {c}/* #sourceMappingURL=data:x */');
});
});
describe('processRules', () => {
describe('parse rules', () => {
function captureRules(input: string): CssRule[] {
const result: CssRule[] = [];
processRules(input, (cssRule) => {
result.push(cssRule);
return cssRule;
});
return result;
}
it('should work with empty css', () => { expect(captureRules('')).toEqual([]); });
it('should capture a rule without body',
() => { expect(captureRules('a;')).toEqual([new CssRule('a', '')]); });
it('should capture css rules with body',
() => { expect(captureRules('a {b}')).toEqual([new CssRule('a', 'b')]); });
it('should capture css rules with nested rules', () => {
expect(captureRules('a {b {c}} d {e}')).toEqual([
new CssRule('a', 'b {c}'), new CssRule('d', 'e')
]);
});
it('should capture multiple rules where some have no body', () => {
expect(captureRules('@import a ; b {c}')).toEqual([
new CssRule('@import a', ''), new CssRule('b', 'c')
]);
});
});
describe('modify rules', () => {
it('should allow to change the selector while preserving whitespaces', () => {
expect(processRules(
'@import a; b {c {d}} e {f}',
(cssRule: CssRule) => new CssRule(cssRule.selector + '2', cssRule.content)))
.toEqual('@import a2; b2 {c {d}} e2 {f}');
});
it('should allow to change the content', () => {
expect(processRules(
'a {b}',
(cssRule: CssRule) => new CssRule(cssRule.selector, cssRule.content + '2')))
.toEqual('a {b2}');
});
});
});
}
| modules/@angular/compiler/test/shadow_css_spec.ts | 1 | https://github.com/angular/angular/commit/aa92512ac6869a575e48a94e508411ec349fa3eb | [
0.9491586089134216,
0.03496202453970909,
0.0001650956692174077,
0.00017231011588592082,
0.1674930602312088
] |
{
"id": 1,
"code_window": [
" it('should handle no context',\n",
" () => { expect(s(':host {}', 'a', 'a-host')).toEqual('[a-host] {}'); });\n",
"\n",
" it('should handle tag selector', () => {\n",
" expect(s(':host(ul) {}', 'a', 'a-host')).toEqual('ul[a-host] {}');\n",
"\n",
" });\n",
"\n",
" it('should handle class selector',\n",
" () => { expect(s(':host(.x) {}', 'a', 'a-host')).toEqual('.x[a-host] {}'); });\n",
"\n",
" it('should handle attribute selector', () => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" it('should handle tag selector',\n",
" () => { expect(s(':host(ul) {}', 'a', 'a-host')).toEqual('ul[a-host] {}'); });\n"
],
"file_path": "modules/@angular/compiler/test/shadow_css_spec.ts",
"type": "replace",
"edit_start_line_idx": 114
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {MapWrapper} from '../facade/collection';
import {Type} from '../type';
import {PlatformReflectionCapabilities} from './platform_reflection_capabilities';
import {ReflectorReader} from './reflector_reader';
import {GetterFn, MethodFn, SetterFn} from './types';
export {PlatformReflectionCapabilities} from './platform_reflection_capabilities';
export {GetterFn, MethodFn, SetterFn} from './types';
/**
* Reflective information about a symbol, including annotations, interfaces, and other metadata.
*/
export class ReflectionInfo {
constructor(
public annotations?: any[], public parameters?: any[][], public factory?: Function,
public interfaces?: any[], public propMetadata?: {[key: string]: any[]}) {}
}
/**
* Provides access to reflection data about symbols. Used internally by Angular
* to power dependency injection and compilation.
*/
export class Reflector extends ReflectorReader {
/** @internal */
_injectableInfo = new Map<any, ReflectionInfo>();
/** @internal */
_getters = new Map<string, GetterFn>();
/** @internal */
_setters = new Map<string, SetterFn>();
/** @internal */
_methods = new Map<string, MethodFn>();
/** @internal */
_usedKeys: Set<any> = null;
constructor(public reflectionCapabilities: PlatformReflectionCapabilities) { super(); }
updateCapabilities(caps: PlatformReflectionCapabilities) { this.reflectionCapabilities = caps; }
isReflectionEnabled(): boolean { return this.reflectionCapabilities.isReflectionEnabled(); }
/**
* Causes `this` reflector to track keys used to access
* {@link ReflectionInfo} objects.
*/
trackUsage(): void { this._usedKeys = new Set(); }
/**
* Lists types for which reflection information was not requested since
* {@link #trackUsage} was called. This list could later be audited as
* potential dead code.
*/
listUnusedKeys(): any[] {
if (!this._usedKeys) {
throw new Error('Usage tracking is disabled');
}
const allTypes = MapWrapper.keys(this._injectableInfo);
return allTypes.filter(key => !this._usedKeys.has(key));
}
registerFunction(func: Function, funcInfo: ReflectionInfo): void {
this._injectableInfo.set(func, funcInfo);
}
registerType(type: Type<any>, typeInfo: ReflectionInfo): void {
this._injectableInfo.set(type, typeInfo);
}
registerGetters(getters: {[key: string]: GetterFn}): void { _mergeMaps(this._getters, getters); }
registerSetters(setters: {[key: string]: SetterFn}): void { _mergeMaps(this._setters, setters); }
registerMethods(methods: {[key: string]: MethodFn}): void { _mergeMaps(this._methods, methods); }
factory(type: Type<any>): Function {
if (this._containsReflectionInfo(type)) {
return this._getReflectionInfo(type).factory || null;
}
return this.reflectionCapabilities.factory(type);
}
parameters(typeOrFunc: Type<any>): any[][] {
if (this._injectableInfo.has(typeOrFunc)) {
return this._getReflectionInfo(typeOrFunc).parameters || [];
}
return this.reflectionCapabilities.parameters(typeOrFunc);
}
annotations(typeOrFunc: Type<any>): any[] {
if (this._injectableInfo.has(typeOrFunc)) {
return this._getReflectionInfo(typeOrFunc).annotations || [];
}
return this.reflectionCapabilities.annotations(typeOrFunc);
}
propMetadata(typeOrFunc: Type<any>): {[key: string]: any[]} {
if (this._injectableInfo.has(typeOrFunc)) {
return this._getReflectionInfo(typeOrFunc).propMetadata || {};
}
return this.reflectionCapabilities.propMetadata(typeOrFunc);
}
interfaces(type: Type<any>): any[] {
if (this._injectableInfo.has(type)) {
return this._getReflectionInfo(type).interfaces || [];
}
return this.reflectionCapabilities.interfaces(type);
}
hasLifecycleHook(type: any, lcInterface: Type<any>, lcProperty: string): boolean {
if (this.interfaces(type).indexOf(lcInterface) !== -1) {
return true;
}
return this.reflectionCapabilities.hasLifecycleHook(type, lcInterface, lcProperty);
}
getter(name: string): GetterFn {
return this._getters.has(name) ? this._getters.get(name) :
this.reflectionCapabilities.getter(name);
}
setter(name: string): SetterFn {
return this._setters.has(name) ? this._setters.get(name) :
this.reflectionCapabilities.setter(name);
}
method(name: string): MethodFn {
return this._methods.has(name) ? this._methods.get(name) :
this.reflectionCapabilities.method(name);
}
/** @internal */
_getReflectionInfo(typeOrFunc: any): ReflectionInfo {
if (this._usedKeys) {
this._usedKeys.add(typeOrFunc);
}
return this._injectableInfo.get(typeOrFunc);
}
/** @internal */
_containsReflectionInfo(typeOrFunc: any) { return this._injectableInfo.has(typeOrFunc); }
importUri(type: any): string { return this.reflectionCapabilities.importUri(type); }
resolveIdentifier(name: string, moduleUrl: string, runtime: any): any {
return this.reflectionCapabilities.resolveIdentifier(name, moduleUrl, runtime);
}
resolveEnum(identifier: any, name: string): any {
return this.reflectionCapabilities.resolveEnum(identifier, name);
}
}
function _mergeMaps(target: Map<string, Function>, config: {[key: string]: Function}): void {
Object.keys(config).forEach(k => { target.set(k, config[k]); });
}
| modules/@angular/core/src/reflection/reflector.ts | 0 | https://github.com/angular/angular/commit/aa92512ac6869a575e48a94e508411ec349fa3eb | [
0.00017612133524380624,
0.00017235474660992622,
0.00016579088696744293,
0.00017330472473986447,
0.0000029018649456702406
] |
{
"id": 1,
"code_window": [
" it('should handle no context',\n",
" () => { expect(s(':host {}', 'a', 'a-host')).toEqual('[a-host] {}'); });\n",
"\n",
" it('should handle tag selector', () => {\n",
" expect(s(':host(ul) {}', 'a', 'a-host')).toEqual('ul[a-host] {}');\n",
"\n",
" });\n",
"\n",
" it('should handle class selector',\n",
" () => { expect(s(':host(.x) {}', 'a', 'a-host')).toEqual('.x[a-host] {}'); });\n",
"\n",
" it('should handle attribute selector', () => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" it('should handle tag selector',\n",
" () => { expect(s(':host(ul) {}', 'a', 'a-host')).toEqual('ul[a-host] {}'); });\n"
],
"file_path": "modules/@angular/compiler/test/shadow_css_spec.ts",
"type": "replace",
"edit_start_line_idx": 114
} | #! /usr/bin/env node
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* TODO: remove this file when license is included in RxJS bundles.
* https://github.com/ReactiveX/RxJS/issues/1067
*
* This script runs after bundles have already been copied to the build-path,
* to prepend the license to each bundle.
**/
var fs = require('fs');
var args = require('minimist')(process.argv);
var license = fs.readFileSync(args['license-path']);
// Make the license block into a JS comment
license = `/**
${license}
**/
`;
var bundles =
fs.readdirSync(args['build-path'])
// Match files that begin with Rx and end with js
.filter(bundle => /^Rx\.?.*\.js$/.test(bundle))
// Load file contents
.map(bundle => {
return {
path: bundle,
contents: fs.readFileSync(`${args['build-path']}/${bundle}`).toString()
};
})
// Concatenate license to bundle
.map(bundle => { return {path: bundle.path, contents: `${license}${bundle.contents}`}; })
// Write file to disk
.forEach(
bundle => fs.writeFileSync(`${args['build-path']}/${bundle.path}`, bundle.contents));
| tools/code.angularjs.org/add-license-to-rx.js | 0 | https://github.com/angular/angular/commit/aa92512ac6869a575e48a94e508411ec349fa3eb | [
0.0001778242876753211,
0.0001735883270157501,
0.00017037476936820894,
0.0001735802215989679,
0.0000024511471110599814
] |
{
"id": 1,
"code_window": [
" it('should handle no context',\n",
" () => { expect(s(':host {}', 'a', 'a-host')).toEqual('[a-host] {}'); });\n",
"\n",
" it('should handle tag selector', () => {\n",
" expect(s(':host(ul) {}', 'a', 'a-host')).toEqual('ul[a-host] {}');\n",
"\n",
" });\n",
"\n",
" it('should handle class selector',\n",
" () => { expect(s(':host(.x) {}', 'a', 'a-host')).toEqual('.x[a-host] {}'); });\n",
"\n",
" it('should handle attribute selector', () => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" it('should handle tag selector',\n",
" () => { expect(s(':host(ul) {}', 'a', 'a-host')).toEqual('ul[a-host] {}'); });\n"
],
"file_path": "modules/@angular/compiler/test/shadow_css_spec.ts",
"type": "replace",
"edit_start_line_idx": 114
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {RouterOutlet} from './directives/router_outlet';
/**
* @whatItDoes Contains all the router outlets created in a component.
*
* @stable
*/
export class RouterOutletMap {
/** @internal */
_outlets: {[name: string]: RouterOutlet} = {};
/**
* Adds an outlet to this map.
*/
registerOutlet(name: string, outlet: RouterOutlet): void { this._outlets[name] = outlet; }
/**
* Removes an outlet from this map.
*/
removeOutlet(name: string): void { this._outlets[name] = undefined; }
}
| modules/@angular/router/src/router_outlet_map.ts | 0 | https://github.com/angular/angular/commit/aa92512ac6869a575e48a94e508411ec349fa3eb | [
0.0001746920170262456,
0.00017312973795924336,
0.0001709669886622578,
0.00017373022274114192,
0.0000015789007647981634
] |
{
"id": 2,
"code_window": [
" it('should handle multiple attribute selectors', () => {\n",
" expect(s(':host([a=\"b\"],[c=d]) {}', 'a', 'a-host'))\n",
" .toEqual('[a=\"b\"][a-host], [c=\"d\"][a-host] {}');\n",
" });\n",
" });\n",
"\n",
" describe((':host-context'), () => {\n",
" it('should handle tag selector', () => {\n",
" expect(s(':host-context(div) {}', 'a', 'a-host')).toEqual('div[a-host], div [a-host] {}');\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
" it('should handle pseudo selector', () => {\n",
" expect(s(':host(:before) {}', 'a', 'a-host')).toEqual('[a-host]:before {}');\n",
" expect(s(':host:before {}', 'a', 'a-host')).toEqual('[a-host]:before {}');\n",
" });\n"
],
"file_path": "modules/@angular/compiler/test/shadow_css_spec.ts",
"type": "add",
"edit_start_line_idx": 143
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {CssRule, ShadowCss, processRules} from '@angular/compiler/src/shadow_css';
import {normalizeCSS} from '@angular/platform-browser/testing/browser_util';
export function main() {
describe('ShadowCss', function() {
function s(css: string, contentAttr: string, hostAttr: string = '') {
const shadowCss = new ShadowCss();
const shim = shadowCss.shimCssText(css, contentAttr, hostAttr);
const nlRegexp = /\n/g;
return normalizeCSS(shim.replace(nlRegexp, ''));
}
it('should handle empty string', () => { expect(s('', 'a')).toEqual(''); });
it('should add an attribute to every rule', () => {
const css = 'one {color: red;}two {color: red;}';
const expected = 'one[a] {color:red;}two[a] {color:red;}';
expect(s(css, 'a')).toEqual(expected);
});
it('should handle invalid css', () => {
const css = 'one {color: red;}garbage';
const expected = 'one[a] {color:red;}garbage';
expect(s(css, 'a')).toEqual(expected);
});
it('should add an attribute to every selector', () => {
const css = 'one, two {color: red;}';
const expected = 'one[a], two[a] {color:red;}';
expect(s(css, 'a')).toEqual(expected);
});
it('should support newlines in the selector and content ', () => {
const css = 'one, \ntwo {\ncolor: red;}';
const expected = 'one[a], two[a] {color:red;}';
expect(s(css, 'a')).toEqual(expected);
});
it('should handle media rules', () => {
const css = '@media screen and (max-width:800px, max-height:100%) {div {font-size:50px;}}';
const expected =
'@media screen and (max-width:800px, max-height:100%) {div[a] {font-size:50px;}}';
expect(s(css, 'a')).toEqual(expected);
});
it('should handle page rules', () => {
const css = '@page {div {font-size:50px;}}';
const expected = '@page {div[a] {font-size:50px;}}';
expect(s(css, 'a')).toEqual(expected);
});
it('should handle document rules', () => {
const css = '@document url(http://www.w3.org/) {div {font-size:50px;}}';
const expected = '@document url(http://www.w3.org/) {div[a] {font-size:50px;}}';
expect(s(css, 'a')).toEqual(expected);
});
it('should handle media rules with simple rules', () => {
const css = '@media screen and (max-width: 800px) {div {font-size: 50px;}} div {}';
const expected = '@media screen and (max-width:800px) {div[a] {font-size:50px;}} div[a] {}';
expect(s(css, 'a')).toEqual(expected);
});
it('should handle support rules', () => {
const css = '@supports (display: flex) {section {display: flex;}}';
const expected = '@supports (display:flex) {section[a] {display:flex;}}';
expect(s(css, 'a')).toEqual(expected);
});
// Check that the browser supports unprefixed CSS animation
it('should handle keyframes rules', () => {
const css = '@keyframes foo {0% {transform:translate(-50%) scaleX(0);}}';
expect(s(css, 'a')).toEqual(css);
});
it('should handle -webkit-keyframes rules', () => {
const css = '@-webkit-keyframes foo {0% {-webkit-transform:translate(-50%) scaleX(0);}}';
expect(s(css, 'a')).toEqual(css);
});
it('should handle complicated selectors', () => {
expect(s('one::before {}', 'a')).toEqual('one[a]::before {}');
expect(s('one two {}', 'a')).toEqual('one[a] two[a] {}');
expect(s('one > two {}', 'a')).toEqual('one[a] > two[a] {}');
expect(s('one + two {}', 'a')).toEqual('one[a] + two[a] {}');
expect(s('one ~ two {}', 'a')).toEqual('one[a] ~ two[a] {}');
const res = s('.one.two > three {}', 'a'); // IE swap classes
expect(res == '.one.two[a] > three[a] {}' || res == '.two.one[a] > three[a] {}')
.toEqual(true);
expect(s('one[attr="value"] {}', 'a')).toEqual('one[attr="value"][a] {}');
expect(s('one[attr=value] {}', 'a')).toEqual('one[attr="value"][a] {}');
expect(s('one[attr^="value"] {}', 'a')).toEqual('one[attr^="value"][a] {}');
expect(s('one[attr$="value"] {}', 'a')).toEqual('one[attr$="value"][a] {}');
expect(s('one[attr*="value"] {}', 'a')).toEqual('one[attr*="value"][a] {}');
expect(s('one[attr|="value"] {}', 'a')).toEqual('one[attr|="value"][a] {}');
expect(s('one[attr~="value"] {}', 'a')).toEqual('one[attr~="value"][a] {}');
expect(s('one[attr="va lue"] {}', 'a')).toEqual('one[attr="va lue"][a] {}');
expect(s('one[attr] {}', 'a')).toEqual('one[attr][a] {}');
expect(s('[is="one"] {}', 'a')).toEqual('[is="one"][a] {}');
});
describe((':host'), () => {
it('should handle no context',
() => { expect(s(':host {}', 'a', 'a-host')).toEqual('[a-host] {}'); });
it('should handle tag selector', () => {
expect(s(':host(ul) {}', 'a', 'a-host')).toEqual('ul[a-host] {}');
});
it('should handle class selector',
() => { expect(s(':host(.x) {}', 'a', 'a-host')).toEqual('.x[a-host] {}'); });
it('should handle attribute selector', () => {
expect(s(':host([a="b"]) {}', 'a', 'a-host')).toEqual('[a="b"][a-host] {}');
expect(s(':host([a=b]) {}', 'a', 'a-host')).toEqual('[a="b"][a-host] {}');
});
it('should handle multiple tag selectors', () => {
expect(s(':host(ul,li) {}', 'a', 'a-host')).toEqual('ul[a-host], li[a-host] {}');
expect(s(':host(ul,li) > .z {}', 'a', 'a-host'))
.toEqual('ul[a-host] > .z[a], li[a-host] > .z[a] {}');
});
it('should handle multiple class selectors', () => {
expect(s(':host(.x,.y) {}', 'a', 'a-host')).toEqual('.x[a-host], .y[a-host] {}');
expect(s(':host(.x,.y) > .z {}', 'a', 'a-host'))
.toEqual('.x[a-host] > .z[a], .y[a-host] > .z[a] {}');
});
it('should handle multiple attribute selectors', () => {
expect(s(':host([a="b"],[c=d]) {}', 'a', 'a-host'))
.toEqual('[a="b"][a-host], [c="d"][a-host] {}');
});
});
describe((':host-context'), () => {
it('should handle tag selector', () => {
expect(s(':host-context(div) {}', 'a', 'a-host')).toEqual('div[a-host], div [a-host] {}');
expect(s(':host-context(ul) > .y {}', 'a', 'a-host'))
.toEqual('ul[a-host] > .y[a], ul [a-host] > .y[a] {}');
});
it('should handle class selector', () => {
expect(s(':host-context(.x) {}', 'a', 'a-host')).toEqual('.x[a-host], .x [a-host] {}');
expect(s(':host-context(.x) > .y {}', 'a', 'a-host'))
.toEqual('.x[a-host] > .y[a], .x [a-host] > .y[a] {}');
});
it('should handle attribute selector', () => {
expect(s(':host-context([a="b"]) {}', 'a', 'a-host'))
.toEqual('[a="b"][a-host], [a="b"] [a-host] {}');
expect(s(':host-context([a=b]) {}', 'a', 'a-host'))
.toEqual('[a=b][a-host], [a="b"] [a-host] {}');
});
});
it('should support polyfill-next-selector', () => {
let css = s('polyfill-next-selector {content: \'x > y\'} z {}', 'a');
expect(css).toEqual('x[a] > y[a]{}');
css = s('polyfill-next-selector {content: "x > y"} z {}', 'a');
expect(css).toEqual('x[a] > y[a]{}');
css = s(`polyfill-next-selector {content: 'button[priority="1"]'} z {}`, 'a');
expect(css).toEqual('button[priority="1"][a]{}');
});
it('should support polyfill-unscoped-rule', () => {
let css = s('polyfill-unscoped-rule {content: \'#menu > .bar\';color: blue;}', 'a');
expect(css).toContain('#menu > .bar {;color:blue;}');
css = s('polyfill-unscoped-rule {content: "#menu > .bar";color: blue;}', 'a');
expect(css).toContain('#menu > .bar {;color:blue;}');
css = s(`polyfill-unscoped-rule {content: 'button[priority="1"]'}`, 'a');
expect(css).toContain('button[priority="1"] {}');
});
it('should support multiple instances polyfill-unscoped-rule', () => {
const css =
s('polyfill-unscoped-rule {content: \'foo\';color: blue;}' +
'polyfill-unscoped-rule {content: \'bar\';color: blue;}',
'a');
expect(css).toContain('foo {;color:blue;}');
expect(css).toContain('bar {;color:blue;}');
});
it('should support polyfill-rule', () => {
let css = s('polyfill-rule {content: \':host.foo .bar\';color: blue;}', 'a', 'a-host');
expect(css).toEqual('.foo[a-host] .bar[a] {;color:blue;}');
css = s('polyfill-rule {content: ":host.foo .bar";color:blue;}', 'a', 'a-host');
expect(css).toEqual('.foo[a-host] .bar[a] {;color:blue;}');
css = s(`polyfill-rule {content: 'button[priority="1"]'}`, 'a', 'a-host');
expect(css).toEqual('button[priority="1"][a] {}');
});
it('should handle ::shadow', () => {
const css = s('x::shadow > y {}', 'a');
expect(css).toEqual('x[a] > y[a] {}');
});
it('should handle /deep/', () => {
const css = s('x /deep/ y {}', 'a');
expect(css).toEqual('x[a] y {}');
});
it('should handle >>>', () => {
const css = s('x >>> y {}', 'a');
expect(css).toEqual('x[a] y {}');
});
it('should pass through @import directives', () => {
const styleStr = '@import url("https://fonts.googleapis.com/css?family=Roboto");';
const css = s(styleStr, 'a');
expect(css).toEqual(styleStr);
});
it('should shim rules after @import', () => {
const styleStr = '@import url("a"); div {}';
const css = s(styleStr, 'a');
expect(css).toEqual('@import url("a"); div[a] {}');
});
it('should leave calc() unchanged', () => {
const styleStr = 'div {height:calc(100% - 55px);}';
const css = s(styleStr, 'a');
expect(css).toEqual('div[a] {height:calc(100% - 55px);}');
});
it('should strip comments', () => { expect(s('/* x */b {c}', 'a')).toEqual('b[a] {c}'); });
it('should ignore special characters in comments',
() => { expect(s('/* {;, */b {c}', 'a')).toEqual('b[a] {c}'); });
it('should support multiline comments',
() => { expect(s('/* \n */b {c}', 'a')).toEqual('b[a] {c}'); });
it('should keep sourceMappingURL comments', () => {
expect(s('b {c}/*# sourceMappingURL=data:x */', 'a'))
.toEqual('b[a] {c}/*# sourceMappingURL=data:x */');
expect(s('b {c}/* #sourceMappingURL=data:x */', 'a'))
.toEqual('b[a] {c}/* #sourceMappingURL=data:x */');
});
});
describe('processRules', () => {
describe('parse rules', () => {
function captureRules(input: string): CssRule[] {
const result: CssRule[] = [];
processRules(input, (cssRule) => {
result.push(cssRule);
return cssRule;
});
return result;
}
it('should work with empty css', () => { expect(captureRules('')).toEqual([]); });
it('should capture a rule without body',
() => { expect(captureRules('a;')).toEqual([new CssRule('a', '')]); });
it('should capture css rules with body',
() => { expect(captureRules('a {b}')).toEqual([new CssRule('a', 'b')]); });
it('should capture css rules with nested rules', () => {
expect(captureRules('a {b {c}} d {e}')).toEqual([
new CssRule('a', 'b {c}'), new CssRule('d', 'e')
]);
});
it('should capture multiple rules where some have no body', () => {
expect(captureRules('@import a ; b {c}')).toEqual([
new CssRule('@import a', ''), new CssRule('b', 'c')
]);
});
});
describe('modify rules', () => {
it('should allow to change the selector while preserving whitespaces', () => {
expect(processRules(
'@import a; b {c {d}} e {f}',
(cssRule: CssRule) => new CssRule(cssRule.selector + '2', cssRule.content)))
.toEqual('@import a2; b2 {c {d}} e2 {f}');
});
it('should allow to change the content', () => {
expect(processRules(
'a {b}',
(cssRule: CssRule) => new CssRule(cssRule.selector, cssRule.content + '2')))
.toEqual('a {b2}');
});
});
});
}
| modules/@angular/compiler/test/shadow_css_spec.ts | 1 | https://github.com/angular/angular/commit/aa92512ac6869a575e48a94e508411ec349fa3eb | [
0.44020211696624756,
0.015595214441418648,
0.0001658025721553713,
0.00017434090841561556,
0.07758133858442307
] |
{
"id": 2,
"code_window": [
" it('should handle multiple attribute selectors', () => {\n",
" expect(s(':host([a=\"b\"],[c=d]) {}', 'a', 'a-host'))\n",
" .toEqual('[a=\"b\"][a-host], [c=\"d\"][a-host] {}');\n",
" });\n",
" });\n",
"\n",
" describe((':host-context'), () => {\n",
" it('should handle tag selector', () => {\n",
" expect(s(':host-context(div) {}', 'a', 'a-host')).toEqual('div[a-host], div [a-host] {}');\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
" it('should handle pseudo selector', () => {\n",
" expect(s(':host(:before) {}', 'a', 'a-host')).toEqual('[a-host]:before {}');\n",
" expect(s(':host:before {}', 'a', 'a-host')).toEqual('[a-host]:before {}');\n",
" });\n"
],
"file_path": "modules/@angular/compiler/test/shadow_css_spec.ts",
"type": "add",
"edit_start_line_idx": 143
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {INTERNAL_SERVER_PLATFORM_PROVIDERS} from './server';
export var __platform_server_private__:
{INTERNAL_SERVER_PLATFORM_PROVIDERS: typeof INTERNAL_SERVER_PLATFORM_PROVIDERS} = {
INTERNAL_SERVER_PLATFORM_PROVIDERS: INTERNAL_SERVER_PLATFORM_PROVIDERS
};
| modules/@angular/platform-server/src/private_export.ts | 0 | https://github.com/angular/angular/commit/aa92512ac6869a575e48a94e508411ec349fa3eb | [
0.0015666397521272302,
0.0008696091827005148,
0.00017257864237762988,
0.0008696091827005148,
0.0006970305694267154
] |
{
"id": 2,
"code_window": [
" it('should handle multiple attribute selectors', () => {\n",
" expect(s(':host([a=\"b\"],[c=d]) {}', 'a', 'a-host'))\n",
" .toEqual('[a=\"b\"][a-host], [c=\"d\"][a-host] {}');\n",
" });\n",
" });\n",
"\n",
" describe((':host-context'), () => {\n",
" it('should handle tag selector', () => {\n",
" expect(s(':host-context(div) {}', 'a', 'a-host')).toEqual('div[a-host], div [a-host] {}');\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
" it('should handle pseudo selector', () => {\n",
" expect(s(':host(:before) {}', 'a', 'a-host')).toEqual('[a-host]:before {}');\n",
" expect(s(':host:before {}', 'a', 'a-host')).toEqual('[a-host]:before {}');\n",
" });\n"
],
"file_path": "modules/@angular/compiler/test/shadow_css_spec.ts",
"type": "add",
"edit_start_line_idx": 143
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
export function supportsState(): boolean {
return !!window.history.pushState;
} | modules/@angular/platform-browser/src/browser/location/history.ts | 0 | https://github.com/angular/angular/commit/aa92512ac6869a575e48a94e508411ec349fa3eb | [
0.00017438297800254077,
0.00017171533545479178,
0.0001690476929070428,
0.00017171533545479178,
0.000002667642547748983
] |
{
"id": 2,
"code_window": [
" it('should handle multiple attribute selectors', () => {\n",
" expect(s(':host([a=\"b\"],[c=d]) {}', 'a', 'a-host'))\n",
" .toEqual('[a=\"b\"][a-host], [c=\"d\"][a-host] {}');\n",
" });\n",
" });\n",
"\n",
" describe((':host-context'), () => {\n",
" it('should handle tag selector', () => {\n",
" expect(s(':host-context(div) {}', 'a', 'a-host')).toEqual('div[a-host], div [a-host] {}');\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
" it('should handle pseudo selector', () => {\n",
" expect(s(':host(:before) {}', 'a', 'a-host')).toEqual('[a-host]:before {}');\n",
" expect(s(':host:before {}', 'a', 'a-host')).toEqual('[a-host]:before {}');\n",
" });\n"
],
"file_path": "modules/@angular/compiler/test/shadow_css_spec.ts",
"type": "add",
"edit_start_line_idx": 143
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
module.exports = function(gulp, plugins, config) {
return function(done) { del(config.path, done); };
};
| tools/build/benchpress.js | 0 | https://github.com/angular/angular/commit/aa92512ac6869a575e48a94e508411ec349fa3eb | [
0.00017116287199314684,
0.00017022909014485776,
0.00016929529374465346,
0.00017022909014485776,
9.337891242466867e-7
] |
{
"id": 0,
"code_window": [
"The CloudWatch plugin enables you to monitor and troubleshoot applications across multiple regional accounts. Using cross-account observability, you can seamlessly search, visualize and analyze metrics and logs without worrying about account boundaries.\n",
"\n",
"To use this feature, configure in the [AWS console under Cloudwatch Settings](https://aws.amazon.com/blogs/aws/new-amazon-cloudwatch-cross-account-observability/), a monitoring and source account, and then add the necessary IAM permissions as described above.\n"
],
"labels": [
"keep",
"keep",
"add"
],
"after_edit": [
"\n",
"## CloudWatch Logs data protection\n",
"\n",
"CloudWatch Logs can safeguard data by using log group data protection policies. If you have data protection enabled for a log group, then any sensitive data that matches the data identifiers you've selected will be masked. In order to view masked data you will need to have the `logs:Unmask` IAM permission enabled. See the AWS documentation on how to [help protect sensitive log data with masking](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/mask-sensitive-log-data.html) to learn more about this."
],
"file_path": "docs/sources/datasources/aws-cloudwatch/_index.md",
"type": "add",
"edit_start_line_idx": 377
} | import { css, cx } from '@emotion/css';
import { stripIndent, stripIndents } from 'common-tags';
import Prism from 'prismjs';
import React, { PureComponent } from 'react';
import { QueryEditorHelpProps } from '@grafana/data';
import { flattenTokens } from '@grafana/ui/src/slate-plugins/slate-prism';
import tokenizer from '../language/cloudwatch-logs/syntax';
import { CloudWatchQuery } from '../types';
interface QueryExample {
category: string;
examples: Array<{
title: string;
expr: string;
}>;
}
const CLIQ_EXAMPLES: QueryExample[] = [
{
category: 'Lambda',
examples: [
{
title: 'View latency statistics for 5-minute intervals',
expr: stripIndents`filter @type = "REPORT" |
stats avg(@duration), max(@duration), min(@duration) by bin(5m)`,
},
{
title: 'Determine the amount of overprovisioned memory',
expr: stripIndent`
filter @type = "REPORT" |
stats max(@memorySize / 1024 / 1024) as provisonedMemoryMB,
min(@maxMemoryUsed / 1024 / 1024) as smallestMemoryRequestMB,
avg(@maxMemoryUsed / 1024 / 1024) as avgMemoryUsedMB,
max(@maxMemoryUsed / 1024 / 1024) as maxMemoryUsedMB,
provisonedMemoryMB - maxMemoryUsedMB as overProvisionedMB`,
},
{
title: 'Find the most expensive requests',
expr: stripIndents`filter @type = "REPORT" |
fields @requestId, @billedDuration |
sort by @billedDuration desc`,
},
],
},
{
category: 'VPC Flow Logs',
examples: [
{
title: 'Average, min, and max byte transfers by source and destination IP addresses',
expr: `stats avg(bytes), min(bytes), max(bytes) by srcAddr, dstAddr`,
},
{
title: 'IP addresses using UDP transfer protocol',
expr: 'filter protocol=17 | stats count(*) by srcAddr',
},
{
title: 'Top 10 byte transfers by source and destination IP addresses',
expr: stripIndents`stats sum(bytes) as bytesTransferred by srcAddr, dstAddr |
sort bytesTransferred desc |
limit 10`,
},
{
title: 'Top 20 source IP addresses with highest number of rejected requests',
expr: stripIndents`filter action="REJECT" |
stats count(*) as numRejections by srcAddr |
sort numRejections desc |
limit 20`,
},
],
},
{
category: 'CloudTrail',
examples: [
{
title: 'Number of log entries by service, event type, and region',
expr: 'stats count(*) by eventSource, eventName, awsRegion',
},
{
title: 'Number of log entries by region and EC2 event type',
expr: stripIndents`filter eventSource="ec2.amazonaws.com" |
stats count(*) as eventCount by eventName, awsRegion |
sort eventCount desc`,
},
{
title: 'Regions, usernames, and ARNs of newly created IAM users',
expr: stripIndents`filter eventName="CreateUser" |
fields awsRegion, requestParameters.userName, responseElements.user.arn`,
},
],
},
{
category: 'Common Queries',
examples: [
{
title: '25 most recently added log events',
expr: stripIndents`fields @timestamp, @message |
sort @timestamp desc |
limit 25`,
},
{
title: 'Number of exceptions logged every 5 minutes',
expr: stripIndents`filter @message like /Exception/ |
stats count(*) as exceptionCount by bin(5m) |
sort exceptionCount desc`,
},
{
title: 'List of log events that are not exceptions',
expr: 'fields @message | filter @message not like /Exception/',
},
],
},
{
category: 'Route 53',
examples: [
{
title: 'Number of requests received every 10 minutes by edge location',
expr: 'stats count(*) by queryType, bin(10m)',
},
{
title: 'Number of unsuccessful requests by domain',
expr: 'filter responseCode="SERVFAIL" | stats count(*) by queryName',
},
{
title: 'Number of requests received every 10 minutes by edge location',
expr: 'stats count(*) as numRequests by resolverIp | sort numRequests desc | limit 10',
},
],
},
{
category: 'AWS AppSync',
examples: [
{
title: 'Number of unique HTTP status codes',
expr: stripIndents`fields ispresent(graphQLAPIId) as isApi |
filter isApi |
filter logType = "RequestSummary" |
stats count() as statusCount by statusCode |
sort statusCount desc`,
},
{
title: 'Top 10 resolvers with maximum latency',
expr: stripIndents`fields resolverArn, duration |
filter logType = "Tracing" |
sort duration desc |
limit 10`,
},
{
title: 'Most frequently invoked resolvers',
expr: stripIndents`fields ispresent(resolverArn) as isRes |
stats count() as invocationCount by resolverArn |
filter isRes |
filter logType = "Tracing" |
sort invocationCount desc |
limit 10`,
},
{
title: 'Resolvers with most errors in mapping templates',
expr: stripIndents`fields ispresent(resolverArn) as isRes |
stats count() as errorCount by resolverArn, logType |
filter isRes and (logType = "RequestMapping" or logType = "ResponseMapping") and fieldInError |
sort errorCount desc |
limit 10`,
},
{
title: 'Field latency statistics',
expr: stripIndents`fields requestId, latency |
filter logType = "RequestSummary" |
sort latency desc |
limit 10`,
},
{
title: 'Resolver latency statistics',
expr: stripIndents`fields ispresent(resolverArn) as isRes |
filter isRes |
filter logType = "Tracing" |
stats min(duration), max(duration), avg(duration) as avgDur by resolverArn |
sort avgDur desc |
limit 10`,
},
{
title: 'Top 10 requests with maximum latency',
expr: stripIndents`fields requestId, latency |
filter logType = "RequestSummary" |
sort latency desc |
limit 10`,
},
],
},
];
function renderHighlightedMarkup(code: string, keyPrefix: string) {
const grammar = tokenizer;
const tokens = flattenTokens(Prism.tokenize(code, grammar));
const spans = tokens
.filter((token) => typeof token !== 'string')
.map((token, i) => {
return (
<span
className={`prism-token token ${token.types.join(' ')} ${token.aliases.join(' ')}`}
key={`${keyPrefix}-token-${i}`}
>
{token.content}
</span>
);
});
return <div className="slate-query-field">{spans}</div>;
}
const exampleCategory = css`
margin-top: 5px;
`;
export default class LogsCheatSheet extends PureComponent<
QueryEditorHelpProps<CloudWatchQuery>,
{ userExamples: string[] }
> {
onClickExample(query: CloudWatchQuery) {
this.props.onClickExample(query);
}
renderExpression(expr: string, keyPrefix: string) {
return (
<button
type="button"
className="cheat-sheet-item__example"
key={expr}
onClick={() =>
this.onClickExample({
refId: this.props.query.refId ?? 'A',
expression: expr,
queryMode: 'Logs',
region: this.props.query.region,
id: this.props.query.refId ?? 'A',
logGroupNames: 'logGroupNames' in this.props.query ? this.props.query.logGroupNames : [],
logGroups: 'logGroups' in this.props.query ? this.props.query.logGroups : [],
})
}
>
<pre>{renderHighlightedMarkup(expr, keyPrefix)}</pre>
</button>
);
}
renderLogsCheatSheet() {
return (
<div>
<h2>CloudWatch Logs Cheat Sheet</h2>
{CLIQ_EXAMPLES.map((cat, i) => (
<div key={`${cat.category}-${i}`}>
<div className={`cheat-sheet-item__title ${cx(exampleCategory)}`}>{cat.category}</div>
{cat.examples.map((item, j) => (
<div className="cheat-sheet-item" key={`item-${j}`}>
<h4>{item.title}</h4>
{this.renderExpression(item.expr, `item-${j}`)}
</div>
))}
</div>
))}
</div>
);
}
render() {
return (
<div>
<h3>CloudWatch Logs cheat sheet</h3>
{CLIQ_EXAMPLES.map((cat, i) => (
<div key={`cat-${i}`}>
<div className={`cheat-sheet-item__title ${cx(exampleCategory)}`}>{cat.category}</div>
{cat.examples.map((item, j) => (
<div className="cheat-sheet-item" key={`item-${j}`}>
<h4>{item.title}</h4>
{this.renderExpression(item.expr, `item-${j}`)}
</div>
))}
</div>
))}
</div>
);
}
}
| public/app/plugins/datasource/cloudwatch/components/LogsCheatSheet.tsx | 1 | https://github.com/grafana/grafana/commit/c235ad67e778a1c2ecf4e43c9f3db7df146c9e89 | [
0.0005796081386506557,
0.00019003900524694473,
0.00016420110478065908,
0.00016741424042265862,
0.00007635779184056446
] |
{
"id": 0,
"code_window": [
"The CloudWatch plugin enables you to monitor and troubleshoot applications across multiple regional accounts. Using cross-account observability, you can seamlessly search, visualize and analyze metrics and logs without worrying about account boundaries.\n",
"\n",
"To use this feature, configure in the [AWS console under Cloudwatch Settings](https://aws.amazon.com/blogs/aws/new-amazon-cloudwatch-cross-account-observability/), a monitoring and source account, and then add the necessary IAM permissions as described above.\n"
],
"labels": [
"keep",
"keep",
"add"
],
"after_edit": [
"\n",
"## CloudWatch Logs data protection\n",
"\n",
"CloudWatch Logs can safeguard data by using log group data protection policies. If you have data protection enabled for a log group, then any sensitive data that matches the data identifiers you've selected will be masked. In order to view masked data you will need to have the `logs:Unmask` IAM permission enabled. See the AWS documentation on how to [help protect sensitive log data with masking](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/mask-sensitive-log-data.html) to learn more about this."
],
"file_path": "docs/sources/datasources/aws-cloudwatch/_index.md",
"type": "add",
"edit_start_line_idx": 377
} | import $ from 'jquery';
import { isString, escape } from 'lodash';
import coreModule from 'app/angular/core_module';
import alertDef from 'app/features/alerting/state/alertDef';
import { DashboardSrv } from 'app/features/dashboard/services/DashboardSrv';
coreModule.directive('annotationTooltip', ['$sanitize', 'dashboardSrv', '$compile', annotationTooltipDirective]);
export function annotationTooltipDirective($sanitize: any, dashboardSrv: DashboardSrv, $compile: any) {
function sanitizeString(str: string) {
try {
return $sanitize(str);
} catch (err) {
console.log('Could not sanitize annotation string, html escaping instead');
return escape(str);
}
}
return {
restrict: 'E',
scope: {
event: '=',
onEdit: '&',
},
link: (scope: any, element: JQuery) => {
const event = scope.event;
let title = event.title;
let text = event.text;
const dashboard = dashboardSrv.getCurrent();
let tooltip = '<div class="graph-annotation">';
let titleStateClass = '';
if (event.alertId !== undefined && event.newState) {
const stateModel = alertDef.getStateDisplayModel(event.newState);
titleStateClass = stateModel.stateClass;
title = `<i class="${stateModel.iconClass}"></i> ${stateModel.text}`;
text = alertDef.getAlertAnnotationInfo(event);
if (event.text) {
text = text + '<br />' + event.text;
}
} else if (title) {
text = title + '<br />' + (isString(text) ? text : '');
title = '';
}
let header = `<div class="graph-annotation__header">`;
if (event.login && event.avatarUrl) {
header += `<div class="graph-annotation__user" bs-tooltip="'Created by ${event.login}'"><img src="${event.avatarUrl}" /></div>`;
}
header += `
<span class="graph-annotation__title ${titleStateClass}">${sanitizeString(title)}</span>
<span class="graph-annotation__time">${dashboard?.formatDate(event.min)}</span>
`;
// Show edit icon only for users with at least Editor role
if (event.id && dashboard?.canEditAnnotations(event.dashboardId)) {
header += `
<span class="pointer graph-annotation__edit-icon" ng-click="onEdit()">
<i class="fa fa-pencil-square"></i>
</span>
`;
}
header += `</div>`;
tooltip += header;
tooltip += '<div class="graph-annotation__body">';
if (text) {
tooltip += '<div ng-non-bindable>' + sanitizeString(text.replace(/\n/g, '<br>')) + '</div>';
}
const tags = event.tags;
if (tags && tags.length) {
scope.tags = tags;
tooltip +=
'<span class="label label-tag small" ng-repeat="tag in tags" tag-color-from-name="tag">{{tag}}</span><br/>';
}
tooltip += '</div>';
tooltip += '</div>';
const $tooltip = $(tooltip);
$tooltip.appendTo(element);
$compile(element.contents())(scope);
},
};
}
| public/app/plugins/panel/graph/annotation_tooltip.ts | 0 | https://github.com/grafana/grafana/commit/c235ad67e778a1c2ecf4e43c9f3db7df146c9e89 | [
0.00017077455413527787,
0.00016623570991214365,
0.00016470870468765497,
0.00016570373554714024,
0.0000016477506505907513
] |
{
"id": 0,
"code_window": [
"The CloudWatch plugin enables you to monitor and troubleshoot applications across multiple regional accounts. Using cross-account observability, you can seamlessly search, visualize and analyze metrics and logs without worrying about account boundaries.\n",
"\n",
"To use this feature, configure in the [AWS console under Cloudwatch Settings](https://aws.amazon.com/blogs/aws/new-amazon-cloudwatch-cross-account-observability/), a monitoring and source account, and then add the necessary IAM permissions as described above.\n"
],
"labels": [
"keep",
"keep",
"add"
],
"after_edit": [
"\n",
"## CloudWatch Logs data protection\n",
"\n",
"CloudWatch Logs can safeguard data by using log group data protection policies. If you have data protection enabled for a log group, then any sensitive data that matches the data identifiers you've selected will be masked. In order to view masked data you will need to have the `logs:Unmask` IAM permission enabled. See the AWS documentation on how to [help protect sensitive log data with masking](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/mask-sensitive-log-data.html) to learn more about this."
],
"file_path": "docs/sources/datasources/aws-cloudwatch/_index.md",
"type": "add",
"edit_start_line_idx": 377
} | <mjml>
<mj-head>
<!-- ⬇ Don't forget to specifify an email subject! Use the HTML comment below ⬇ -->
<mj-title>
{{ Subject .Subject .TemplateData "{{ .InvitedBy }} has added you to the {{ .OrgName }} organization" }}
</mj-title>
<mj-include path="./partials/layout/head.mjml" />
</mj-head>
<mj-body>
<mj-section>
<mj-include path="./partials/layout/header.mjml" />
</mj-section>
<mj-section background-color="#22252b" border="1px solid #2f3037">
<mj-column>
<mj-text>
<h2>You have been added to {{ .OrgName }}</h2>
<strong>{{ .InvitedBy }}</strong> has added you to the <strong>{{ .OrgName }}</strong> organization in Grafana.
</mj-text>
<mj-text>
Once logged in, <strong>{{ .OrgName }}</strong> will be available to switch to in the user interface.
</mj-text>
<mj-text>
Log in now by clicking the link below:
</mj-text>
<mj-button href="{{ .AppUrl }}">
Login to Grafana
</mj-button>
<mj-text>
You can also copy and paste this link into your browser directly:
</mj-text>
<mj-text>
<a rel="noopener" href="{{ .AppUrl }}">{{ .AppUrl }}</a>
</mj-text>
</mj-column>
</mj-section>
<mj-section>
<mj-include path="./partials/layout/footer.mjml" />
</mj-section>
</mj-body>
</mjml>
| emails/templates/invited_to_org.mjml | 0 | https://github.com/grafana/grafana/commit/c235ad67e778a1c2ecf4e43c9f3db7df146c9e89 | [
0.00018433932564221323,
0.00016947474796324968,
0.00016473494179081172,
0.00016603292897343636,
0.000007456833827745868
] |
{
"id": 0,
"code_window": [
"The CloudWatch plugin enables you to monitor and troubleshoot applications across multiple regional accounts. Using cross-account observability, you can seamlessly search, visualize and analyze metrics and logs without worrying about account boundaries.\n",
"\n",
"To use this feature, configure in the [AWS console under Cloudwatch Settings](https://aws.amazon.com/blogs/aws/new-amazon-cloudwatch-cross-account-observability/), a monitoring and source account, and then add the necessary IAM permissions as described above.\n"
],
"labels": [
"keep",
"keep",
"add"
],
"after_edit": [
"\n",
"## CloudWatch Logs data protection\n",
"\n",
"CloudWatch Logs can safeguard data by using log group data protection policies. If you have data protection enabled for a log group, then any sensitive data that matches the data identifiers you've selected will be masked. In order to view masked data you will need to have the `logs:Unmask` IAM permission enabled. See the AWS documentation on how to [help protect sensitive log data with masking](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/mask-sensitive-log-data.html) to learn more about this."
],
"file_path": "docs/sources/datasources/aws-cloudwatch/_index.md",
"type": "add",
"edit_start_line_idx": 377
} | // Copyright (c) 2017 Uber Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import { render, screen } from '@testing-library/react';
import React from 'react';
import TimelineHeaderRow, { TimelineHeaderRowProps } from './TimelineHeaderRow';
const nameColumnWidth = 0.25;
const setup = () => {
const props = {
nameColumnWidth,
duration: 1234,
numTicks: 5,
onCollapseAll: () => {},
onCollapseOne: () => {},
onColummWidthChange: () => {},
onExpandAll: () => {},
onExpandOne: () => {},
updateNextViewRangeTime: () => {},
updateViewRangeTime: () => {},
viewRangeTime: {
current: [0.1, 0.9],
},
};
return render(<TimelineHeaderRow {...(props as unknown as TimelineHeaderRowProps)} />);
};
describe('TimelineHeaderRow', () => {
it('renders without exploding', () => {
expect(() => setup()).not.toThrow();
});
it('renders the title', () => {
setup();
expect(screen.getByRole('heading', { name: 'Service & Operation' }));
});
it('renders the collapser controls', () => {
setup();
expect(screen.getByRole('button', { name: 'Expand All' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Collapse All' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Expand +1' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Collapse +1' })).toBeInTheDocument();
});
it('renders the resizer controls', () => {
setup();
expect(screen.getByTestId('TimelineColumnResizer')).toBeInTheDocument();
expect(screen.getByTestId('TimelineColumnResizer--dragger')).toBeInTheDocument();
expect(screen.getByTestId('TimelineColumnResizer--gripIcon')).toBeInTheDocument();
});
it('propagates the name column width', () => {
setup();
const timelineCells = screen.queryAllByTestId('TimelineRowCell');
expect(timelineCells).toHaveLength(2);
expect(getComputedStyle(timelineCells[0]).maxWidth).toBe(`${nameColumnWidth * 100}%`);
expect(getComputedStyle(timelineCells[1]).maxWidth).toBe(`${(1 - nameColumnWidth) * 100}%`);
});
it('renders the TimelineViewingLayer', () => {
setup();
expect(screen.getByTestId('TimelineViewingLayer')).toBeInTheDocument();
});
it('renders the Ticks', () => {
setup();
expect(screen.getAllByTestId('TicksID')).toHaveLength(5);
});
});
| public/app/features/explore/TraceView/components/TraceTimelineViewer/TimelineHeaderRow/TimelineHeaderRow.test.tsx | 0 | https://github.com/grafana/grafana/commit/c235ad67e778a1c2ecf4e43c9f3db7df146c9e89 | [
0.0001817695883801207,
0.00017025534179992974,
0.00016622823022771627,
0.00016958998457994312,
0.000004303222340240609
] |
{
"id": 1,
"code_window": [
"const exampleCategory = css`\n",
" margin-top: 5px;\n",
"`;\n",
"\n",
"export default class LogsCheatSheet extends PureComponent<\n",
" QueryEditorHelpProps<CloudWatchQuery>,\n",
" { userExamples: string[] }\n",
"> {\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"const link = css`\n",
" text-decoration: underline;\n",
"`;\n",
"\n"
],
"file_path": "public/app/plugins/datasource/cloudwatch/components/LogsCheatSheet.tsx",
"type": "add",
"edit_start_line_idx": 218
} | ---
aliases:
- ../data-sources/aws-cloudwatch/
- ../data-sources/aws-cloudwatch/preconfig-cloudwatch-dashboards/
- ../data-sources/aws-cloudwatch/provision-cloudwatch/
- cloudwatch/
- preconfig-cloudwatch-dashboards/
- provision-cloudwatch/
description: Guide for using Amazon CloudWatch in Grafana
keywords:
- grafana
- cloudwatch
- guide
menuTitle: Amazon CloudWatch
title: Amazon CloudWatch data source
weight: 200
---
# Amazon CloudWatch data source
Grafana ships with built-in support for Amazon CloudWatch.
This topic describes queries, templates, variables, and other configuration specific to the CloudWatch data source.
For instructions on how to add a data source to Grafana, refer to the [administration documentation]({{< relref "../../administration/data-source-management/" >}}).
Only users with the organization administrator role can add data sources.
Administrators can also [provision the data source]({{< relref "#provision-the-data-source" >}}) with Grafana's provisioning system, and should [control pricing]({{< relref "#control-pricing" >}}) and [manage service quotas]({{< relref "#manage-service-quotas" >}}) accordingly.
Once you've added the data source, you can [configure it]({{< relref "#configure-the-data-source" >}}) so that your Grafana instance's users can create queries in its [query editor]({{< relref "./query-editor/" >}}) when they [build dashboards]({{< relref "../../dashboards/build-dashboards/" >}}) and use [Explore]({{< relref "../../explore/" >}}).
> **Note:** To troubleshoot issues while setting up the CloudWatch data source, check the `/var/log/grafana/grafana.log` file.
## Configure the data source
**To access the data source configuration page:**
1. Hover the cursor over the **Configuration** (gear) icon.
1. Select **Data Sources**.
1. Select the CloudWatch data source.
### Configure AWS authentication
A Grafana plugin's requests to AWS are made on behalf of an AWS Identity and Access Management (IAM) role or IAM user.
The IAM user or IAM role must have the associated policies to perform certain API actions.
For authentication options and configuration details, refer to [AWS authentication]({{< relref "./aws-authentication/" >}}).
#### IAM policy examples
To read CloudWatch metrics and EC2 tags, instances, regions, and alarms, you must grant Grafana permissions via IAM.
You can attach these permissions to the IAM role or IAM user you configured in [AWS authentication]({{< relref "./aws-authentication/" >}}).
**Metrics-only:**
```json
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AllowReadingMetricsFromCloudWatch",
"Effect": "Allow",
"Action": [
"cloudwatch:DescribeAlarmsForMetric",
"cloudwatch:DescribeAlarmHistory",
"cloudwatch:DescribeAlarms",
"cloudwatch:ListMetrics",
"cloudwatch:GetMetricData",
"cloudwatch:GetInsightRuleReport"
],
"Resource": "*"
},
{
"Sid": "AllowReadingTagsInstancesRegionsFromEC2",
"Effect": "Allow",
"Action": ["ec2:DescribeTags", "ec2:DescribeInstances", "ec2:DescribeRegions"],
"Resource": "*"
},
{
"Sid": "AllowReadingResourcesForTags",
"Effect": "Allow",
"Action": "tag:GetResources",
"Resource": "*"
}
]
}
```
**Logs-only:**
```json
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AllowReadingLogsFromCloudWatch",
"Effect": "Allow",
"Action": [
"logs:DescribeLogGroups",
"logs:GetLogGroupFields",
"logs:StartQuery",
"logs:StopQuery",
"logs:GetQueryResults",
"logs:GetLogEvents"
],
"Resource": "*"
},
{
"Sid": "AllowReadingTagsInstancesRegionsFromEC2",
"Effect": "Allow",
"Action": ["ec2:DescribeTags", "ec2:DescribeInstances", "ec2:DescribeRegions"],
"Resource": "*"
},
{
"Sid": "AllowReadingResourcesForTags",
"Effect": "Allow",
"Action": "tag:GetResources",
"Resource": "*"
}
]
}
```
**Metrics and Logs:**
```json
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AllowReadingMetricsFromCloudWatch",
"Effect": "Allow",
"Action": [
"cloudwatch:DescribeAlarmsForMetric",
"cloudwatch:DescribeAlarmHistory",
"cloudwatch:DescribeAlarms",
"cloudwatch:ListMetrics",
"cloudwatch:GetMetricData",
"cloudwatch:GetInsightRuleReport"
],
"Resource": "*"
},
{
"Sid": "AllowReadingLogsFromCloudWatch",
"Effect": "Allow",
"Action": [
"logs:DescribeLogGroups",
"logs:GetLogGroupFields",
"logs:StartQuery",
"logs:StopQuery",
"logs:GetQueryResults",
"logs:GetLogEvents"
],
"Resource": "*"
},
{
"Sid": "AllowReadingTagsInstancesRegionsFromEC2",
"Effect": "Allow",
"Action": ["ec2:DescribeTags", "ec2:DescribeInstances", "ec2:DescribeRegions"],
"Resource": "*"
},
{
"Sid": "AllowReadingResourcesForTags",
"Effect": "Allow",
"Action": "tag:GetResources",
"Resource": "*"
}
]
}
```
**Cross-account observability: (see below) **
```json
{
"Version": "2012-10-17",
"Statement": [
{
"Action": ["oam:ListSinks", "oam:ListAttachedLinks"],
"Effect": "Allow",
"Resource": "*"
}
]
}
```
### Configure CloudWatch settings
#### Namespaces of Custom Metrics
Grafana can't load custom namespaces through the CloudWatch [GetMetricData API](https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_GetMetricData.html).
To make custom metrics appear in the data source's query editor fields, specify the names of the namespaces containing the custom metrics in the data source configuration's _Namespaces of Custom Metrics_ field.
The field accepts multiple namespaces separated by commas.
#### Timeout
Configure the timeout specifically for CloudWatch Logs queries.
Log queries don't keep a single request open, and instead periodically poll for results.
Therefore, they don't recognize the standard Grafana query timeout.
Because of limits on concurrently running queries in CloudWatch, they can also take longer to finish.
#### X-Ray trace links
To automatically add links in your logs when the log contains the `@xrayTraceId` field, link an X-Ray data source in the "X-Ray trace link" section of the data source configuration.
{{< figure src="/static/img/docs/cloudwatch/xray-trace-link-configuration-8-2.png" max-width="800px" class="docs-image--no-shadow" caption="Trace link configuration" >}}
The data source select contains only existing data source instances of type X-Ray.
To use this feature, you must already have an X-Ray data source configured.
For details, see the [X-Ray data source docs](/grafana/plugins/grafana-x-ray-datasource/).
To view the X-Ray link, select the log row in either the Explore view or dashboard [Logs panel]({{< relref "../../panels-visualizations/visualizations/logs" >}}) to view the log details section.
To log the `@xrayTraceId`, see the [AWS X-Ray documentation](https://docs.amazonaws.cn/en_us/xray/latest/devguide/xray-services.html).
To provide the field to Grafana, your log queries must also contain the `@xrayTraceId` field, for example by using the query `fields @message, @xrayTraceId`.
{{< figure src="/static/img/docs/cloudwatch/xray-link-log-details-8-2.png" max-width="800px" class="docs-image--no-shadow" caption="Trace link in log details" >}}
### Configure the data source with grafana.ini
The Grafana [configuration file]({{< relref "../../setup-grafana/configure-grafana#aws" >}}) includes an `AWS` section where you can configure data source options:
| Configuration option | Description |
| ------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `allowed_auth_providers` | Specifies which authentication providers are allowed for the CloudWatch data source. The following providers are enabled by default in open-source Grafana: `default` (AWS SDK default), keys (Access and secret key), credentials (Credentials file), ec2_IAM_role (EC2 IAM role). |
| `assume_role_enabled` | Allows you to disable `assume role (ARN)` in the CloudWatch data source. The assume role (ARN) is enabled by default in open-source Grafana. |
| `list_metrics_page_limit` | Sets the limit of List Metrics API pages. When a custom namespace is specified in the query editor, the [List Metrics API](https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_ListMetrics.html) populates the _Metrics_ field and _Dimension_ fields. The API is paginated and returns up to 500 results per page, and the data source also limits the number of pages to 500 by default. This setting customizes that limit. |
### Provision the data source
You can define and configure the data source in YAML files as part of Grafana's provisioning system.
For more information about provisioning, and for available configuration options, refer to [Provisioning Grafana]({{< relref "../../administration/provisioning/#data-sources" >}}).
#### Provisioning examples
**Using AWS SDK (default):**
```yaml
apiVersion: 1
datasources:
- name: CloudWatch
type: cloudwatch
jsonData:
authType: default
defaultRegion: eu-west-2
```
**Using credentials' profile name (non-default):**
```yaml
apiVersion: 1
datasources:
- name: CloudWatch
type: cloudwatch
jsonData:
authType: credentials
defaultRegion: eu-west-2
customMetricsNamespaces: 'CWAgent,CustomNameSpace'
profile: secondary
```
**Using accessKey and secretKey:**
```yaml
apiVersion: 1
datasources:
- name: CloudWatch
type: cloudwatch
jsonData:
authType: keys
defaultRegion: eu-west-2
secureJsonData:
accessKey: '<your access key>'
secretKey: '<your secret key>'
```
**Using AWS SDK Default and ARN of IAM Role to Assume:**
```yaml
apiVersion: 1
datasources:
- name: CloudWatch
type: cloudwatch
jsonData:
authType: default
assumeRoleArn: arn:aws:iam::123456789012:root
defaultRegion: eu-west-2
```
## Query the data source
The CloudWatch data source can query data from both CloudWatch metrics and CloudWatch Logs APIs, each with its own specialized query editor.
For details, see the [query editor documentation]({{< relref "./query-editor/" >}}).
## Use template variables
Instead of hard-coding details such as server, application, and sensor names in metric queries, you can use variables.
Grafana lists these variables in dropdown select boxes at the top of the dashboard to help you change the data displayed in your dashboard.
Grafana refers to such variables as template variables.
For details, see the [template variables documentation]({{< relref "./template-variables/" >}}).
## Import pre-configured dashboards
The CloudWatch data source ships with curated and pre-configured dashboards for five of the most popular AWS services:
- **Amazon Elastic Compute Cloud:** `Amazon EC2`
- **Amazon Elastic Block Store:** `Amazon EBS`
- **AWS Lambda:** `AWS Lambda`
- **Amazon CloudWatch Logs:** `Amazon CloudWatch Logs`
- **Amazon Relational Database Service:** `Amazon RDS`
**To import curated dashboards:**
1. Navigate to the data source's [configuration page]({{< relref "#configure-the-data-source" >}}).
1. Select the **Dashboards** tab.
This displays the curated selection of importable dashboards.
1. Select **Import** for the dashboard to import.
{{< figure src="/static/img/docs/v65/cloudwatch-dashboard-import.png" caption="CloudWatch dashboard import" >}}
**To customize an imported dashboard:**
To customize one of these dashboards, we recommend that you save it under a different name.
If you don't, upgrading Grafana can overwrite the customized dashboard with the new version.
## Create queries for alerting
Alerting requires queries that return numeric data, which CloudWatch Logs support.
For example, you can enable alerts through the use of the `stats` command.
This is also a valid query for alerting on messages that include the text "Exception":
```
filter @message like /Exception/
| stats count(*) as exceptionCount by bin(1h)
| sort exceptionCount desc
```
> **Note:** If you receive an error like `input data must be a wide series but got ...` when trying to alert on a query, make sure that your query returns valid numeric data that can be output to a Time series panel.
For more information on Grafana alerts, refer to [Alerting]({{< relref "../../alerting" >}}).
## Control pricing
The Amazon CloudWatch data source for Grafana uses [`ListMetrics`](https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_ListMetrics.html) and [`GetMetricData`](https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_GetMetricData.html) CloudWatch API calls to list and retrieve metrics.
Pricing for CloudWatch Logs is based on the amount of data ingested, archived, and analyzed via CloudWatch Logs Insights queries.
Each time you select a dimension in the query editor, Grafana issues a `ListMetrics` API request.
Each time you change queries in the query editor, Grafana issues a new request to the `GetMetricData` API.
> **Note:** Grafana v6.5 and higher replaced all `GetMetricStatistics` API requests with calls to GetMetricData to provide better support for CloudWatch metric math, and enables the automatic generation of search expressions when using wildcards or disabling the `Match Exact` option.
> The `GetMetricStatistics` API qualified for the CloudWatch API free tier, but `GetMetricData` calls don't.
For more information, refer to the [CloudWatch pricing page](https://aws.amazon.com/cloudwatch/pricing/).
## Manage service quotas
AWS defines quotas, or limits, for resources, actions, and items in your AWS account.
Depending on the number of queries in your dashboard and the number of users accessing the dashboard, you might reach the usage limits for various CloudWatch and CloudWatch Logs resources.
Quotas are defined per account and per region.
If you use multiple regions or configured more than one CloudWatch data source to query against multiple accounts, you must request a quota increase for each account and region in which you reach the limit.
To request a quota increase, visit the [AWS Service Quotas console](https://console.aws.amazon.com/servicequotas/home?r#!/services/monitoring/quotas/L-5E141212).
For more information, refer to the AWS documentation for [Service Quotas](https://docs.aws.amazon.com/servicequotas/latest/userguide/intro.html) and [CloudWatch limits](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch_limits.html).
## Cross-account observability
The CloudWatch plugin enables you to monitor and troubleshoot applications across multiple regional accounts. Using cross-account observability, you can seamlessly search, visualize and analyze metrics and logs without worrying about account boundaries.
To use this feature, configure in the [AWS console under Cloudwatch Settings](https://aws.amazon.com/blogs/aws/new-amazon-cloudwatch-cross-account-observability/), a monitoring and source account, and then add the necessary IAM permissions as described above.
| docs/sources/datasources/aws-cloudwatch/_index.md | 1 | https://github.com/grafana/grafana/commit/c235ad67e778a1c2ecf4e43c9f3db7df146c9e89 | [
0.0002721499477047473,
0.00017208569624926895,
0.0001618384412722662,
0.00016923235671129078,
0.000017224574548890814
] |
{
"id": 1,
"code_window": [
"const exampleCategory = css`\n",
" margin-top: 5px;\n",
"`;\n",
"\n",
"export default class LogsCheatSheet extends PureComponent<\n",
" QueryEditorHelpProps<CloudWatchQuery>,\n",
" { userExamples: string[] }\n",
"> {\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"const link = css`\n",
" text-decoration: underline;\n",
"`;\n",
"\n"
],
"file_path": "public/app/plugins/datasource/cloudwatch/components/LogsCheatSheet.tsx",
"type": "add",
"edit_start_line_idx": 218
} | import { ArrayVector, DataFrame, FieldType } from '@grafana/data';
import { makeTableFrames } from './makeTableFrames';
const frame1: DataFrame = {
name: 'frame1',
refId: 'A',
meta: {
executedQueryString: 'something1',
},
fields: [
{
name: 'Time',
type: FieldType.time,
config: {},
values: new ArrayVector([1645029699311]),
},
{
name: 'Value',
type: FieldType.number,
labels: {
level: 'error',
location: 'moon',
protocol: 'http',
},
config: {
displayNameFromDS: '{level="error", location="moon", protocol="http"}',
},
values: new ArrayVector([23]),
},
],
length: 1,
};
const frame2: DataFrame = {
name: 'frame1',
refId: 'A',
meta: {
executedQueryString: 'something1',
},
fields: [
{
name: 'Time',
type: FieldType.time,
config: {},
values: new ArrayVector([1645029699311]),
},
{
name: 'Value',
type: FieldType.number,
labels: {
level: 'info',
location: 'moon',
protocol: 'http',
},
config: {
displayNameFromDS: '{level="info", location="moon", protocol="http"}',
},
values: new ArrayVector([45]),
},
],
length: 1,
};
const frame3: DataFrame = {
name: 'frame1',
refId: 'B',
meta: {
executedQueryString: 'something1',
},
fields: [
{
name: 'Time',
type: FieldType.time,
config: {},
values: new ArrayVector([1645029699311]),
},
{
name: 'Value',
type: FieldType.number,
labels: {
level: 'error',
location: 'moon',
protocol: 'http',
},
config: {
displayNameFromDS: '{level="error", location="moon", protocol="http"}',
},
values: new ArrayVector([72]),
},
],
length: 1,
};
const outputSingle = [
{
fields: [
{ config: {}, name: 'Time', type: 'time', values: new ArrayVector([1645029699311]) },
{ config: { filterable: true }, name: 'level', type: 'string', values: new ArrayVector(['error']) },
{ config: { filterable: true }, name: 'location', type: 'string', values: new ArrayVector(['moon']) },
{ config: { filterable: true }, name: 'protocol', type: 'string', values: new ArrayVector(['http']) },
{ config: {}, name: 'Value #A', type: 'number', values: new ArrayVector([23]) },
],
length: 1,
meta: { preferredVisualisationType: 'table' },
refId: 'A',
},
];
const outputMulti = [
{
fields: [
{ config: {}, name: 'Time', type: 'time', values: new ArrayVector([1645029699311, 1645029699311]) },
{ config: { filterable: true }, name: 'level', type: 'string', values: new ArrayVector(['error', 'info']) },
{ config: { filterable: true }, name: 'location', type: 'string', values: new ArrayVector(['moon', 'moon']) },
{ config: { filterable: true }, name: 'protocol', type: 'string', values: new ArrayVector(['http', 'http']) },
{ config: {}, name: 'Value #A', type: 'number', values: new ArrayVector([23, 45]) },
],
length: 2,
meta: { preferredVisualisationType: 'table' },
refId: 'A',
},
{
fields: [
{ config: {}, name: 'Time', type: 'time', values: new ArrayVector([1645029699311]) },
{ config: { filterable: true }, name: 'level', type: 'string', values: new ArrayVector(['error']) },
{ config: { filterable: true }, name: 'location', type: 'string', values: new ArrayVector(['moon']) },
{ config: { filterable: true }, name: 'protocol', type: 'string', values: new ArrayVector(['http']) },
{ config: {}, name: 'Value #B', type: 'number', values: new ArrayVector([72]) },
],
length: 1,
meta: { preferredVisualisationType: 'table' },
refId: 'B',
},
];
describe('loki makeTableFrames', () => {
it('converts a single instant metric dataframe to table dataframe', () => {
const result = makeTableFrames([frame1]);
expect(result).toEqual(outputSingle);
});
it('converts 3 instant metric dataframes into 2 tables', () => {
const result = makeTableFrames([frame1, frame2, frame3]);
expect(result).toEqual(outputMulti);
});
});
| public/app/plugins/datasource/loki/makeTableFrames.test.ts | 0 | https://github.com/grafana/grafana/commit/c235ad67e778a1c2ecf4e43c9f3db7df146c9e89 | [
0.00018068526696879417,
0.00017814621969591826,
0.00017522936104796827,
0.00017833760648500174,
0.0000012020458370898268
] |
{
"id": 1,
"code_window": [
"const exampleCategory = css`\n",
" margin-top: 5px;\n",
"`;\n",
"\n",
"export default class LogsCheatSheet extends PureComponent<\n",
" QueryEditorHelpProps<CloudWatchQuery>,\n",
" { userExamples: string[] }\n",
"> {\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"const link = css`\n",
" text-decoration: underline;\n",
"`;\n",
"\n"
],
"file_path": "public/app/plugins/datasource/cloudwatch/components/LogsCheatSheet.tsx",
"type": "add",
"edit_start_line_idx": 218
} | import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import React from 'react';
import { SecretInput, RESET_BUTTON_TEXT, CONFIGURED_TEXT } from './SecretInput';
const PLACEHOLDER_TEXT = 'Your secret...';
describe('<SecretInput />', () => {
it('should render an input if the secret is not configured', () => {
render(<SecretInput isConfigured={false} onChange={() => {}} onReset={() => {}} placeholder={PLACEHOLDER_TEXT} />);
const input = screen.getByPlaceholderText(PLACEHOLDER_TEXT);
// Should show an enabled input
expect(input).toBeInTheDocument();
expect(input).not.toBeDisabled();
// Should not show a "Reset" button
expect(screen.queryByRole('button', { name: RESET_BUTTON_TEXT })).not.toBeInTheDocument();
});
it('should render a disabled input with a reset button if the secret is already configured', () => {
render(<SecretInput isConfigured={true} onChange={() => {}} onReset={() => {}} placeholder={PLACEHOLDER_TEXT} />);
const input = screen.getByPlaceholderText(PLACEHOLDER_TEXT);
// Should show a disabled input
expect(input).toBeInTheDocument();
expect(input).toBeDisabled();
expect(input).toHaveValue(CONFIGURED_TEXT);
// Should show a reset button
expect(screen.queryByRole('button', { name: RESET_BUTTON_TEXT })).toBeInTheDocument();
});
it('should be possible to reset a configured secret', async () => {
const onReset = jest.fn();
render(<SecretInput isConfigured={true} onChange={() => {}} onReset={onReset} placeholder={PLACEHOLDER_TEXT} />);
// Should show a reset button and a disabled input
expect(screen.queryByPlaceholderText(PLACEHOLDER_TEXT)).toBeDisabled();
expect(screen.queryByRole('button', { name: RESET_BUTTON_TEXT })).toBeInTheDocument();
// Click on "Reset"
await userEvent.click(screen.getByRole('button', { name: RESET_BUTTON_TEXT }));
expect(onReset).toHaveBeenCalledTimes(1);
});
it('should be possible to change the value of the secret', async () => {
const onChange = jest.fn();
render(<SecretInput isConfigured={false} onChange={onChange} onReset={() => {}} placeholder={PLACEHOLDER_TEXT} />);
const input = screen.getByPlaceholderText(PLACEHOLDER_TEXT);
expect(input).toHaveValue('');
await userEvent.type(input, 'Foo');
expect(onChange).toHaveBeenCalled();
expect(input).toHaveValue('Foo');
});
});
| packages/grafana-ui/src/components/SecretInput/SecretInput.test.tsx | 0 | https://github.com/grafana/grafana/commit/c235ad67e778a1c2ecf4e43c9f3db7df146c9e89 | [
0.0001770904491422698,
0.0001732409291435033,
0.0001687075855443254,
0.00017369462875649333,
0.0000028405224838934373
] |
{
"id": 1,
"code_window": [
"const exampleCategory = css`\n",
" margin-top: 5px;\n",
"`;\n",
"\n",
"export default class LogsCheatSheet extends PureComponent<\n",
" QueryEditorHelpProps<CloudWatchQuery>,\n",
" { userExamples: string[] }\n",
"> {\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"const link = css`\n",
" text-decoration: underline;\n",
"`;\n",
"\n"
],
"file_path": "public/app/plugins/datasource/cloudwatch/components/LogsCheatSheet.tsx",
"type": "add",
"edit_start_line_idx": 218
} | ---
title: Upgrade guide common tasks
---
We recommend that you upgrade Grafana often to stay current with the latest fixes and enhancements.
Because Grafana upgrades are backward compatible, the upgrade process is straightforward, and dashboards and graphs will not change.
In addition to common tasks you should complete for all versions of Grafana, there might be additional upgrade tasks to complete for a version.
> **Note:** There might be minor breaking changes in some releases. We outline these changes in the [What's New ]({{< relref "../../whatsnew/" >}}) document for each release.
For versions of Grafana prior to v9.2, we published additional information in the [Release Notes]({{< relref "../../release-notes/" >}}).
When available, we list all changes with links to pull requests or issues in the [Changelog](https://github.com/grafana/grafana/blob/main/CHANGELOG.md).
> **Note:** When possible, we recommend that you test the Grafana upgrade process in a test or development environment.
## Back up the Grafana database
Although Grafana automatically upgrades the database on startup, we recommend that you back up your Grafana database so that you can roll back to a previous version, if required.
### SQLite
If you use SQLite, you only need to back up the `grafana.db` file. On Unix systems, the database file is usually located in `/var/lib/grafana/`.
If you are unsure which database you use and where it is stored, check the Grafana configuration file. If you
installed Grafana to a custom location using a binary tar/zip, the database is usually located in `<grafana_install_dir>/data`.
### MySQL
To back up or restore a MySQL Grafana database, run the following commands:
```bash
backup:
> mysqldump -u root -p[root_password] [grafana] > grafana_backup.sql
restore:
> mysql -u root -p grafana < grafana_backup.sql
```
### Postgres
To back up or restore a Postgres Grafana database, run the following commands:
```bash
backup:
> pg_dump grafana > grafana_backup
restore:
> psql grafana < grafana_backup
```
## Backup plugins
We recommend that you back up installed plugins before you upgrade Grafana so that you can roll back to a previous version of Grafana, if necessary.
## Upgrade Grafana
The following sections provide instructions for how to upgrade Grafana based on your installation method.
### Debian
To upgrade Grafana installed from a Debian package (`.deb`), complete the following steps:
1. In your current installation of Grafana, save your custom configuration changes to a file named `<grafana_install_dir>/conf/custom.ini`.
This enables you to upgrade Grafana without the risk of losing your configuration changes.
1. [Download](https://grafana.com/grafana/download?platform=linux) the latest version of Grafana.
1. Run the following `dpkg -i` command.
```bash
wget <debian package url>
sudo apt-get install -y adduser
sudo dpkg -i grafana_<version>_amd64.deb
```
### APT repository
To upgrade Grafana installed from the Grafana Labs APT repository, complete the following steps:
1. In your current installation of Grafana, save your custom configuration changes to a file named `<grafana_install_dir>/conf/custom.ini`.
This enables you to upgrade Grafana without the risk of losing your configuration changes.
1. Run the following commands:
```bash
sudo apt-get update
sudo apt-get upgrade
```
Grafana automatically updates when you run `apt-get upgrade`.
### Binary .tar file
To upgrade Grafana installed from the binary `.tar.gz` package, complete the following steps:
1. In your current installation of Grafana, save your custom configuration changes to a file named `<grafana_install_dir>/conf/custom.ini`.
This enables you to upgrade Grafana without the risk of losing your configuration changes.
1. [Download](https://grafana.com/grafana/download) the binary `.tar.gz` package.
1. Extract the downloaded package and overwrite the existing files.
### CentOS or RHEL
To upgrade Grafana running on CentOS or RHEL, complete the following steps:
1. In your current installation of Grafana, save your custom configuration changes to a file named `<grafana_install_dir>/conf/custom.ini`.
This enables you to upgrade Grafana without the risk of losing your configuration changes.
1. Perform one of the following steps based on your installation.
- If you [downloaded an RPM package](https://grafana.com/grafana/download) to install Grafana, then complete the steps documented in [Install on RPM-based Linux]({{< relref "../../setup-grafana/installation/rpm/" >}}) to upgrade Grafana.
- If you used the Grafana YUM repository, run the following command:
```bash
sudo yum update grafana
```
### Docker
To upgrade Grafana running in a Docker container, complete the following steps:
1. In your current installation of Grafana, save your custom configuration changes to a file named `<grafana_install_dir>/conf/custom.ini`.
This enables you to upgrade Grafana without the risk of losing your configuration changes.
1. Run a commands similar to the following commands.
> **Note:** This is an example. The parameters you enter depend on how you configured your Grafana container.
```bash
docker pull grafana/grafana
docker stop my-grafana-container
docker rm my-grafana-container
docker run -d --name=my-grafana-container --restart=always -v /var/lib/grafana:/var/lib/grafana grafana/grafana
```
### Windows
To upgrade Grafana installed on Windows, complete the following steps:
1. In your current installation of Grafana, save your custom configuration changes to a file named `<grafana_install_dir>/conf/custom.ini`.
This enables you to upgrade Grafana without the risk of losing your configuration changes.
1. [Download](https://grafana.com/grafana/download) the Windows binary package.
1. Extract the contents of the package to the location in which you installed Grafana.
You can overwrite existing files and folders, when prompted.
### Mac
To upgrade Grafana installed on Mac, complete the following steps:
1. In your current installation of Grafana, save your custom configuration changes to a file named `<grafana_install_dir>/conf/custom.ini`.
This enables you to upgrade Grafana without the risk of losing your configuration changes.
1. [Download](https://grafana.com/grafana/download) the Mac binary package.
1. Extract the contents of the package to the location in which you installed Grafana.
You can overwrite existing files and folders, when prompted.
## Update Grafana plugins
After you upgrade Grafana, we recommend that you update all plugins because a new version of Grafana
can make older plugins stop working properly.
Run the following command to update plugins:
```bash
grafana-cli plugins update-all
```
| docs/sources/shared/upgrade/upgrade-common-tasks.md | 0 | https://github.com/grafana/grafana/commit/c235ad67e778a1c2ecf4e43c9f3db7df146c9e89 | [
0.0001765886408975348,
0.00017157394904643297,
0.00016544281970709562,
0.00017226659110747278,
0.000003137719659207505
] |
{
"id": 2,
"code_window": [
" {this.renderExpression(item.expr, `item-${j}`)}\n",
" </div>\n",
" ))}\n",
" </div>\n",
" ))}\n",
" </div>\n",
" );\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" <div>\n",
" If you are seeing masked data, you may have CloudWatch logs data protection enabled.{' '}\n",
" <a\n",
" className={cx(link)}\n",
" href=\"https://grafana.com/docs/grafana/latest/datasources/aws-cloudwatch/#cloudwatch-logs-data-protection\"\n",
" target=\"_blank\"\n",
" rel=\"noreferrer\"\n",
" >\n",
" See documentation for details\n",
" </a>\n",
" .\n",
" </div>\n"
],
"file_path": "public/app/plugins/datasource/cloudwatch/components/LogsCheatSheet.tsx",
"type": "add",
"edit_start_line_idx": 282
} | ---
aliases:
- ../data-sources/aws-cloudwatch/
- ../data-sources/aws-cloudwatch/preconfig-cloudwatch-dashboards/
- ../data-sources/aws-cloudwatch/provision-cloudwatch/
- cloudwatch/
- preconfig-cloudwatch-dashboards/
- provision-cloudwatch/
description: Guide for using Amazon CloudWatch in Grafana
keywords:
- grafana
- cloudwatch
- guide
menuTitle: Amazon CloudWatch
title: Amazon CloudWatch data source
weight: 200
---
# Amazon CloudWatch data source
Grafana ships with built-in support for Amazon CloudWatch.
This topic describes queries, templates, variables, and other configuration specific to the CloudWatch data source.
For instructions on how to add a data source to Grafana, refer to the [administration documentation]({{< relref "../../administration/data-source-management/" >}}).
Only users with the organization administrator role can add data sources.
Administrators can also [provision the data source]({{< relref "#provision-the-data-source" >}}) with Grafana's provisioning system, and should [control pricing]({{< relref "#control-pricing" >}}) and [manage service quotas]({{< relref "#manage-service-quotas" >}}) accordingly.
Once you've added the data source, you can [configure it]({{< relref "#configure-the-data-source" >}}) so that your Grafana instance's users can create queries in its [query editor]({{< relref "./query-editor/" >}}) when they [build dashboards]({{< relref "../../dashboards/build-dashboards/" >}}) and use [Explore]({{< relref "../../explore/" >}}).
> **Note:** To troubleshoot issues while setting up the CloudWatch data source, check the `/var/log/grafana/grafana.log` file.
## Configure the data source
**To access the data source configuration page:**
1. Hover the cursor over the **Configuration** (gear) icon.
1. Select **Data Sources**.
1. Select the CloudWatch data source.
### Configure AWS authentication
A Grafana plugin's requests to AWS are made on behalf of an AWS Identity and Access Management (IAM) role or IAM user.
The IAM user or IAM role must have the associated policies to perform certain API actions.
For authentication options and configuration details, refer to [AWS authentication]({{< relref "./aws-authentication/" >}}).
#### IAM policy examples
To read CloudWatch metrics and EC2 tags, instances, regions, and alarms, you must grant Grafana permissions via IAM.
You can attach these permissions to the IAM role or IAM user you configured in [AWS authentication]({{< relref "./aws-authentication/" >}}).
**Metrics-only:**
```json
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AllowReadingMetricsFromCloudWatch",
"Effect": "Allow",
"Action": [
"cloudwatch:DescribeAlarmsForMetric",
"cloudwatch:DescribeAlarmHistory",
"cloudwatch:DescribeAlarms",
"cloudwatch:ListMetrics",
"cloudwatch:GetMetricData",
"cloudwatch:GetInsightRuleReport"
],
"Resource": "*"
},
{
"Sid": "AllowReadingTagsInstancesRegionsFromEC2",
"Effect": "Allow",
"Action": ["ec2:DescribeTags", "ec2:DescribeInstances", "ec2:DescribeRegions"],
"Resource": "*"
},
{
"Sid": "AllowReadingResourcesForTags",
"Effect": "Allow",
"Action": "tag:GetResources",
"Resource": "*"
}
]
}
```
**Logs-only:**
```json
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AllowReadingLogsFromCloudWatch",
"Effect": "Allow",
"Action": [
"logs:DescribeLogGroups",
"logs:GetLogGroupFields",
"logs:StartQuery",
"logs:StopQuery",
"logs:GetQueryResults",
"logs:GetLogEvents"
],
"Resource": "*"
},
{
"Sid": "AllowReadingTagsInstancesRegionsFromEC2",
"Effect": "Allow",
"Action": ["ec2:DescribeTags", "ec2:DescribeInstances", "ec2:DescribeRegions"],
"Resource": "*"
},
{
"Sid": "AllowReadingResourcesForTags",
"Effect": "Allow",
"Action": "tag:GetResources",
"Resource": "*"
}
]
}
```
**Metrics and Logs:**
```json
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AllowReadingMetricsFromCloudWatch",
"Effect": "Allow",
"Action": [
"cloudwatch:DescribeAlarmsForMetric",
"cloudwatch:DescribeAlarmHistory",
"cloudwatch:DescribeAlarms",
"cloudwatch:ListMetrics",
"cloudwatch:GetMetricData",
"cloudwatch:GetInsightRuleReport"
],
"Resource": "*"
},
{
"Sid": "AllowReadingLogsFromCloudWatch",
"Effect": "Allow",
"Action": [
"logs:DescribeLogGroups",
"logs:GetLogGroupFields",
"logs:StartQuery",
"logs:StopQuery",
"logs:GetQueryResults",
"logs:GetLogEvents"
],
"Resource": "*"
},
{
"Sid": "AllowReadingTagsInstancesRegionsFromEC2",
"Effect": "Allow",
"Action": ["ec2:DescribeTags", "ec2:DescribeInstances", "ec2:DescribeRegions"],
"Resource": "*"
},
{
"Sid": "AllowReadingResourcesForTags",
"Effect": "Allow",
"Action": "tag:GetResources",
"Resource": "*"
}
]
}
```
**Cross-account observability: (see below) **
```json
{
"Version": "2012-10-17",
"Statement": [
{
"Action": ["oam:ListSinks", "oam:ListAttachedLinks"],
"Effect": "Allow",
"Resource": "*"
}
]
}
```
### Configure CloudWatch settings
#### Namespaces of Custom Metrics
Grafana can't load custom namespaces through the CloudWatch [GetMetricData API](https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_GetMetricData.html).
To make custom metrics appear in the data source's query editor fields, specify the names of the namespaces containing the custom metrics in the data source configuration's _Namespaces of Custom Metrics_ field.
The field accepts multiple namespaces separated by commas.
#### Timeout
Configure the timeout specifically for CloudWatch Logs queries.
Log queries don't keep a single request open, and instead periodically poll for results.
Therefore, they don't recognize the standard Grafana query timeout.
Because of limits on concurrently running queries in CloudWatch, they can also take longer to finish.
#### X-Ray trace links
To automatically add links in your logs when the log contains the `@xrayTraceId` field, link an X-Ray data source in the "X-Ray trace link" section of the data source configuration.
{{< figure src="/static/img/docs/cloudwatch/xray-trace-link-configuration-8-2.png" max-width="800px" class="docs-image--no-shadow" caption="Trace link configuration" >}}
The data source select contains only existing data source instances of type X-Ray.
To use this feature, you must already have an X-Ray data source configured.
For details, see the [X-Ray data source docs](/grafana/plugins/grafana-x-ray-datasource/).
To view the X-Ray link, select the log row in either the Explore view or dashboard [Logs panel]({{< relref "../../panels-visualizations/visualizations/logs" >}}) to view the log details section.
To log the `@xrayTraceId`, see the [AWS X-Ray documentation](https://docs.amazonaws.cn/en_us/xray/latest/devguide/xray-services.html).
To provide the field to Grafana, your log queries must also contain the `@xrayTraceId` field, for example by using the query `fields @message, @xrayTraceId`.
{{< figure src="/static/img/docs/cloudwatch/xray-link-log-details-8-2.png" max-width="800px" class="docs-image--no-shadow" caption="Trace link in log details" >}}
### Configure the data source with grafana.ini
The Grafana [configuration file]({{< relref "../../setup-grafana/configure-grafana#aws" >}}) includes an `AWS` section where you can configure data source options:
| Configuration option | Description |
| ------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `allowed_auth_providers` | Specifies which authentication providers are allowed for the CloudWatch data source. The following providers are enabled by default in open-source Grafana: `default` (AWS SDK default), keys (Access and secret key), credentials (Credentials file), ec2_IAM_role (EC2 IAM role). |
| `assume_role_enabled` | Allows you to disable `assume role (ARN)` in the CloudWatch data source. The assume role (ARN) is enabled by default in open-source Grafana. |
| `list_metrics_page_limit` | Sets the limit of List Metrics API pages. When a custom namespace is specified in the query editor, the [List Metrics API](https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_ListMetrics.html) populates the _Metrics_ field and _Dimension_ fields. The API is paginated and returns up to 500 results per page, and the data source also limits the number of pages to 500 by default. This setting customizes that limit. |
### Provision the data source
You can define and configure the data source in YAML files as part of Grafana's provisioning system.
For more information about provisioning, and for available configuration options, refer to [Provisioning Grafana]({{< relref "../../administration/provisioning/#data-sources" >}}).
#### Provisioning examples
**Using AWS SDK (default):**
```yaml
apiVersion: 1
datasources:
- name: CloudWatch
type: cloudwatch
jsonData:
authType: default
defaultRegion: eu-west-2
```
**Using credentials' profile name (non-default):**
```yaml
apiVersion: 1
datasources:
- name: CloudWatch
type: cloudwatch
jsonData:
authType: credentials
defaultRegion: eu-west-2
customMetricsNamespaces: 'CWAgent,CustomNameSpace'
profile: secondary
```
**Using accessKey and secretKey:**
```yaml
apiVersion: 1
datasources:
- name: CloudWatch
type: cloudwatch
jsonData:
authType: keys
defaultRegion: eu-west-2
secureJsonData:
accessKey: '<your access key>'
secretKey: '<your secret key>'
```
**Using AWS SDK Default and ARN of IAM Role to Assume:**
```yaml
apiVersion: 1
datasources:
- name: CloudWatch
type: cloudwatch
jsonData:
authType: default
assumeRoleArn: arn:aws:iam::123456789012:root
defaultRegion: eu-west-2
```
## Query the data source
The CloudWatch data source can query data from both CloudWatch metrics and CloudWatch Logs APIs, each with its own specialized query editor.
For details, see the [query editor documentation]({{< relref "./query-editor/" >}}).
## Use template variables
Instead of hard-coding details such as server, application, and sensor names in metric queries, you can use variables.
Grafana lists these variables in dropdown select boxes at the top of the dashboard to help you change the data displayed in your dashboard.
Grafana refers to such variables as template variables.
For details, see the [template variables documentation]({{< relref "./template-variables/" >}}).
## Import pre-configured dashboards
The CloudWatch data source ships with curated and pre-configured dashboards for five of the most popular AWS services:
- **Amazon Elastic Compute Cloud:** `Amazon EC2`
- **Amazon Elastic Block Store:** `Amazon EBS`
- **AWS Lambda:** `AWS Lambda`
- **Amazon CloudWatch Logs:** `Amazon CloudWatch Logs`
- **Amazon Relational Database Service:** `Amazon RDS`
**To import curated dashboards:**
1. Navigate to the data source's [configuration page]({{< relref "#configure-the-data-source" >}}).
1. Select the **Dashboards** tab.
This displays the curated selection of importable dashboards.
1. Select **Import** for the dashboard to import.
{{< figure src="/static/img/docs/v65/cloudwatch-dashboard-import.png" caption="CloudWatch dashboard import" >}}
**To customize an imported dashboard:**
To customize one of these dashboards, we recommend that you save it under a different name.
If you don't, upgrading Grafana can overwrite the customized dashboard with the new version.
## Create queries for alerting
Alerting requires queries that return numeric data, which CloudWatch Logs support.
For example, you can enable alerts through the use of the `stats` command.
This is also a valid query for alerting on messages that include the text "Exception":
```
filter @message like /Exception/
| stats count(*) as exceptionCount by bin(1h)
| sort exceptionCount desc
```
> **Note:** If you receive an error like `input data must be a wide series but got ...` when trying to alert on a query, make sure that your query returns valid numeric data that can be output to a Time series panel.
For more information on Grafana alerts, refer to [Alerting]({{< relref "../../alerting" >}}).
## Control pricing
The Amazon CloudWatch data source for Grafana uses [`ListMetrics`](https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_ListMetrics.html) and [`GetMetricData`](https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_GetMetricData.html) CloudWatch API calls to list and retrieve metrics.
Pricing for CloudWatch Logs is based on the amount of data ingested, archived, and analyzed via CloudWatch Logs Insights queries.
Each time you select a dimension in the query editor, Grafana issues a `ListMetrics` API request.
Each time you change queries in the query editor, Grafana issues a new request to the `GetMetricData` API.
> **Note:** Grafana v6.5 and higher replaced all `GetMetricStatistics` API requests with calls to GetMetricData to provide better support for CloudWatch metric math, and enables the automatic generation of search expressions when using wildcards or disabling the `Match Exact` option.
> The `GetMetricStatistics` API qualified for the CloudWatch API free tier, but `GetMetricData` calls don't.
For more information, refer to the [CloudWatch pricing page](https://aws.amazon.com/cloudwatch/pricing/).
## Manage service quotas
AWS defines quotas, or limits, for resources, actions, and items in your AWS account.
Depending on the number of queries in your dashboard and the number of users accessing the dashboard, you might reach the usage limits for various CloudWatch and CloudWatch Logs resources.
Quotas are defined per account and per region.
If you use multiple regions or configured more than one CloudWatch data source to query against multiple accounts, you must request a quota increase for each account and region in which you reach the limit.
To request a quota increase, visit the [AWS Service Quotas console](https://console.aws.amazon.com/servicequotas/home?r#!/services/monitoring/quotas/L-5E141212).
For more information, refer to the AWS documentation for [Service Quotas](https://docs.aws.amazon.com/servicequotas/latest/userguide/intro.html) and [CloudWatch limits](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch_limits.html).
## Cross-account observability
The CloudWatch plugin enables you to monitor and troubleshoot applications across multiple regional accounts. Using cross-account observability, you can seamlessly search, visualize and analyze metrics and logs without worrying about account boundaries.
To use this feature, configure in the [AWS console under Cloudwatch Settings](https://aws.amazon.com/blogs/aws/new-amazon-cloudwatch-cross-account-observability/), a monitoring and source account, and then add the necessary IAM permissions as described above.
| docs/sources/datasources/aws-cloudwatch/_index.md | 1 | https://github.com/grafana/grafana/commit/c235ad67e778a1c2ecf4e43c9f3db7df146c9e89 | [
0.00017549439508002251,
0.00017059505626093596,
0.00016234042413998395,
0.00017193856183439493,
0.0000037671022710128454
] |
{
"id": 2,
"code_window": [
" {this.renderExpression(item.expr, `item-${j}`)}\n",
" </div>\n",
" ))}\n",
" </div>\n",
" ))}\n",
" </div>\n",
" );\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" <div>\n",
" If you are seeing masked data, you may have CloudWatch logs data protection enabled.{' '}\n",
" <a\n",
" className={cx(link)}\n",
" href=\"https://grafana.com/docs/grafana/latest/datasources/aws-cloudwatch/#cloudwatch-logs-data-protection\"\n",
" target=\"_blank\"\n",
" rel=\"noreferrer\"\n",
" >\n",
" See documentation for details\n",
" </a>\n",
" .\n",
" </div>\n"
],
"file_path": "public/app/plugins/datasource/cloudwatch/components/LogsCheatSheet.tsx",
"type": "add",
"edit_start_line_idx": 282
} | <svg xmlns="http://www.w3.org/2000/svg" data-name="Layer 1" viewBox="0 0 24 24"><path d="M12,2.2467A10.00042,10.00042,0,0,0,8.83752,21.73419c.5.08752.6875-.21247.6875-.475,0-.23749-.01251-1.025-.01251-1.86249C7,19.85919,6.35,18.78423,6.15,18.22173A3.636,3.636,0,0,0,5.125,16.8092c-.35-.1875-.85-.65-.01251-.66248A2.00117,2.00117,0,0,1,6.65,17.17169a2.13742,2.13742,0,0,0,2.91248.825A2.10376,2.10376,0,0,1,10.2,16.65923c-2.225-.25-4.55-1.11254-4.55-4.9375a3.89187,3.89187,0,0,1,1.025-2.6875,3.59373,3.59373,0,0,1,.1-2.65s.83747-.26251,2.75,1.025a9.42747,9.42747,0,0,1,5,0c1.91248-1.3,2.75-1.025,2.75-1.025a3.59323,3.59323,0,0,1,.1,2.65,3.869,3.869,0,0,1,1.025,2.6875c0,3.83747-2.33752,4.6875-4.5625,4.9375a2.36814,2.36814,0,0,1,.675,1.85c0,1.33752-.01251,2.41248-.01251,2.75,0,.26251.1875.575.6875.475A10.0053,10.0053,0,0,0,12,2.2467Z"/></svg> | public/img/icons/unicons/github.svg | 0 | https://github.com/grafana/grafana/commit/c235ad67e778a1c2ecf4e43c9f3db7df146c9e89 | [
0.00022672105114907026,
0.00022672105114907026,
0.00022672105114907026,
0.00022672105114907026,
0
] |
{
"id": 2,
"code_window": [
" {this.renderExpression(item.expr, `item-${j}`)}\n",
" </div>\n",
" ))}\n",
" </div>\n",
" ))}\n",
" </div>\n",
" );\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" <div>\n",
" If you are seeing masked data, you may have CloudWatch logs data protection enabled.{' '}\n",
" <a\n",
" className={cx(link)}\n",
" href=\"https://grafana.com/docs/grafana/latest/datasources/aws-cloudwatch/#cloudwatch-logs-data-protection\"\n",
" target=\"_blank\"\n",
" rel=\"noreferrer\"\n",
" >\n",
" See documentation for details\n",
" </a>\n",
" .\n",
" </div>\n"
],
"file_path": "public/app/plugins/datasource/cloudwatch/components/LogsCheatSheet.tsx",
"type": "add",
"edit_start_line_idx": 282
} | <svg xmlns="http://www.w3.org/2000/svg" data-name="Layer 1" viewBox="0 0 24 24"><path d="M14.29,14.19,11,17.48,9.71,16.19a1,1,0,0,0-1.42,0,1,1,0,0,0,0,1.41l2,2a1,1,0,0,0,1.42,0l4-4a1,1,0,0,0,0-1.41A1,1,0,0,0,14.29,14.19Zm4.13-5.87a7,7,0,0,0-13.36,1.9,4,4,0,0,0-.38,7.65A1,1,0,1,0,5.32,16,2,2,0,0,1,4,14.1a2,2,0,0,1,2-2,1,1,0,0,0,1-1,5,5,0,0,1,9.73-1.6,1,1,0,0,0,.78.66A3,3,0,0,1,17.75,16,1,1,0,0,0,18,18l.25,0a5,5,0,0,0,.17-9.62Z"/></svg> | public/img/icons/unicons/cloud-check.svg | 0 | https://github.com/grafana/grafana/commit/c235ad67e778a1c2ecf4e43c9f3db7df146c9e89 | [
0.00017325695080216974,
0.00017325695080216974,
0.00017325695080216974,
0.00017325695080216974,
0
] |
{
"id": 2,
"code_window": [
" {this.renderExpression(item.expr, `item-${j}`)}\n",
" </div>\n",
" ))}\n",
" </div>\n",
" ))}\n",
" </div>\n",
" );\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" <div>\n",
" If you are seeing masked data, you may have CloudWatch logs data protection enabled.{' '}\n",
" <a\n",
" className={cx(link)}\n",
" href=\"https://grafana.com/docs/grafana/latest/datasources/aws-cloudwatch/#cloudwatch-logs-data-protection\"\n",
" target=\"_blank\"\n",
" rel=\"noreferrer\"\n",
" >\n",
" See documentation for details\n",
" </a>\n",
" .\n",
" </div>\n"
],
"file_path": "public/app/plugins/datasource/cloudwatch/components/LogsCheatSheet.tsx",
"type": "add",
"edit_start_line_idx": 282
} | import { QueryEditorProps } from '@grafana/data';
import { PrometheusDatasource } from '../datasource';
import { PromOptions, PromQuery } from '../types';
export type PromQueryEditorProps = QueryEditorProps<PrometheusDatasource, PromQuery, PromOptions>;
| public/app/plugins/datasource/prometheus/components/types.ts | 0 | https://github.com/grafana/grafana/commit/c235ad67e778a1c2ecf4e43c9f3db7df146c9e89 | [
0.00017660514276940376,
0.00017660514276940376,
0.00017660514276940376,
0.00017660514276940376,
0
] |
{
"id": 0,
"code_window": [
"\t\tconst request: IInlineChatRequest = {\n",
"\t\t\trequestId: generateUuid(),\n",
"\t\t\tprompt: this._activeSession.lastInput.value,\n",
"\t\t\tattempt: this._activeSession.lastInput.attempt,\n",
"\t\t\tselection: this._editor.getSelection(),\n",
"\t\t\twholeRange: this._activeSession.wholeRange.value,\n",
"\t\t\tlive: this._activeSession.editMode !== EditMode.Preview // TODO@jrieken let extension know what document is used for previewing\n",
"\t\t};\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\twholeRange: this._activeSession.wholeRange.trackedInitialRange,\n"
],
"file_path": "src/vs/workbench/contrib/inlineChat/browser/inlineChatController.ts",
"type": "replace",
"edit_start_line_idx": 604
} | /*---------------------------------------------------------------------------------------------
* 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 { equals } from 'vs/base/common/arrays';
import { Emitter, Event } from 'vs/base/common/event';
import { DisposableStore } from 'vs/base/common/lifecycle';
import { mock } from 'vs/base/test/common/mock';
import { ensureNoDisposablesAreLeakedInTestSuite } from 'vs/base/test/common/utils';
import { TestDiffProviderFactoryService } from 'vs/editor/browser/diff/testDiffProviderFactoryService';
import { IActiveCodeEditor } from 'vs/editor/browser/editorBrowser';
import { IDiffProviderFactoryService } from 'vs/editor/browser/widget/diffEditor/diffProviderFactoryService';
import { Range } from 'vs/editor/common/core/range';
import { ITextModel } from 'vs/editor/common/model';
import { IModelService } from 'vs/editor/common/services/model';
import { instantiateTestCodeEditor } from 'vs/editor/test/browser/testCodeEditor';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { TestConfigurationService } from 'vs/platform/configuration/test/common/testConfigurationService';
import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { SyncDescriptor } from 'vs/platform/instantiation/common/descriptors';
import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection';
import { TestInstantiationService } from 'vs/platform/instantiation/test/common/instantiationServiceMock';
import { MockContextKeyService } from 'vs/platform/keybinding/test/common/mockKeybindingService';
import { IEditorProgressService, IProgressRunner } from 'vs/platform/progress/common/progress';
import { IViewDescriptorService } from 'vs/workbench/common/views';
import { AccessibilityVerbositySettingId } from 'vs/workbench/contrib/accessibility/browser/accessibilityConfiguration';
import { IAccessibleViewService } from 'vs/workbench/contrib/accessibility/browser/accessibleView';
import { IChatAccessibilityService } from 'vs/workbench/contrib/chat/browser/chat';
import { IChatResponseViewModel } from 'vs/workbench/contrib/chat/common/chatViewModel';
import { InlineChatController, InlineChatRunOptions, State } from 'vs/workbench/contrib/inlineChat/browser/inlineChatController';
import { IInlineChatSessionService, InlineChatSessionService } from 'vs/workbench/contrib/inlineChat/browser/inlineChatSession';
import { IInlineChatService, InlineChatConfigKeys, InlineChatResponseType } from 'vs/workbench/contrib/inlineChat/common/inlineChat';
import { InlineChatServiceImpl } from 'vs/workbench/contrib/inlineChat/common/inlineChatServiceImpl';
import { workbenchInstantiationService } from 'vs/workbench/test/browser/workbenchTestServices';
suite('InteractiveChatController', function () {
class TestController extends InlineChatController {
static INIT_SEQUENCE: readonly State[] = [State.CREATE_SESSION, State.INIT_UI, State.WAIT_FOR_INPUT];
static INIT_SEQUENCE_AUTO_SEND: readonly State[] = [...this.INIT_SEQUENCE, State.MAKE_REQUEST, State.APPLY_RESPONSE, State.SHOW_RESPONSE, State.WAIT_FOR_INPUT];
private readonly _onDidChangeState = new Emitter<State>();
readonly onDidChangeState: Event<State> = this._onDidChangeState.event;
readonly states: readonly State[] = [];
waitFor(states: readonly State[]): Promise<void> {
const actual: State[] = [];
return new Promise<void>((resolve, reject) => {
const d = this.onDidChangeState(state => {
actual.push(state);
if (equals(states, actual)) {
d.dispose();
resolve();
}
});
setTimeout(() => {
d.dispose();
reject(`timeout, \nWANTED ${states.join('>')}, \nGOT ${actual.join('>')}`);
}, 1000);
});
}
protected override async _nextState(state: State, options: InlineChatRunOptions): Promise<void> {
let nextState: State | void = state;
while (nextState) {
this._onDidChangeState.fire(nextState);
(<State[]>this.states).push(nextState);
nextState = await this[nextState](options);
}
}
override dispose() {
super.dispose();
this._onDidChangeState.dispose();
}
}
const store = new DisposableStore();
let configurationService: TestConfigurationService;
let editor: IActiveCodeEditor;
let model: ITextModel;
let ctrl: TestController;
// let contextKeys: MockContextKeyService;
let inlineChatService: InlineChatServiceImpl;
let inlineChatSessionService: IInlineChatSessionService;
let instaService: TestInstantiationService;
setup(function () {
const contextKeyService = new MockContextKeyService();
inlineChatService = new InlineChatServiceImpl(contextKeyService);
configurationService = new TestConfigurationService();
configurationService.setUserConfiguration('chat', { editor: { fontSize: 14, fontFamily: 'default' } });
configurationService.setUserConfiguration('editor', {});
const serviceCollection = new ServiceCollection(
[IContextKeyService, contextKeyService],
[IInlineChatService, inlineChatService],
[IDiffProviderFactoryService, new SyncDescriptor(TestDiffProviderFactoryService)],
[IInlineChatSessionService, new SyncDescriptor(InlineChatSessionService)],
[IEditorProgressService, new class extends mock<IEditorProgressService>() {
override show(total: unknown, delay?: unknown): IProgressRunner {
return {
total() { },
worked(value) { },
done() { },
};
}
}],
[IChatAccessibilityService, new class extends mock<IChatAccessibilityService>() {
override acceptResponse(response: IChatResponseViewModel | undefined, requestId: number): void { }
override acceptRequest(): number { return -1; }
}],
[IAccessibleViewService, new class extends mock<IAccessibleViewService>() {
override getOpenAriaHint(verbositySettingKey: AccessibilityVerbositySettingId): string | null {
return null;
}
}],
[IConfigurationService, configurationService],
[IViewDescriptorService, new class extends mock<IViewDescriptorService>() {
override onDidChangeLocation = Event.None;
}]
);
instaService = store.add(workbenchInstantiationService(undefined, store).createChild(serviceCollection));
inlineChatSessionService = store.add(instaService.get(IInlineChatSessionService));
model = store.add(instaService.get(IModelService).createModel('Hello\nWorld\nHello Again\nHello World\n', null));
editor = store.add(instantiateTestCodeEditor(instaService, model));
store.add(inlineChatService.addProvider({
debugName: 'Unit Test',
label: 'Unit Test',
prepareInlineChatSession() {
return {
id: Math.random()
};
},
provideResponse(session, request) {
return {
type: InlineChatResponseType.EditorEdit,
id: Math.random(),
edits: [{
range: new Range(1, 1, 1, 1),
text: request.prompt
}]
};
}
}));
});
teardown(function () {
store.clear();
ctrl?.dispose();
});
ensureNoDisposablesAreLeakedInTestSuite();
test('creation, not showing anything', function () {
ctrl = instaService.createInstance(TestController, editor);
assert.ok(ctrl);
assert.strictEqual(ctrl.getWidgetPosition(), undefined);
});
test('run (show/hide)', async function () {
ctrl = instaService.createInstance(TestController, editor);
const p = ctrl.waitFor(TestController.INIT_SEQUENCE_AUTO_SEND);
const run = ctrl.run({ message: 'Hello', autoSend: true });
await p;
assert.ok(ctrl.getWidgetPosition() !== undefined);
await ctrl.cancelSession();
await run;
assert.ok(ctrl.getWidgetPosition() === undefined);
});
test('wholeRange expands to whole lines, editor selection default', async function () {
editor.setSelection(new Range(1, 1, 1, 3));
ctrl = instaService.createInstance(TestController, editor);
const d = inlineChatService.addProvider({
debugName: 'Unit Test',
label: 'Unit Test',
prepareInlineChatSession() {
return {
id: Math.random()
};
},
provideResponse(session, request) {
throw new Error();
}
});
ctrl.run({});
await Event.toPromise(Event.filter(ctrl.onDidChangeState, e => e === State.WAIT_FOR_INPUT));
const session = inlineChatSessionService.getSession(editor, editor.getModel()!.uri);
assert.ok(session);
assert.deepStrictEqual(session.wholeRange.value, new Range(1, 1, 1, 6));
await ctrl.cancelSession();
d.dispose();
});
test('wholeRange expands to whole lines, session provided', async function () {
editor.setSelection(new Range(1, 1, 1, 1));
ctrl = instaService.createInstance(TestController, editor);
const d = inlineChatService.addProvider({
debugName: 'Unit Test',
label: 'Unit Test',
prepareInlineChatSession() {
return {
id: Math.random(),
wholeRange: new Range(1, 1, 1, 3)
};
},
provideResponse(session, request) {
throw new Error();
}
});
ctrl.run({});
await Event.toPromise(Event.filter(ctrl.onDidChangeState, e => e === State.WAIT_FOR_INPUT));
const session = inlineChatSessionService.getSession(editor, editor.getModel()!.uri);
assert.ok(session);
assert.deepStrictEqual(session.wholeRange.value, new Range(1, 1, 1, 6));
await ctrl.cancelSession();
d.dispose();
});
test('typing outside of wholeRange finishes session', async function () {
configurationService.setUserConfiguration(InlineChatConfigKeys.FinishOnType, true);
ctrl = instaService.createInstance(TestController, editor);
const p = ctrl.waitFor(TestController.INIT_SEQUENCE_AUTO_SEND);
const r = ctrl.run({ message: 'Hello', autoSend: true });
await p;
const session = inlineChatSessionService.getSession(editor, editor.getModel()!.uri);
assert.ok(session);
assert.deepStrictEqual(session.wholeRange.value, new Range(1, 1, 1, 11));
editor.setSelection(new Range(2, 1, 2, 1));
editor.trigger('test', 'type', { text: 'a' });
await ctrl.waitFor([State.ACCEPT]);
await r;
});
test('\'whole range\' isn\'t updated for edits outside whole range #4346', async function () {
editor.setSelection(new Range(3, 1, 3, 1));
const d = inlineChatService.addProvider({
debugName: 'Unit Test',
label: 'Unit Test',
prepareInlineChatSession() {
return {
id: Math.random(),
wholeRange: new Range(3, 1, 3, 3)
};
},
provideResponse(session, request) {
return {
type: InlineChatResponseType.EditorEdit,
id: Math.random(),
edits: [{
range: new Range(1, 1, 1, 1), // EDIT happens outside of whole range
text: `${request.prompt}\n${request.prompt}`
}]
};
}
});
store.add(d);
ctrl = instaService.createInstance(TestController, editor);
const p = ctrl.waitFor(TestController.INIT_SEQUENCE);
const r = ctrl.run({ message: 'Hello', autoSend: false });
await p;
const session = inlineChatSessionService.getSession(editor, editor.getModel()!.uri);
assert.ok(session);
assert.deepStrictEqual(session.wholeRange.value, new Range(3, 1, 3, 12));
ctrl.acceptInput();
await ctrl.waitFor([State.MAKE_REQUEST, State.APPLY_RESPONSE, State.SHOW_RESPONSE, State.WAIT_FOR_INPUT]);
assert.deepStrictEqual(session.wholeRange.value, new Range(4, 1, 4, 12));
await ctrl.cancelSession();
await r;
});
test('Stuck inline chat widget #211', async function () {
const d = inlineChatService.addProvider({
debugName: 'Unit Test',
label: 'Unit Test',
prepareInlineChatSession() {
return {
id: Math.random(),
wholeRange: new Range(3, 1, 3, 3)
};
},
provideResponse(session, request) {
return new Promise<never>(() => { });
}
});
store.add(d);
ctrl = instaService.createInstance(TestController, editor);
const p = ctrl.waitFor([...TestController.INIT_SEQUENCE, State.MAKE_REQUEST]);
const r = ctrl.run({ message: 'Hello', autoSend: true });
await p;
ctrl.acceptSession();
await r;
assert.strictEqual(ctrl.getWidgetPosition(), undefined);
});
test('[Bug] Inline Chat\'s streaming pushed broken iterations to the undo stack #2403', async function () {
const d = inlineChatService.addProvider({
debugName: 'Unit Test',
label: 'Unit Test',
prepareInlineChatSession() {
return {
id: Math.random(),
wholeRange: new Range(3, 1, 3, 3)
};
},
async provideResponse(session, request, progress) {
progress.report({ edits: [{ range: new Range(1, 1, 1, 1), text: 'hEllo1\n' }] });
progress.report({ edits: [{ range: new Range(2, 1, 2, 1), text: 'hEllo2\n' }] });
return {
id: Math.random(),
type: InlineChatResponseType.EditorEdit,
edits: [{ range: new Range(1, 1, 1000, 1), text: 'Hello1\nHello2\n' }]
};
}
});
const valueThen = editor.getModel().getValue();
store.add(d);
ctrl = instaService.createInstance(TestController, editor);
const p = ctrl.waitFor([...TestController.INIT_SEQUENCE, State.MAKE_REQUEST, State.APPLY_RESPONSE, State.SHOW_RESPONSE, State.WAIT_FOR_INPUT]);
const r = ctrl.run({ message: 'Hello', autoSend: true });
await p;
ctrl.acceptSession();
await r;
assert.strictEqual(editor.getModel().getValue(), 'Hello1\nHello2\n');
editor.getModel().undo();
assert.strictEqual(editor.getModel().getValue(), valueThen);
});
});
| src/vs/workbench/contrib/inlineChat/test/browser/inlineChatController.test.ts | 1 | https://github.com/microsoft/vscode/commit/48a9149e6ad2cbc0f7ebfdb2ce6143627c077d1e | [
0.8066028356552124,
0.039633944630622864,
0.0001631545164855197,
0.00022463806089945138,
0.15475493669509888
] |
{
"id": 0,
"code_window": [
"\t\tconst request: IInlineChatRequest = {\n",
"\t\t\trequestId: generateUuid(),\n",
"\t\t\tprompt: this._activeSession.lastInput.value,\n",
"\t\t\tattempt: this._activeSession.lastInput.attempt,\n",
"\t\t\tselection: this._editor.getSelection(),\n",
"\t\t\twholeRange: this._activeSession.wholeRange.value,\n",
"\t\t\tlive: this._activeSession.editMode !== EditMode.Preview // TODO@jrieken let extension know what document is used for previewing\n",
"\t\t};\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\twholeRange: this._activeSession.wholeRange.trackedInitialRange,\n"
],
"file_path": "src/vs/workbench/contrib/inlineChat/browser/inlineChatController.ts",
"type": "replace",
"edit_start_line_idx": 604
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Disposable, Event, EventEmitter, FileDecoration, FileDecorationProvider, SourceControlHistoryItem, SourceControlHistoryItemChange, SourceControlHistoryItemGroup, SourceControlHistoryOptions, SourceControlHistoryProvider, ThemeIcon, Uri, window, l10n, LogOutputChannel } from 'vscode';
import { Repository, Resource } from './repository';
import { IDisposable, filterEvent } from './util';
import { toGitUri } from './uri';
import { Branch, RefType, Status } from './api/git';
import { emojify, ensureEmojis } from './emoji';
import { Operation } from './operation';
export class GitHistoryProvider implements SourceControlHistoryProvider, FileDecorationProvider, IDisposable {
private readonly _onDidChangeCurrentHistoryItemGroup = new EventEmitter<void>();
readonly onDidChangeCurrentHistoryItemGroup: Event<void> = this._onDidChangeCurrentHistoryItemGroup.event;
private readonly _onDidChangeDecorations = new EventEmitter<Uri[]>();
readonly onDidChangeFileDecorations: Event<Uri[]> = this._onDidChangeDecorations.event;
private _HEAD: Branch | undefined;
private _currentHistoryItemGroup: SourceControlHistoryItemGroup | undefined;
get currentHistoryItemGroup(): SourceControlHistoryItemGroup | undefined { return this._currentHistoryItemGroup; }
set currentHistoryItemGroup(value: SourceControlHistoryItemGroup | undefined) {
this._currentHistoryItemGroup = value;
this._onDidChangeCurrentHistoryItemGroup.fire();
}
private historyItemDecorations = new Map<string, FileDecoration>();
private disposables: Disposable[] = [];
constructor(protected readonly repository: Repository, private readonly logger: LogOutputChannel) {
this.disposables.push(repository.onDidRunGitStatus(this.onDidRunGitStatus, this));
this.disposables.push(filterEvent(repository.onDidRunOperation, e => e.operation === Operation.Refresh)(() => this._onDidChangeCurrentHistoryItemGroup.fire()));
this.disposables.push(window.registerFileDecorationProvider(this));
}
private async onDidRunGitStatus(): Promise<void> {
// Check if HEAD has changed
if (this._HEAD?.name === this.repository.HEAD?.name &&
this._HEAD?.commit === this.repository.HEAD?.commit &&
this._HEAD?.upstream?.name === this.repository.HEAD?.upstream?.name &&
this._HEAD?.upstream?.remote === this.repository.HEAD?.upstream?.remote &&
this._HEAD?.upstream?.commit === this.repository.HEAD?.upstream?.commit) {
return;
}
this._HEAD = this.repository.HEAD;
// Check if HEAD supports incoming/outgoing (not a tag, not detached)
if (!this._HEAD?.name || !this._HEAD?.commit || this._HEAD.type === RefType.Tag) {
this.currentHistoryItemGroup = undefined;
return;
}
this.currentHistoryItemGroup = {
id: `refs/heads/${this._HEAD.name}`,
label: this._HEAD.name,
upstream: this._HEAD.upstream ?
{
id: `refs/remotes/${this._HEAD.upstream.remote}/${this._HEAD.upstream.name}`,
label: `${this._HEAD.upstream.remote}/${this._HEAD.upstream.name}`,
} : undefined
};
}
async provideHistoryItems(historyItemGroupId: string, options: SourceControlHistoryOptions): Promise<SourceControlHistoryItem[]> {
//TODO@lszomoru - support limit and cursor
if (typeof options.limit === 'number') {
throw new Error('Unsupported options.');
}
if (typeof options.limit?.id !== 'string') {
throw new Error('Unsupported options.');
}
const optionsRef = options.limit.id;
const historyItemGroupIdRef = await this.repository.revParse(historyItemGroupId) ?? '';
const [commits, summary] = await Promise.all([
this.repository.log({ range: `${optionsRef}..${historyItemGroupIdRef}`, shortStats: true, sortByAuthorDate: true }),
this.getSummaryHistoryItem(optionsRef, historyItemGroupIdRef)
]);
await ensureEmojis();
const historyItems = commits.length === 0 ? [] : [summary];
historyItems.push(...commits.map(commit => {
const newLineIndex = commit.message.indexOf('\n');
const subject = newLineIndex !== -1 ? commit.message.substring(0, newLineIndex) : commit.message;
return {
id: commit.hash,
parentIds: commit.parents,
label: emojify(subject),
description: commit.authorName,
icon: new ThemeIcon('git-commit'),
timestamp: commit.authorDate?.getTime(),
statistics: commit.shortStat ?? { files: 0, insertions: 0, deletions: 0 },
};
}));
return historyItems;
}
async provideHistoryItemChanges(historyItemId: string): Promise<SourceControlHistoryItemChange[]> {
// The "All Changes" history item uses a special id
// which is a commit range instead of a single commit id
let [originalRef, modifiedRef] = historyItemId.includes('..')
? historyItemId.split('..') : [undefined, historyItemId];
if (!originalRef) {
const commit = await this.repository.getCommit(modifiedRef);
originalRef = commit.parents.length > 0 ? commit.parents[0] : `${modifiedRef}^`;
}
const historyItemChangesUri: Uri[] = [];
const historyItemChanges: SourceControlHistoryItemChange[] = [];
const changes = await this.repository.diffBetween(originalRef, modifiedRef);
for (const change of changes) {
const historyItemUri = change.uri.with({
query: `ref=${historyItemId}`
});
// History item change
historyItemChanges.push({
uri: historyItemUri,
originalUri: toGitUri(change.originalUri, originalRef),
modifiedUri: toGitUri(change.originalUri, modifiedRef),
renameUri: change.renameUri,
});
// History item change decoration
const fileDecoration = this.getHistoryItemChangeFileDecoration(change.status);
this.historyItemDecorations.set(historyItemUri.toString(), fileDecoration);
historyItemChangesUri.push(historyItemUri);
}
this._onDidChangeDecorations.fire(historyItemChangesUri);
return historyItemChanges;
}
async resolveHistoryItemGroupBase(historyItemGroupId: string): Promise<SourceControlHistoryItemGroup | undefined> {
// TODO - support for all history item groups
if (historyItemGroupId !== this.currentHistoryItemGroup?.id) {
return undefined;
}
if (this.currentHistoryItemGroup?.upstream) {
return this.currentHistoryItemGroup.upstream;
}
// Branch base
try {
const branchBase = await this.repository.getBranchBase(historyItemGroupId);
if (branchBase?.name && branchBase?.type === RefType.Head) {
return {
id: `refs/heads/${branchBase.name}`,
label: branchBase.name
};
}
if (branchBase?.name && branchBase.remote && branchBase?.type === RefType.RemoteHead) {
return {
id: `refs/remotes/${branchBase.remote}/${branchBase.name}`,
label: `${branchBase.remote}/${branchBase.name}`
};
}
}
catch (err) {
this.logger.error(`Failed to get branch base for '${historyItemGroupId}': ${err.message}`);
}
return undefined;
}
async resolveHistoryItemGroupCommonAncestor(refId1: string, refId2: string): Promise<{ id: string; ahead: number; behind: number } | undefined> {
const ancestor = await this.repository.getMergeBase(refId1, refId2);
if (!ancestor) {
return undefined;
}
const commitCount = await this.repository.getCommitCount(`${refId1}...${refId2}`);
return { id: ancestor, ahead: commitCount.ahead, behind: commitCount.behind };
}
provideFileDecoration(uri: Uri): FileDecoration | undefined {
return this.historyItemDecorations.get(uri.toString());
}
private getHistoryItemChangeFileDecoration(status: Status): FileDecoration {
const letter = Resource.getStatusLetter(status);
const tooltip = Resource.getStatusText(status);
const color = Resource.getStatusColor(status);
return new FileDecoration(letter, tooltip, color);
}
private async getSummaryHistoryItem(ref1: string, ref2: string): Promise<SourceControlHistoryItem> {
const statistics = await this.repository.diffBetweenShortStat(ref1, ref2);
return { id: `${ref1}..${ref2}`, parentIds: [], icon: new ThemeIcon('files'), label: l10n.t('All Changes'), statistics };
}
dispose(): void {
this.disposables.forEach(d => d.dispose());
}
}
| extensions/git/src/historyProvider.ts | 0 | https://github.com/microsoft/vscode/commit/48a9149e6ad2cbc0f7ebfdb2ce6143627c077d1e | [
0.00017666038183961064,
0.00017300968465860933,
0.00016473855066578835,
0.00017368988483212888,
0.0000027964115361100994
] |
{
"id": 0,
"code_window": [
"\t\tconst request: IInlineChatRequest = {\n",
"\t\t\trequestId: generateUuid(),\n",
"\t\t\tprompt: this._activeSession.lastInput.value,\n",
"\t\t\tattempt: this._activeSession.lastInput.attempt,\n",
"\t\t\tselection: this._editor.getSelection(),\n",
"\t\t\twholeRange: this._activeSession.wholeRange.value,\n",
"\t\t\tlive: this._activeSession.editMode !== EditMode.Preview // TODO@jrieken let extension know what document is used for previewing\n",
"\t\t};\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\twholeRange: this._activeSession.wholeRange.trackedInitialRange,\n"
],
"file_path": "src/vs/workbench/contrib/inlineChat/browser/inlineChatController.ts",
"type": "replace",
"edit_start_line_idx": 604
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { DeferredPromise } from 'vs/base/common/async';
import { VSBuffer } from 'vs/base/common/buffer';
import { CancellationToken } from 'vs/base/common/cancellation';
import { Emitter, Event } from 'vs/base/common/event';
import { Lazy } from 'vs/base/common/lazy';
import { Disposable } from 'vs/base/common/lifecycle';
import { IObservable, observableValue } from 'vs/base/common/observable';
import { language } from 'vs/base/common/platform';
import { WellDefinedPrefixTree } from 'vs/base/common/prefixTree';
import { removeAnsiEscapeCodes } from 'vs/base/common/strings';
import { localize } from 'vs/nls';
import { IUriIdentityService } from 'vs/platform/uriIdentity/common/uriIdentity';
import { IComputedStateAccessor, refreshComputedState } from 'vs/workbench/contrib/testing/common/getComputedState';
import { TestCoverage } from 'vs/workbench/contrib/testing/common/testCoverage';
import { TestId } from 'vs/workbench/contrib/testing/common/testId';
import { makeEmptyCounts, maxPriority, statesInOrder, terminalStatePriorities, TestStateCount } from 'vs/workbench/contrib/testing/common/testingStates';
import { getMarkId, IRichLocation, ISerializedTestResults, ITestItem, ITestMessage, ITestOutputMessage, ITestRunTask, ITestTaskState, ResolvedTestRunRequest, TestItemExpandState, TestMessageType, TestResultItem, TestResultState } from 'vs/workbench/contrib/testing/common/testTypes';
export interface ITestRunTaskResults extends ITestRunTask {
/**
* Contains test coverage for the result, if it's available.
*/
readonly coverage: IObservable<undefined | ((tkn: CancellationToken) => Promise<TestCoverage>)>;
/**
* Messages from the task not associated with any specific test.
*/
readonly otherMessages: ITestOutputMessage[];
/**
* Test results output for the task.
*/
readonly output: ITaskRawOutput;
}
export interface ITestResult {
/**
* Count of the number of tests in each run state.
*/
readonly counts: Readonly<TestStateCount>;
/**
* Unique ID of this set of test results.
*/
readonly id: string;
/**
* If the test is completed, the unix milliseconds time at which it was
* completed. If undefined, the test is still running.
*/
readonly completedAt: number | undefined;
/**
* Whether this test result is triggered from an auto run.
*/
readonly request: ResolvedTestRunRequest;
/**
* Human-readable name of the test result.
*/
readonly name: string;
/**
* Gets all tests involved in the run.
*/
tests: IterableIterator<TestResultItem>;
/**
* List of this result's subtasks.
*/
tasks: ReadonlyArray<ITestRunTaskResults>;
/**
* Gets the state of the test by its extension-assigned ID.
*/
getStateById(testExtId: string): TestResultItem | undefined;
/**
* Serializes the test result. Used to save and restore results
* in the workspace.
*/
toJSON(): ISerializedTestResults | undefined;
/**
* Serializes the test result, includes messages. Used to send the test states to the extension host.
*/
toJSONWithMessages(): ISerializedTestResults | undefined;
}
/**
* Output type exposed from live test results.
*/
export interface ITaskRawOutput {
readonly onDidWriteData: Event<VSBuffer>;
readonly endPromise: Promise<void>;
readonly buffers: VSBuffer[];
readonly length: number;
/** Gets a continuous buffer for the desired range */
getRange(start: number, length: number): VSBuffer;
/** Gets an iterator of buffers for the range; may avoid allocation of getRange() */
getRangeIter(start: number, length: number): Iterable<VSBuffer>;
}
const emptyRawOutput: ITaskRawOutput = {
buffers: [],
length: 0,
onDidWriteData: Event.None,
endPromise: Promise.resolve(),
getRange: () => VSBuffer.alloc(0),
getRangeIter: () => [],
};
export class TaskRawOutput implements ITaskRawOutput {
private readonly writeDataEmitter = new Emitter<VSBuffer>();
private readonly endDeferred = new DeferredPromise<void>();
private offset = 0;
/** @inheritdoc */
public readonly onDidWriteData = this.writeDataEmitter.event;
/** @inheritdoc */
public readonly endPromise = this.endDeferred.p;
/** @inheritdoc */
public readonly buffers: VSBuffer[] = [];
/** @inheritdoc */
public get length() {
return this.offset;
}
/** @inheritdoc */
getRange(start: number, length: number): VSBuffer {
const buf = VSBuffer.alloc(length);
let bufLastWrite = 0;
for (const chunk of this.getRangeIter(start, length)) {
buf.buffer.set(chunk.buffer, bufLastWrite);
bufLastWrite += chunk.byteLength;
}
return bufLastWrite < length ? buf.slice(0, bufLastWrite) : buf;
}
/** @inheritdoc */
*getRangeIter(start: number, length: number) {
let soFar = 0;
let internalLastRead = 0;
for (const b of this.buffers) {
if (internalLastRead + b.byteLength <= start) {
internalLastRead += b.byteLength;
continue;
}
const bstart = Math.max(0, start - internalLastRead);
const bend = Math.min(b.byteLength, bstart + length - soFar);
yield b.slice(bstart, bend);
soFar += bend - bstart;
internalLastRead += b.byteLength;
if (soFar === length) {
break;
}
}
}
/**
* Appends data to the output, returning the byte range where the data can be found.
*/
public append(data: VSBuffer, marker?: number) {
const offset = this.offset;
let length = data.byteLength;
if (marker === undefined) {
this.push(data);
return { offset, length };
}
// Bytes that should be 'trimmed' off the end of data. This is done because
// selections in the terminal are based on the entire line, and commonly
// the interesting marked range has a trailing new line. We don't want to
// select the trailing line (which might have other data)
// so we place the marker before all trailing trimbytes.
const enum TrimBytes {
CR = 13,
LF = 10,
}
const start = VSBuffer.fromString(getMarkCode(marker, true));
const end = VSBuffer.fromString(getMarkCode(marker, false));
length += start.byteLength + end.byteLength;
this.push(start);
let trimLen = data.byteLength;
for (; trimLen > 0; trimLen--) {
const last = data.buffer[trimLen - 1];
if (last !== TrimBytes.CR && last !== TrimBytes.LF) {
break;
}
}
this.push(data.slice(0, trimLen));
this.push(end);
this.push(data.slice(trimLen));
return { offset, length };
}
private push(data: VSBuffer) {
if (data.byteLength === 0) {
return;
}
this.buffers.push(data);
this.writeDataEmitter.fire(data);
this.offset += data.byteLength;
}
/** Signals the output has ended. */
public end() {
this.endDeferred.complete();
}
}
export const resultItemParents = function* (results: ITestResult, item: TestResultItem) {
for (const id of TestId.fromString(item.item.extId).idsToRoot()) {
yield results.getStateById(id.toString())!;
}
};
export const maxCountPriority = (counts: Readonly<TestStateCount>) => {
for (const state of statesInOrder) {
if (counts[state] > 0) {
return state;
}
}
return TestResultState.Unset;
};
const getMarkCode = (marker: number, start: boolean) => `\x1b]633;SetMark;Id=${getMarkId(marker, start)};Hidden\x07`;
interface TestResultItemWithChildren extends TestResultItem {
/** Children in the run */
children: TestResultItemWithChildren[];
}
const itemToNode = (controllerId: string, item: ITestItem, parent: string | null): TestResultItemWithChildren => ({
controllerId,
expand: TestItemExpandState.NotExpandable,
item: { ...item },
children: [],
tasks: [],
ownComputedState: TestResultState.Unset,
computedState: TestResultState.Unset,
});
export const enum TestResultItemChangeReason {
ComputedStateChange,
OwnStateChange,
NewMessage,
}
export type TestResultItemChange = { item: TestResultItem; result: ITestResult } & (
| { reason: TestResultItemChangeReason.ComputedStateChange }
| { reason: TestResultItemChangeReason.OwnStateChange; previousState: TestResultState; previousOwnDuration: number | undefined }
| { reason: TestResultItemChangeReason.NewMessage; message: ITestMessage }
);
/**
* Results of a test. These are created when the test initially started running
* and marked as "complete" when the run finishes.
*/
export class LiveTestResult extends Disposable implements ITestResult {
private readonly completeEmitter = this._register(new Emitter<void>());
private readonly newTaskEmitter = this._register(new Emitter<number>());
private readonly endTaskEmitter = this._register(new Emitter<number>());
private readonly changeEmitter = this._register(new Emitter<TestResultItemChange>());
/** todo@connor4312: convert to a WellDefinedPrefixTree */
private readonly testById = new Map<string, TestResultItemWithChildren>();
private testMarkerCounter = 0;
private _completedAt?: number;
public readonly startedAt = Date.now();
public readonly onChange = this.changeEmitter.event;
public readonly onComplete = this.completeEmitter.event;
public readonly onNewTask = this.newTaskEmitter.event;
public readonly onEndTask = this.endTaskEmitter.event;
public readonly tasks: (ITestRunTaskResults & { output: TaskRawOutput })[] = [];
public readonly name = localize('runFinished', 'Test run at {0}', new Date().toLocaleString(language));
/**
* @inheritdoc
*/
public get completedAt() {
return this._completedAt;
}
/**
* @inheritdoc
*/
public readonly counts = makeEmptyCounts();
/**
* @inheritdoc
*/
public get tests() {
return this.testById.values();
}
private readonly computedStateAccessor: IComputedStateAccessor<TestResultItemWithChildren> = {
getOwnState: i => i.ownComputedState,
getCurrentComputedState: i => i.computedState,
setComputedState: (i, s) => i.computedState = s,
getChildren: i => i.children,
getParents: i => {
const { testById: testByExtId } = this;
return (function* () {
const parentId = TestId.fromString(i.item.extId).parentId;
if (parentId) {
for (const id of parentId.idsToRoot()) {
yield testByExtId.get(id.toString())!;
}
}
})();
},
};
constructor(
public readonly id: string,
public readonly persist: boolean,
public readonly request: ResolvedTestRunRequest,
) {
super();
}
/**
* @inheritdoc
*/
public getStateById(extTestId: string) {
return this.testById.get(extTestId);
}
/**
* Appends output that occurred during the test run.
*/
public appendOutput(output: VSBuffer, taskId: string, location?: IRichLocation, testId?: string): void {
const preview = output.byteLength > 100 ? output.slice(0, 100).toString() + '…' : output.toString();
let marker: number | undefined;
// currently, the UI only exposes jump-to-message from tests or locations,
// so no need to mark outputs that don't come from either of those.
if (testId || location) {
marker = this.testMarkerCounter++;
}
const index = this.mustGetTaskIndex(taskId);
const task = this.tasks[index];
const { offset, length } = task.output.append(output, marker);
const message: ITestOutputMessage = {
location,
message: removeAnsiEscapeCodes(preview),
offset,
length,
marker,
type: TestMessageType.Output,
};
const test = testId && this.testById.get(testId);
if (test) {
test.tasks[index].messages.push(message);
this.changeEmitter.fire({ item: test, result: this, reason: TestResultItemChangeReason.NewMessage, message });
} else {
task.otherMessages.push(message);
}
}
/**
* Adds a new run task to the results.
*/
public addTask(task: ITestRunTask) {
this.tasks.push({ ...task, coverage: observableValue(this, undefined), otherMessages: [], output: new TaskRawOutput() });
for (const test of this.tests) {
test.tasks.push({ duration: undefined, messages: [], state: TestResultState.Unset });
}
this.newTaskEmitter.fire(this.tasks.length - 1);
}
/**
* Add the chain of tests to the run. The first test in the chain should
* be either a test root, or a previously-known test.
*/
public addTestChainToRun(controllerId: string, chain: ReadonlyArray<ITestItem>) {
let parent = this.testById.get(chain[0].extId);
if (!parent) { // must be a test root
parent = this.addTestToRun(controllerId, chain[0], null);
}
for (let i = 1; i < chain.length; i++) {
parent = this.addTestToRun(controllerId, chain[i], parent.item.extId);
}
return undefined;
}
/**
* Updates the state of the test by its internal ID.
*/
public updateState(testId: string, taskId: string, state: TestResultState, duration?: number) {
const entry = this.testById.get(testId);
if (!entry) {
return;
}
const index = this.mustGetTaskIndex(taskId);
const oldTerminalStatePrio = terminalStatePriorities[entry.tasks[index].state];
const newTerminalStatePrio = terminalStatePriorities[state];
// Ignore requests to set the state from one terminal state back to a
// "lower" one, e.g. from failed back to passed:
if (oldTerminalStatePrio !== undefined &&
(newTerminalStatePrio === undefined || newTerminalStatePrio < oldTerminalStatePrio)) {
return;
}
this.fireUpdateAndRefresh(entry, index, state, duration);
}
/**
* Appends a message for the test in the run.
*/
public appendMessage(testId: string, taskId: string, message: ITestMessage) {
const entry = this.testById.get(testId);
if (!entry) {
return;
}
entry.tasks[this.mustGetTaskIndex(taskId)].messages.push(message);
this.changeEmitter.fire({ item: entry, result: this, reason: TestResultItemChangeReason.NewMessage, message });
}
/**
* Marks the task in the test run complete.
*/
public markTaskComplete(taskId: string) {
const index = this.mustGetTaskIndex(taskId);
const task = this.tasks[index];
task.running = false;
task.output.end();
this.setAllToState(
TestResultState.Unset,
taskId,
t => t.state === TestResultState.Queued || t.state === TestResultState.Running,
);
this.endTaskEmitter.fire(index);
}
/**
* Notifies the service that all tests are complete.
*/
public markComplete() {
if (this._completedAt !== undefined) {
throw new Error('cannot complete a test result multiple times');
}
for (const task of this.tasks) {
if (task.running) {
this.markTaskComplete(task.id);
}
}
this._completedAt = Date.now();
this.completeEmitter.fire();
}
/**
* Marks the test and all of its children in the run as retired.
*/
public markRetired(testIds: WellDefinedPrefixTree<undefined> | undefined) {
for (const [id, test] of this.testById) {
if (!test.retired && (!testIds || testIds.hasKeyOrParent(TestId.fromString(id).path))) {
test.retired = true;
this.changeEmitter.fire({ reason: TestResultItemChangeReason.ComputedStateChange, item: test, result: this });
}
}
}
/**
* @inheritdoc
*/
public toJSON(): ISerializedTestResults | undefined {
return this.completedAt && this.persist ? this.doSerialize.value : undefined;
}
public toJSONWithMessages(): ISerializedTestResults | undefined {
return this.completedAt && this.persist ? this.doSerializeWithMessages.value : undefined;
}
/**
* Updates all tests in the collection to the given state.
*/
protected setAllToState(state: TestResultState, taskId: string, when: (task: ITestTaskState, item: TestResultItem) => boolean) {
const index = this.mustGetTaskIndex(taskId);
for (const test of this.testById.values()) {
if (when(test.tasks[index], test)) {
this.fireUpdateAndRefresh(test, index, state);
}
}
}
private fireUpdateAndRefresh(entry: TestResultItem, taskIndex: number, newState: TestResultState, newOwnDuration?: number) {
const previousOwnComputed = entry.ownComputedState;
const previousOwnDuration = entry.ownDuration;
const changeEvent: TestResultItemChange = {
item: entry,
result: this,
reason: TestResultItemChangeReason.OwnStateChange,
previousState: previousOwnComputed,
previousOwnDuration: previousOwnDuration,
};
entry.tasks[taskIndex].state = newState;
if (newOwnDuration !== undefined) {
entry.tasks[taskIndex].duration = newOwnDuration;
entry.ownDuration = Math.max(entry.ownDuration || 0, newOwnDuration);
}
const newOwnComputed = maxPriority(...entry.tasks.map(t => t.state));
if (newOwnComputed === previousOwnComputed) {
if (newOwnDuration !== previousOwnDuration) {
this.changeEmitter.fire(changeEvent); // fire manually since state change won't do it
}
return;
}
entry.ownComputedState = newOwnComputed;
this.counts[previousOwnComputed]--;
this.counts[newOwnComputed]++;
refreshComputedState(this.computedStateAccessor, entry).forEach(t =>
this.changeEmitter.fire(t === entry ? changeEvent : {
item: t,
result: this,
reason: TestResultItemChangeReason.ComputedStateChange,
}),
);
}
private addTestToRun(controllerId: string, item: ITestItem, parent: string | null) {
const node = itemToNode(controllerId, item, parent);
this.testById.set(item.extId, node);
this.counts[TestResultState.Unset]++;
if (parent) {
this.testById.get(parent)?.children.push(node);
}
if (this.tasks.length) {
for (let i = 0; i < this.tasks.length; i++) {
node.tasks.push({ duration: undefined, messages: [], state: TestResultState.Unset });
}
}
return node;
}
private mustGetTaskIndex(taskId: string) {
const index = this.tasks.findIndex(t => t.id === taskId);
if (index === -1) {
throw new Error(`Unknown task ${taskId} in updateState`);
}
return index;
}
private readonly doSerialize = new Lazy((): ISerializedTestResults => ({
id: this.id,
completedAt: this.completedAt!,
tasks: this.tasks.map(t => ({ id: t.id, name: t.name })),
name: this.name,
request: this.request,
items: [...this.testById.values()].map(TestResultItem.serializeWithoutMessages),
}));
private readonly doSerializeWithMessages = new Lazy((): ISerializedTestResults => ({
id: this.id,
completedAt: this.completedAt!,
tasks: this.tasks.map(t => ({ id: t.id, name: t.name })),
name: this.name,
request: this.request,
items: [...this.testById.values()].map(TestResultItem.serialize),
}));
}
/**
* Test results hydrated from a previously-serialized test run.
*/
export class HydratedTestResult implements ITestResult {
/**
* @inheritdoc
*/
public readonly counts = makeEmptyCounts();
/**
* @inheritdoc
*/
public readonly id: string;
/**
* @inheritdoc
*/
public readonly completedAt: number;
/**
* @inheritdoc
*/
public readonly tasks: ITestRunTaskResults[];
/**
* @inheritdoc
*/
public get tests() {
return this.testById.values();
}
/**
* @inheritdoc
*/
public readonly name: string;
/**
* @inheritdoc
*/
public readonly request: ResolvedTestRunRequest;
private readonly testById = new Map<string, TestResultItem>();
constructor(
identity: IUriIdentityService,
private readonly serialized: ISerializedTestResults,
private readonly persist = true,
) {
this.id = serialized.id;
this.completedAt = serialized.completedAt;
this.tasks = serialized.tasks.map((task, i) => ({
id: task.id,
name: task.name,
running: false,
coverage: observableValue(this, undefined),
output: emptyRawOutput,
otherMessages: []
}));
this.name = serialized.name;
this.request = serialized.request;
for (const item of serialized.items) {
const de = TestResultItem.deserialize(identity, item);
this.counts[de.ownComputedState]++;
this.testById.set(item.item.extId, de);
}
}
/**
* @inheritdoc
*/
public getStateById(extTestId: string) {
return this.testById.get(extTestId);
}
/**
* @inheritdoc
*/
public toJSON(): ISerializedTestResults | undefined {
return this.persist ? this.serialized : undefined;
}
/**
* @inheritdoc
*/
public toJSONWithMessages(): ISerializedTestResults | undefined {
return this.toJSON();
}
}
| src/vs/workbench/contrib/testing/common/testResult.ts | 0 | https://github.com/microsoft/vscode/commit/48a9149e6ad2cbc0f7ebfdb2ce6143627c077d1e | [
0.00017705887148622423,
0.0001716569095151499,
0.00016288310871459544,
0.00017270696116611362,
0.0000033843696201074636
] |
{
"id": 0,
"code_window": [
"\t\tconst request: IInlineChatRequest = {\n",
"\t\t\trequestId: generateUuid(),\n",
"\t\t\tprompt: this._activeSession.lastInput.value,\n",
"\t\t\tattempt: this._activeSession.lastInput.attempt,\n",
"\t\t\tselection: this._editor.getSelection(),\n",
"\t\t\twholeRange: this._activeSession.wholeRange.value,\n",
"\t\t\tlive: this._activeSession.editMode !== EditMode.Preview // TODO@jrieken let extension know what document is used for previewing\n",
"\t\t};\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\twholeRange: this._activeSession.wholeRange.trackedInitialRange,\n"
],
"file_path": "src/vs/workbench/contrib/inlineChat/browser/inlineChatController.ts",
"type": "replace",
"edit_start_line_idx": 604
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
use crate::{constants::APPLICATION_NAME, util::errors::CodeError};
use async_trait::async_trait;
use std::path::{Path, PathBuf};
use std::pin::Pin;
use std::task::{Context, Poll};
use tokio::io::{AsyncRead, AsyncWrite};
use tokio::net::TcpListener;
use uuid::Uuid;
// todo: we could probably abstract this into some crate, if one doesn't already exist
cfg_if::cfg_if! {
if #[cfg(unix)] {
pub type AsyncPipe = tokio::net::UnixStream;
pub type AsyncPipeWriteHalf = tokio::net::unix::OwnedWriteHalf;
pub type AsyncPipeReadHalf = tokio::net::unix::OwnedReadHalf;
pub async fn get_socket_rw_stream(path: &Path) -> Result<AsyncPipe, CodeError> {
tokio::net::UnixStream::connect(path)
.await
.map_err(CodeError::AsyncPipeFailed)
}
pub async fn listen_socket_rw_stream(path: &Path) -> Result<AsyncPipeListener, CodeError> {
tokio::net::UnixListener::bind(path)
.map(AsyncPipeListener)
.map_err(CodeError::AsyncPipeListenerFailed)
}
pub struct AsyncPipeListener(tokio::net::UnixListener);
impl AsyncPipeListener {
pub async fn accept(&mut self) -> Result<AsyncPipe, CodeError> {
self.0.accept().await.map_err(CodeError::AsyncPipeListenerFailed).map(|(s, _)| s)
}
}
pub fn socket_stream_split(pipe: AsyncPipe) -> (AsyncPipeReadHalf, AsyncPipeWriteHalf) {
pipe.into_split()
}
} else {
use tokio::{time::sleep, io::ReadBuf};
use tokio::net::windows::named_pipe::{ClientOptions, ServerOptions, NamedPipeClient, NamedPipeServer};
use std::{time::Duration, io};
use pin_project::pin_project;
#[pin_project(project = AsyncPipeProj)]
pub enum AsyncPipe {
PipeClient(#[pin] NamedPipeClient),
PipeServer(#[pin] NamedPipeServer),
}
impl AsyncRead for AsyncPipe {
fn poll_read(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut ReadBuf<'_>,
) -> Poll<io::Result<()>> {
match self.project() {
AsyncPipeProj::PipeClient(c) => c.poll_read(cx, buf),
AsyncPipeProj::PipeServer(c) => c.poll_read(cx, buf),
}
}
}
impl AsyncWrite for AsyncPipe {
fn poll_write(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<io::Result<usize>> {
match self.project() {
AsyncPipeProj::PipeClient(c) => c.poll_write(cx, buf),
AsyncPipeProj::PipeServer(c) => c.poll_write(cx, buf),
}
}
fn poll_write_vectored(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
bufs: &[io::IoSlice<'_>],
) -> Poll<Result<usize, io::Error>> {
match self.project() {
AsyncPipeProj::PipeClient(c) => c.poll_write_vectored(cx, bufs),
AsyncPipeProj::PipeServer(c) => c.poll_write_vectored(cx, bufs),
}
}
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
match self.project() {
AsyncPipeProj::PipeClient(c) => c.poll_flush(cx),
AsyncPipeProj::PipeServer(c) => c.poll_flush(cx),
}
}
fn is_write_vectored(&self) -> bool {
match self {
AsyncPipe::PipeClient(c) => c.is_write_vectored(),
AsyncPipe::PipeServer(c) => c.is_write_vectored(),
}
}
fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), io::Error>> {
match self.project() {
AsyncPipeProj::PipeClient(c) => c.poll_shutdown(cx),
AsyncPipeProj::PipeServer(c) => c.poll_shutdown(cx),
}
}
}
pub type AsyncPipeWriteHalf = tokio::io::WriteHalf<AsyncPipe>;
pub type AsyncPipeReadHalf = tokio::io::ReadHalf<AsyncPipe>;
pub async fn get_socket_rw_stream(path: &Path) -> Result<AsyncPipe, CodeError> {
// Tokio says we can need to try in a loop. Do so.
// https://docs.rs/tokio/latest/tokio/net/windows/named_pipe/struct.NamedPipeClient.html
let client = loop {
match ClientOptions::new().open(path) {
Ok(client) => break client,
// ERROR_PIPE_BUSY https://docs.microsoft.com/en-us/windows/win32/debug/system-error-codes--0-499-
Err(e) if e.raw_os_error() == Some(231) => sleep(Duration::from_millis(100)).await,
Err(e) => return Err(CodeError::AsyncPipeFailed(e)),
}
};
Ok(AsyncPipe::PipeClient(client))
}
pub struct AsyncPipeListener {
path: PathBuf,
server: NamedPipeServer
}
impl AsyncPipeListener {
pub async fn accept(&mut self) -> Result<AsyncPipe, CodeError> {
// see https://docs.rs/tokio/latest/tokio/net/windows/named_pipe/struct.NamedPipeServer.html
// this is a bit weird in that the server becomes the client once
// they get a connection, and we create a new client.
self.server
.connect()
.await
.map_err(CodeError::AsyncPipeListenerFailed)?;
// Construct the next server to be connected before sending the one
// we already have of onto a task. This ensures that the server
// isn't closed (after it's done in the task) before a new one is
// available. Otherwise the client might error with
// `io::ErrorKind::NotFound`.
let next_server = ServerOptions::new()
.create(&self.path)
.map_err(CodeError::AsyncPipeListenerFailed)?;
Ok(AsyncPipe::PipeServer(std::mem::replace(&mut self.server, next_server)))
}
}
pub async fn listen_socket_rw_stream(path: &Path) -> Result<AsyncPipeListener, CodeError> {
let server = ServerOptions::new()
.first_pipe_instance(true)
.create(path)
.map_err(CodeError::AsyncPipeListenerFailed)?;
Ok(AsyncPipeListener { path: path.to_owned(), server })
}
pub fn socket_stream_split(pipe: AsyncPipe) -> (AsyncPipeReadHalf, AsyncPipeWriteHalf) {
tokio::io::split(pipe)
}
}
}
impl AsyncPipeListener {
pub fn into_pollable(self) -> PollableAsyncListener {
PollableAsyncListener {
listener: Some(self),
write_fut: tokio_util::sync::ReusableBoxFuture::new(make_accept_fut(None)),
}
}
}
pub struct PollableAsyncListener {
listener: Option<AsyncPipeListener>,
write_fut: tokio_util::sync::ReusableBoxFuture<
'static,
(AsyncPipeListener, Result<AsyncPipe, CodeError>),
>,
}
async fn make_accept_fut(
data: Option<AsyncPipeListener>,
) -> (AsyncPipeListener, Result<AsyncPipe, CodeError>) {
match data {
Some(mut l) => {
let c = l.accept().await;
(l, c)
}
None => unreachable!("this future should not be pollable in this state"),
}
}
impl hyper::server::accept::Accept for PollableAsyncListener {
type Conn = AsyncPipe;
type Error = CodeError;
fn poll_accept(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<Result<Self::Conn, Self::Error>>> {
if let Some(l) = self.listener.take() {
self.write_fut.set(make_accept_fut(Some(l)))
}
match self.write_fut.poll(cx) {
Poll::Ready((l, cnx)) => {
self.listener = Some(l);
Poll::Ready(Some(cnx))
}
Poll::Pending => Poll::Pending,
}
}
}
/// Gets a random name for a pipe/socket on the paltform
pub fn get_socket_name() -> PathBuf {
cfg_if::cfg_if! {
if #[cfg(unix)] {
std::env::temp_dir().join(format!("{}-{}", APPLICATION_NAME, Uuid::new_v4()))
} else {
PathBuf::from(format!(r"\\.\pipe\{}-{}", APPLICATION_NAME, Uuid::new_v4()))
}
}
}
pub type AcceptedRW = (
Box<dyn AsyncRead + Send + Unpin>,
Box<dyn AsyncWrite + Send + Unpin>,
);
#[async_trait]
pub trait AsyncRWAccepter {
async fn accept_rw(&mut self) -> Result<AcceptedRW, CodeError>;
}
#[async_trait]
impl AsyncRWAccepter for AsyncPipeListener {
async fn accept_rw(&mut self) -> Result<AcceptedRW, CodeError> {
let pipe = self.accept().await?;
let (read, write) = socket_stream_split(pipe);
Ok((Box::new(read), Box::new(write)))
}
}
#[async_trait]
impl AsyncRWAccepter for TcpListener {
async fn accept_rw(&mut self) -> Result<AcceptedRW, CodeError> {
let (stream, _) = self
.accept()
.await
.map_err(CodeError::AsyncPipeListenerFailed)?;
let (read, write) = tokio::io::split(stream);
Ok((Box::new(read), Box::new(write)))
}
}
| cli/src/async_pipe.rs | 0 | https://github.com/microsoft/vscode/commit/48a9149e6ad2cbc0f7ebfdb2ce6143627c077d1e | [
0.00017781836504582316,
0.00017297235899604857,
0.00016360239533241838,
0.00017346127424389124,
0.0000027434027742856415
] |
{
"id": 1,
"code_window": [
"\t\tthis._decorationIds = [first].concat(newIds);\n",
"\t\tthis._onDidChange.fire(this);\n",
"\t}\n",
"\n",
"\tget value(): Range {\n",
"\t\tlet result: Range | undefined;\n",
"\t\tfor (const id of this._decorationIds) {\n",
"\t\t\tconst range = this._textModel.getDecorationRange(id);\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tget trackedInitialRange(): Range {\n",
"\t\tconst [first] = this._decorationIds;\n",
"\t\treturn this._textModel.getDecorationRange(first) ?? new Range(1, 1, 1, 1);\n",
"\t}\n",
"\n"
],
"file_path": "src/vs/workbench/contrib/inlineChat/browser/inlineChatSession.ts",
"type": "add",
"edit_start_line_idx": 116
} | /*---------------------------------------------------------------------------------------------
* 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 { equals } from 'vs/base/common/arrays';
import { Emitter, Event } from 'vs/base/common/event';
import { DisposableStore } from 'vs/base/common/lifecycle';
import { mock } from 'vs/base/test/common/mock';
import { ensureNoDisposablesAreLeakedInTestSuite } from 'vs/base/test/common/utils';
import { TestDiffProviderFactoryService } from 'vs/editor/browser/diff/testDiffProviderFactoryService';
import { IActiveCodeEditor } from 'vs/editor/browser/editorBrowser';
import { IDiffProviderFactoryService } from 'vs/editor/browser/widget/diffEditor/diffProviderFactoryService';
import { Range } from 'vs/editor/common/core/range';
import { ITextModel } from 'vs/editor/common/model';
import { IModelService } from 'vs/editor/common/services/model';
import { instantiateTestCodeEditor } from 'vs/editor/test/browser/testCodeEditor';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { TestConfigurationService } from 'vs/platform/configuration/test/common/testConfigurationService';
import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { SyncDescriptor } from 'vs/platform/instantiation/common/descriptors';
import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection';
import { TestInstantiationService } from 'vs/platform/instantiation/test/common/instantiationServiceMock';
import { MockContextKeyService } from 'vs/platform/keybinding/test/common/mockKeybindingService';
import { IEditorProgressService, IProgressRunner } from 'vs/platform/progress/common/progress';
import { IViewDescriptorService } from 'vs/workbench/common/views';
import { AccessibilityVerbositySettingId } from 'vs/workbench/contrib/accessibility/browser/accessibilityConfiguration';
import { IAccessibleViewService } from 'vs/workbench/contrib/accessibility/browser/accessibleView';
import { IChatAccessibilityService } from 'vs/workbench/contrib/chat/browser/chat';
import { IChatResponseViewModel } from 'vs/workbench/contrib/chat/common/chatViewModel';
import { InlineChatController, InlineChatRunOptions, State } from 'vs/workbench/contrib/inlineChat/browser/inlineChatController';
import { IInlineChatSessionService, InlineChatSessionService } from 'vs/workbench/contrib/inlineChat/browser/inlineChatSession';
import { IInlineChatService, InlineChatConfigKeys, InlineChatResponseType } from 'vs/workbench/contrib/inlineChat/common/inlineChat';
import { InlineChatServiceImpl } from 'vs/workbench/contrib/inlineChat/common/inlineChatServiceImpl';
import { workbenchInstantiationService } from 'vs/workbench/test/browser/workbenchTestServices';
suite('InteractiveChatController', function () {
class TestController extends InlineChatController {
static INIT_SEQUENCE: readonly State[] = [State.CREATE_SESSION, State.INIT_UI, State.WAIT_FOR_INPUT];
static INIT_SEQUENCE_AUTO_SEND: readonly State[] = [...this.INIT_SEQUENCE, State.MAKE_REQUEST, State.APPLY_RESPONSE, State.SHOW_RESPONSE, State.WAIT_FOR_INPUT];
private readonly _onDidChangeState = new Emitter<State>();
readonly onDidChangeState: Event<State> = this._onDidChangeState.event;
readonly states: readonly State[] = [];
waitFor(states: readonly State[]): Promise<void> {
const actual: State[] = [];
return new Promise<void>((resolve, reject) => {
const d = this.onDidChangeState(state => {
actual.push(state);
if (equals(states, actual)) {
d.dispose();
resolve();
}
});
setTimeout(() => {
d.dispose();
reject(`timeout, \nWANTED ${states.join('>')}, \nGOT ${actual.join('>')}`);
}, 1000);
});
}
protected override async _nextState(state: State, options: InlineChatRunOptions): Promise<void> {
let nextState: State | void = state;
while (nextState) {
this._onDidChangeState.fire(nextState);
(<State[]>this.states).push(nextState);
nextState = await this[nextState](options);
}
}
override dispose() {
super.dispose();
this._onDidChangeState.dispose();
}
}
const store = new DisposableStore();
let configurationService: TestConfigurationService;
let editor: IActiveCodeEditor;
let model: ITextModel;
let ctrl: TestController;
// let contextKeys: MockContextKeyService;
let inlineChatService: InlineChatServiceImpl;
let inlineChatSessionService: IInlineChatSessionService;
let instaService: TestInstantiationService;
setup(function () {
const contextKeyService = new MockContextKeyService();
inlineChatService = new InlineChatServiceImpl(contextKeyService);
configurationService = new TestConfigurationService();
configurationService.setUserConfiguration('chat', { editor: { fontSize: 14, fontFamily: 'default' } });
configurationService.setUserConfiguration('editor', {});
const serviceCollection = new ServiceCollection(
[IContextKeyService, contextKeyService],
[IInlineChatService, inlineChatService],
[IDiffProviderFactoryService, new SyncDescriptor(TestDiffProviderFactoryService)],
[IInlineChatSessionService, new SyncDescriptor(InlineChatSessionService)],
[IEditorProgressService, new class extends mock<IEditorProgressService>() {
override show(total: unknown, delay?: unknown): IProgressRunner {
return {
total() { },
worked(value) { },
done() { },
};
}
}],
[IChatAccessibilityService, new class extends mock<IChatAccessibilityService>() {
override acceptResponse(response: IChatResponseViewModel | undefined, requestId: number): void { }
override acceptRequest(): number { return -1; }
}],
[IAccessibleViewService, new class extends mock<IAccessibleViewService>() {
override getOpenAriaHint(verbositySettingKey: AccessibilityVerbositySettingId): string | null {
return null;
}
}],
[IConfigurationService, configurationService],
[IViewDescriptorService, new class extends mock<IViewDescriptorService>() {
override onDidChangeLocation = Event.None;
}]
);
instaService = store.add(workbenchInstantiationService(undefined, store).createChild(serviceCollection));
inlineChatSessionService = store.add(instaService.get(IInlineChatSessionService));
model = store.add(instaService.get(IModelService).createModel('Hello\nWorld\nHello Again\nHello World\n', null));
editor = store.add(instantiateTestCodeEditor(instaService, model));
store.add(inlineChatService.addProvider({
debugName: 'Unit Test',
label: 'Unit Test',
prepareInlineChatSession() {
return {
id: Math.random()
};
},
provideResponse(session, request) {
return {
type: InlineChatResponseType.EditorEdit,
id: Math.random(),
edits: [{
range: new Range(1, 1, 1, 1),
text: request.prompt
}]
};
}
}));
});
teardown(function () {
store.clear();
ctrl?.dispose();
});
ensureNoDisposablesAreLeakedInTestSuite();
test('creation, not showing anything', function () {
ctrl = instaService.createInstance(TestController, editor);
assert.ok(ctrl);
assert.strictEqual(ctrl.getWidgetPosition(), undefined);
});
test('run (show/hide)', async function () {
ctrl = instaService.createInstance(TestController, editor);
const p = ctrl.waitFor(TestController.INIT_SEQUENCE_AUTO_SEND);
const run = ctrl.run({ message: 'Hello', autoSend: true });
await p;
assert.ok(ctrl.getWidgetPosition() !== undefined);
await ctrl.cancelSession();
await run;
assert.ok(ctrl.getWidgetPosition() === undefined);
});
test('wholeRange expands to whole lines, editor selection default', async function () {
editor.setSelection(new Range(1, 1, 1, 3));
ctrl = instaService.createInstance(TestController, editor);
const d = inlineChatService.addProvider({
debugName: 'Unit Test',
label: 'Unit Test',
prepareInlineChatSession() {
return {
id: Math.random()
};
},
provideResponse(session, request) {
throw new Error();
}
});
ctrl.run({});
await Event.toPromise(Event.filter(ctrl.onDidChangeState, e => e === State.WAIT_FOR_INPUT));
const session = inlineChatSessionService.getSession(editor, editor.getModel()!.uri);
assert.ok(session);
assert.deepStrictEqual(session.wholeRange.value, new Range(1, 1, 1, 6));
await ctrl.cancelSession();
d.dispose();
});
test('wholeRange expands to whole lines, session provided', async function () {
editor.setSelection(new Range(1, 1, 1, 1));
ctrl = instaService.createInstance(TestController, editor);
const d = inlineChatService.addProvider({
debugName: 'Unit Test',
label: 'Unit Test',
prepareInlineChatSession() {
return {
id: Math.random(),
wholeRange: new Range(1, 1, 1, 3)
};
},
provideResponse(session, request) {
throw new Error();
}
});
ctrl.run({});
await Event.toPromise(Event.filter(ctrl.onDidChangeState, e => e === State.WAIT_FOR_INPUT));
const session = inlineChatSessionService.getSession(editor, editor.getModel()!.uri);
assert.ok(session);
assert.deepStrictEqual(session.wholeRange.value, new Range(1, 1, 1, 6));
await ctrl.cancelSession();
d.dispose();
});
test('typing outside of wholeRange finishes session', async function () {
configurationService.setUserConfiguration(InlineChatConfigKeys.FinishOnType, true);
ctrl = instaService.createInstance(TestController, editor);
const p = ctrl.waitFor(TestController.INIT_SEQUENCE_AUTO_SEND);
const r = ctrl.run({ message: 'Hello', autoSend: true });
await p;
const session = inlineChatSessionService.getSession(editor, editor.getModel()!.uri);
assert.ok(session);
assert.deepStrictEqual(session.wholeRange.value, new Range(1, 1, 1, 11));
editor.setSelection(new Range(2, 1, 2, 1));
editor.trigger('test', 'type', { text: 'a' });
await ctrl.waitFor([State.ACCEPT]);
await r;
});
test('\'whole range\' isn\'t updated for edits outside whole range #4346', async function () {
editor.setSelection(new Range(3, 1, 3, 1));
const d = inlineChatService.addProvider({
debugName: 'Unit Test',
label: 'Unit Test',
prepareInlineChatSession() {
return {
id: Math.random(),
wholeRange: new Range(3, 1, 3, 3)
};
},
provideResponse(session, request) {
return {
type: InlineChatResponseType.EditorEdit,
id: Math.random(),
edits: [{
range: new Range(1, 1, 1, 1), // EDIT happens outside of whole range
text: `${request.prompt}\n${request.prompt}`
}]
};
}
});
store.add(d);
ctrl = instaService.createInstance(TestController, editor);
const p = ctrl.waitFor(TestController.INIT_SEQUENCE);
const r = ctrl.run({ message: 'Hello', autoSend: false });
await p;
const session = inlineChatSessionService.getSession(editor, editor.getModel()!.uri);
assert.ok(session);
assert.deepStrictEqual(session.wholeRange.value, new Range(3, 1, 3, 12));
ctrl.acceptInput();
await ctrl.waitFor([State.MAKE_REQUEST, State.APPLY_RESPONSE, State.SHOW_RESPONSE, State.WAIT_FOR_INPUT]);
assert.deepStrictEqual(session.wholeRange.value, new Range(4, 1, 4, 12));
await ctrl.cancelSession();
await r;
});
test('Stuck inline chat widget #211', async function () {
const d = inlineChatService.addProvider({
debugName: 'Unit Test',
label: 'Unit Test',
prepareInlineChatSession() {
return {
id: Math.random(),
wholeRange: new Range(3, 1, 3, 3)
};
},
provideResponse(session, request) {
return new Promise<never>(() => { });
}
});
store.add(d);
ctrl = instaService.createInstance(TestController, editor);
const p = ctrl.waitFor([...TestController.INIT_SEQUENCE, State.MAKE_REQUEST]);
const r = ctrl.run({ message: 'Hello', autoSend: true });
await p;
ctrl.acceptSession();
await r;
assert.strictEqual(ctrl.getWidgetPosition(), undefined);
});
test('[Bug] Inline Chat\'s streaming pushed broken iterations to the undo stack #2403', async function () {
const d = inlineChatService.addProvider({
debugName: 'Unit Test',
label: 'Unit Test',
prepareInlineChatSession() {
return {
id: Math.random(),
wholeRange: new Range(3, 1, 3, 3)
};
},
async provideResponse(session, request, progress) {
progress.report({ edits: [{ range: new Range(1, 1, 1, 1), text: 'hEllo1\n' }] });
progress.report({ edits: [{ range: new Range(2, 1, 2, 1), text: 'hEllo2\n' }] });
return {
id: Math.random(),
type: InlineChatResponseType.EditorEdit,
edits: [{ range: new Range(1, 1, 1000, 1), text: 'Hello1\nHello2\n' }]
};
}
});
const valueThen = editor.getModel().getValue();
store.add(d);
ctrl = instaService.createInstance(TestController, editor);
const p = ctrl.waitFor([...TestController.INIT_SEQUENCE, State.MAKE_REQUEST, State.APPLY_RESPONSE, State.SHOW_RESPONSE, State.WAIT_FOR_INPUT]);
const r = ctrl.run({ message: 'Hello', autoSend: true });
await p;
ctrl.acceptSession();
await r;
assert.strictEqual(editor.getModel().getValue(), 'Hello1\nHello2\n');
editor.getModel().undo();
assert.strictEqual(editor.getModel().getValue(), valueThen);
});
});
| src/vs/workbench/contrib/inlineChat/test/browser/inlineChatController.test.ts | 1 | https://github.com/microsoft/vscode/commit/48a9149e6ad2cbc0f7ebfdb2ce6143627c077d1e | [
0.8029986619949341,
0.030171221122145653,
0.00016467369277961552,
0.00017174816457554698,
0.1321440488100052
] |
{
"id": 1,
"code_window": [
"\t\tthis._decorationIds = [first].concat(newIds);\n",
"\t\tthis._onDidChange.fire(this);\n",
"\t}\n",
"\n",
"\tget value(): Range {\n",
"\t\tlet result: Range | undefined;\n",
"\t\tfor (const id of this._decorationIds) {\n",
"\t\t\tconst range = this._textModel.getDecorationRange(id);\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tget trackedInitialRange(): Range {\n",
"\t\tconst [first] = this._decorationIds;\n",
"\t\treturn this._textModel.getDecorationRange(first) ?? new Range(1, 1, 1, 1);\n",
"\t}\n",
"\n"
],
"file_path": "src/vs/workbench/contrib/inlineChat/browser/inlineChatSession.ts",
"type": "add",
"edit_start_line_idx": 116
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Emitter, Event } from 'vs/base/common/event';
import { Disposable, dispose, IDisposable, IReference } from 'vs/base/common/lifecycle';
import { Mimes } from 'vs/base/common/mime';
import { ICodeEditor } from 'vs/editor/browser/editorBrowser';
import { ICodeEditorService } from 'vs/editor/browser/services/codeEditorService';
import { IPosition } from 'vs/editor/common/core/position';
import { Range } from 'vs/editor/common/core/range';
import { Selection } from 'vs/editor/common/core/selection';
import * as editorCommon from 'vs/editor/common/editorCommon';
import * as model from 'vs/editor/common/model';
import { SearchParams } from 'vs/editor/common/model/textModelSearch';
import { IResolvedTextEditorModel, ITextModelService } from 'vs/editor/common/services/resolverService';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IUndoRedoService } from 'vs/platform/undoRedo/common/undoRedo';
import { IWordWrapTransientState, readTransientState, writeTransientState } from 'vs/workbench/contrib/codeEditor/browser/toggleWordWrap';
import { CellEditState, CellFocusMode, CursorAtBoundary, CursorAtLineBoundary, IEditableCellViewModel, INotebookCellDecorationOptions } from 'vs/workbench/contrib/notebook/browser/notebookBrowser';
import { CellViewModelStateChangeEvent } from 'vs/workbench/contrib/notebook/browser/notebookViewEvents';
import { ViewContext } from 'vs/workbench/contrib/notebook/browser/viewModel/viewContext';
import { NotebookCellTextModel } from 'vs/workbench/contrib/notebook/common/model/notebookCellTextModel';
import { CellKind, INotebookCellStatusBarItem, INotebookSearchOptions } from 'vs/workbench/contrib/notebook/common/notebookCommon';
import { getEditorTopPadding, NotebookOptionsChangeEvent } from 'vs/workbench/contrib/notebook/browser/notebookOptions';
export abstract class BaseCellViewModel extends Disposable {
protected readonly _onDidChangeEditorAttachState = this._register(new Emitter<void>());
// Do not merge this event with `onDidChangeState` as we are using `Event.once(onDidChangeEditorAttachState)` elsewhere.
readonly onDidChangeEditorAttachState = this._onDidChangeEditorAttachState.event;
protected readonly _onDidChangeState = this._register(new Emitter<CellViewModelStateChangeEvent>());
public readonly onDidChangeState: Event<CellViewModelStateChangeEvent> = this._onDidChangeState.event;
get handle() {
return this.model.handle;
}
get uri() {
return this.model.uri;
}
get lineCount() {
return this.model.textBuffer.getLineCount();
}
get metadata() {
return this.model.metadata;
}
get internalMetadata() {
return this.model.internalMetadata;
}
get language() {
return this.model.language;
}
get mime(): string {
if (typeof this.model.mime === 'string') {
return this.model.mime;
}
switch (this.language) {
case 'markdown':
return Mimes.markdown;
default:
return Mimes.text;
}
}
abstract cellKind: CellKind;
private _editState: CellEditState = CellEditState.Preview;
private _lineNumbers: 'on' | 'off' | 'inherit' = 'inherit';
get lineNumbers(): 'on' | 'off' | 'inherit' {
return this._lineNumbers;
}
set lineNumbers(lineNumbers: 'on' | 'off' | 'inherit') {
if (lineNumbers === this._lineNumbers) {
return;
}
this._lineNumbers = lineNumbers;
this._onDidChangeState.fire({ cellLineNumberChanged: true });
}
private _focusMode: CellFocusMode = CellFocusMode.Container;
get focusMode() {
return this._focusMode;
}
set focusMode(newMode: CellFocusMode) {
if (this._focusMode !== newMode) {
this._focusMode = newMode;
this._onDidChangeState.fire({ focusModeChanged: true });
}
}
protected _textEditor?: ICodeEditor;
get editorAttached(): boolean {
return !!this._textEditor;
}
private _editorListeners: IDisposable[] = [];
private _editorViewStates: editorCommon.ICodeEditorViewState | null = null;
private _editorTransientState: IWordWrapTransientState | null = null;
private _resolvedCellDecorations = new Map<string, INotebookCellDecorationOptions>();
private readonly _cellDecorationsChanged = this._register(new Emitter<{ added: INotebookCellDecorationOptions[]; removed: INotebookCellDecorationOptions[] }>());
onCellDecorationsChanged: Event<{ added: INotebookCellDecorationOptions[]; removed: INotebookCellDecorationOptions[] }> = this._cellDecorationsChanged.event;
private _resolvedDecorations = new Map<string, {
id?: string;
options: model.IModelDeltaDecoration;
}>();
private _lastDecorationId: number = 0;
private _cellStatusBarItems = new Map<string, INotebookCellStatusBarItem>();
private readonly _onDidChangeCellStatusBarItems = this._register(new Emitter<void>());
readonly onDidChangeCellStatusBarItems: Event<void> = this._onDidChangeCellStatusBarItems.event;
private _lastStatusBarId: number = 0;
get textModel(): model.ITextModel | undefined {
return this.model.textModel;
}
hasModel(): this is IEditableCellViewModel {
return !!this.textModel;
}
private _dragging: boolean = false;
get dragging(): boolean {
return this._dragging;
}
set dragging(v: boolean) {
this._dragging = v;
this._onDidChangeState.fire({ dragStateChanged: true });
}
protected _textModelRef: IReference<IResolvedTextEditorModel> | undefined;
private _inputCollapsed: boolean = false;
get isInputCollapsed(): boolean {
return this._inputCollapsed;
}
set isInputCollapsed(v: boolean) {
this._inputCollapsed = v;
this._onDidChangeState.fire({ inputCollapsedChanged: true });
}
private _outputCollapsed: boolean = false;
get isOutputCollapsed(): boolean {
return this._outputCollapsed;
}
set isOutputCollapsed(v: boolean) {
this._outputCollapsed = v;
this._onDidChangeState.fire({ outputCollapsedChanged: true });
}
private _isDisposed = false;
constructor(
readonly viewType: string,
readonly model: NotebookCellTextModel,
public id: string,
private readonly _viewContext: ViewContext,
private readonly _configurationService: IConfigurationService,
private readonly _modelService: ITextModelService,
private readonly _undoRedoService: IUndoRedoService,
private readonly _codeEditorService: ICodeEditorService,
// private readonly _keymapService: INotebookKeymapService
) {
super();
this._register(model.onDidChangeMetadata(() => {
this._onDidChangeState.fire({ metadataChanged: true });
}));
this._register(model.onDidChangeInternalMetadata(e => {
this._onDidChangeState.fire({ internalMetadataChanged: true });
if (e.lastRunSuccessChanged) {
// Statusbar visibility may change
this.layoutChange({});
}
}));
this._register(this._configurationService.onDidChangeConfiguration(e => {
if (e.affectsConfiguration('notebook.lineNumbers')) {
this.lineNumbers = 'inherit';
}
}));
if (this.model.collapseState?.inputCollapsed) {
this._inputCollapsed = true;
}
if (this.model.collapseState?.outputCollapsed) {
this._outputCollapsed = true;
}
}
abstract updateOptions(e: NotebookOptionsChangeEvent): void;
abstract getHeight(lineHeight: number): number;
abstract onDeselect(): void;
abstract layoutChange(change: any): void;
assertTextModelAttached(): boolean {
if (this.textModel && this._textEditor && this._textEditor.getModel() === this.textModel) {
return true;
}
return false;
}
// private handleKeyDown(e: IKeyboardEvent) {
// if (this.viewType === IPYNB_VIEW_TYPE && isWindows && e.ctrlKey && e.keyCode === KeyCode.Enter) {
// this._keymapService.promptKeymapRecommendation();
// }
// }
attachTextEditor(editor: ICodeEditor, estimatedHasHorizontalScrolling?: boolean) {
if (!editor.hasModel()) {
throw new Error('Invalid editor: model is missing');
}
if (this._textEditor === editor) {
if (this._editorListeners.length === 0) {
this._editorListeners.push(this._textEditor.onDidChangeCursorSelection(() => { this._onDidChangeState.fire({ selectionChanged: true }); }));
// this._editorListeners.push(this._textEditor.onKeyDown(e => this.handleKeyDown(e)));
this._onDidChangeState.fire({ selectionChanged: true });
}
return;
}
this._textEditor = editor;
if (this._editorViewStates) {
this._restoreViewState(this._editorViewStates);
} else {
// If no real editor view state was persisted, restore a default state.
// This forces the editor to measure its content width immediately.
if (estimatedHasHorizontalScrolling) {
this._restoreViewState({
contributionsState: {},
cursorState: [],
viewState: {
scrollLeft: 0,
firstPosition: { lineNumber: 1, column: 1 },
firstPositionDeltaTop: getEditorTopPadding()
}
});
}
}
if (this._editorTransientState) {
writeTransientState(editor.getModel(), this._editorTransientState, this._codeEditorService);
}
this._textEditor?.changeDecorations((accessor) => {
this._resolvedDecorations.forEach((value, key) => {
if (key.startsWith('_lazy_')) {
// lazy ones
const ret = accessor.addDecoration(value.options.range, value.options.options);
this._resolvedDecorations.get(key)!.id = ret;
}
else {
const ret = accessor.addDecoration(value.options.range, value.options.options);
this._resolvedDecorations.get(key)!.id = ret;
}
});
});
this._editorListeners.push(this._textEditor.onDidChangeCursorSelection(() => { this._onDidChangeState.fire({ selectionChanged: true }); }));
// this._editorListeners.push(this._textEditor.onKeyDown(e => this.handleKeyDown(e)));
this._onDidChangeState.fire({ selectionChanged: true });
this._onDidChangeEditorAttachState.fire();
}
detachTextEditor() {
this.saveViewState();
this.saveTransientState();
// decorations need to be cleared first as editors can be resued.
this._textEditor?.changeDecorations((accessor) => {
this._resolvedDecorations.forEach(value => {
const resolvedid = value.id;
if (resolvedid) {
accessor.removeDecoration(resolvedid);
}
});
});
this._textEditor = undefined;
dispose(this._editorListeners);
this._editorListeners = [];
this._onDidChangeEditorAttachState.fire();
if (this._textModelRef) {
this._textModelRef.dispose();
this._textModelRef = undefined;
}
}
getText(): string {
return this.model.getValue();
}
getTextLength(): number {
return this.model.getTextLength();
}
private saveViewState(): void {
if (!this._textEditor) {
return;
}
this._editorViewStates = this._textEditor.saveViewState();
}
private saveTransientState() {
if (!this._textEditor || !this._textEditor.hasModel()) {
return;
}
this._editorTransientState = readTransientState(this._textEditor.getModel(), this._codeEditorService);
}
saveEditorViewState() {
if (this._textEditor) {
this._editorViewStates = this._textEditor.saveViewState();
}
return this._editorViewStates;
}
restoreEditorViewState(editorViewStates: editorCommon.ICodeEditorViewState | null, totalHeight?: number) {
this._editorViewStates = editorViewStates;
}
private _restoreViewState(state: editorCommon.ICodeEditorViewState | null): void {
if (state) {
this._textEditor?.restoreViewState(state);
}
}
addModelDecoration(decoration: model.IModelDeltaDecoration): string {
if (!this._textEditor) {
const id = ++this._lastDecorationId;
const decorationId = `_lazy_${this.id};${id}`;
this._resolvedDecorations.set(decorationId, { options: decoration });
return decorationId;
}
let id: string;
this._textEditor.changeDecorations((accessor) => {
id = accessor.addDecoration(decoration.range, decoration.options);
this._resolvedDecorations.set(id, { id, options: decoration });
});
return id!;
}
removeModelDecoration(decorationId: string) {
const realDecorationId = this._resolvedDecorations.get(decorationId);
if (this._textEditor && realDecorationId && realDecorationId.id !== undefined) {
this._textEditor.changeDecorations((accessor) => {
accessor.removeDecoration(realDecorationId.id!);
});
}
// lastly, remove all the cache
this._resolvedDecorations.delete(decorationId);
}
deltaModelDecorations(oldDecorations: readonly string[], newDecorations: readonly model.IModelDeltaDecoration[]): string[] {
oldDecorations.forEach(id => {
this.removeModelDecoration(id);
});
const ret = newDecorations.map(option => {
return this.addModelDecoration(option);
});
return ret;
}
private _removeCellDecoration(decorationId: string) {
const options = this._resolvedCellDecorations.get(decorationId);
this._resolvedCellDecorations.delete(decorationId);
if (options) {
for (const existingOptions of this._resolvedCellDecorations.values()) {
// don't remove decorations that are applied from other entries
if (options.className === existingOptions.className) {
options.className = undefined;
}
if (options.outputClassName === existingOptions.outputClassName) {
options.outputClassName = undefined;
}
if (options.gutterClassName === existingOptions.gutterClassName) {
options.gutterClassName = undefined;
}
if (options.topClassName === existingOptions.topClassName) {
options.topClassName = undefined;
}
}
this._cellDecorationsChanged.fire({ added: [], removed: [options] });
}
}
private _addCellDecoration(options: INotebookCellDecorationOptions): string {
const id = ++this._lastDecorationId;
const decorationId = `_cell_${this.id};${id}`;
this._resolvedCellDecorations.set(decorationId, options);
this._cellDecorationsChanged.fire({ added: [options], removed: [] });
return decorationId;
}
getCellDecorations() {
return [...this._resolvedCellDecorations.values()];
}
getCellDecorationRange(decorationId: string): Range | null {
if (this._textEditor) {
// (this._textEditor as CodeEditorWidget).decora
return this._textEditor.getModel()?.getDecorationRange(decorationId) ?? null;
}
return null;
}
deltaCellDecorations(oldDecorations: string[], newDecorations: INotebookCellDecorationOptions[]): string[] {
oldDecorations.forEach(id => {
this._removeCellDecoration(id);
});
const ret = newDecorations.map(option => {
return this._addCellDecoration(option);
});
return ret;
}
deltaCellStatusBarItems(oldItems: readonly string[], newItems: readonly INotebookCellStatusBarItem[]): string[] {
oldItems.forEach(id => {
const item = this._cellStatusBarItems.get(id);
if (item) {
this._cellStatusBarItems.delete(id);
}
});
const newIds = newItems.map(item => {
const id = ++this._lastStatusBarId;
const itemId = `_cell_${this.id};${id}`;
this._cellStatusBarItems.set(itemId, item);
return itemId;
});
this._onDidChangeCellStatusBarItems.fire();
return newIds;
}
getCellStatusBarItems(): INotebookCellStatusBarItem[] {
return Array.from(this._cellStatusBarItems.values());
}
revealRangeInCenter(range: Range) {
this._textEditor?.revealRangeInCenter(range, editorCommon.ScrollType.Immediate);
}
setSelection(range: Range) {
this._textEditor?.setSelection(range);
}
setSelections(selections: Selection[]) {
if (selections.length) {
this._textEditor?.setSelections(selections);
}
}
getSelections() {
return this._textEditor?.getSelections() || [];
}
getSelectionsStartPosition(): IPosition[] | undefined {
if (this._textEditor) {
const selections = this._textEditor.getSelections();
return selections?.map(s => s.getStartPosition());
} else {
const selections = this._editorViewStates?.cursorState;
return selections?.map(s => s.selectionStart);
}
}
getLineScrollTopOffset(line: number): number {
if (!this._textEditor) {
return 0;
}
const editorPadding = this._viewContext.notebookOptions.computeEditorPadding(this.internalMetadata, this.uri);
return this._textEditor.getTopForLineNumber(line) + editorPadding.top;
}
getPositionScrollTopOffset(range: Selection | Range): number {
if (!this._textEditor) {
return 0;
}
const position = range instanceof Selection ? range.getPosition() : range.getStartPosition();
const editorPadding = this._viewContext.notebookOptions.computeEditorPadding(this.internalMetadata, this.uri);
return this._textEditor.getTopForPosition(position.lineNumber, position.column) + editorPadding.top;
}
cursorAtLineBoundary(): CursorAtLineBoundary {
if (!this._textEditor || !this.textModel || !this._textEditor.hasTextFocus()) {
return CursorAtLineBoundary.None;
}
const selection = this._textEditor.getSelection();
if (!selection || !selection.isEmpty()) {
return CursorAtLineBoundary.None;
}
const currentLineLength = this.textModel.getLineLength(selection.startLineNumber);
if (currentLineLength === 0) {
return CursorAtLineBoundary.Both;
}
switch (selection.startColumn) {
case 1:
return CursorAtLineBoundary.Start;
case currentLineLength + 1:
return CursorAtLineBoundary.End;
default:
return CursorAtLineBoundary.None;
}
}
cursorAtBoundary(): CursorAtBoundary {
if (!this._textEditor) {
return CursorAtBoundary.None;
}
if (!this.textModel) {
return CursorAtBoundary.None;
}
// only validate primary cursor
const selection = this._textEditor.getSelection();
// only validate empty cursor
if (!selection || !selection.isEmpty()) {
return CursorAtBoundary.None;
}
const firstViewLineTop = this._textEditor.getTopForPosition(1, 1);
const lastViewLineTop = this._textEditor.getTopForPosition(this.textModel!.getLineCount(), this.textModel!.getLineLength(this.textModel!.getLineCount()));
const selectionTop = this._textEditor.getTopForPosition(selection.startLineNumber, selection.startColumn);
if (selectionTop === lastViewLineTop) {
if (selectionTop === firstViewLineTop) {
return CursorAtBoundary.Both;
} else {
return CursorAtBoundary.Bottom;
}
} else {
if (selectionTop === firstViewLineTop) {
return CursorAtBoundary.Top;
} else {
return CursorAtBoundary.None;
}
}
}
private _editStateSource: string = '';
get editStateSource(): string {
return this._editStateSource;
}
updateEditState(newState: CellEditState, source: string) {
this._editStateSource = source;
if (newState === this._editState) {
return;
}
this._editState = newState;
this._onDidChangeState.fire({ editStateChanged: true });
if (this._editState === CellEditState.Preview) {
this.focusMode = CellFocusMode.Container;
}
}
getEditState() {
return this._editState;
}
get textBuffer() {
return this.model.textBuffer;
}
/**
* Text model is used for editing.
*/
async resolveTextModel(): Promise<model.ITextModel> {
if (!this._textModelRef || !this.textModel) {
this._textModelRef = await this._modelService.createModelReference(this.uri);
if (this._isDisposed) {
return this.textModel!;
}
if (!this._textModelRef) {
throw new Error(`Cannot resolve text model for ${this.uri}`);
}
this._register(this.textModel!.onDidChangeContent(() => this.onDidChangeTextModelContent()));
}
return this.textModel!;
}
protected abstract onDidChangeTextModelContent(): void;
protected cellStartFind(value: string, options: INotebookSearchOptions): model.FindMatch[] | null {
let cellMatches: model.FindMatch[] = [];
if (this.assertTextModelAttached()) {
cellMatches = this.textModel!.findMatches(
value,
false,
options.regex || false,
options.caseSensitive || false,
options.wholeWord ? options.wordSeparators || null : null,
options.regex || false);
} else {
const lineCount = this.textBuffer.getLineCount();
const fullRange = new Range(1, 1, lineCount, this.textBuffer.getLineLength(lineCount) + 1);
const searchParams = new SearchParams(value, options.regex || false, options.caseSensitive || false, options.wholeWord ? options.wordSeparators || null : null,);
const searchData = searchParams.parseSearchRequest();
if (!searchData) {
return null;
}
cellMatches = this.textBuffer.findMatchesLineByLine(fullRange, searchData, options.regex || false, 1000);
}
return cellMatches;
}
override dispose() {
this._isDisposed = true;
super.dispose();
dispose(this._editorListeners);
// Only remove the undo redo stack if we map this cell uri to itself
// If we are not in perCell mode, it will map to the full NotebookDocument and
// we don't want to remove that entire document undo / redo stack when a cell is deleted
if (this._undoRedoService.getUriComparisonKey(this.uri) === this.uri.toString()) {
this._undoRedoService.removeElements(this.uri);
}
this._textModelRef?.dispose();
}
toJSON(): object {
return {
handle: this.handle
};
}
}
| src/vs/workbench/contrib/notebook/browser/viewModel/baseCellViewModel.ts | 0 | https://github.com/microsoft/vscode/commit/48a9149e6ad2cbc0f7ebfdb2ce6143627c077d1e | [
0.9865931868553162,
0.030802881345152855,
0.000165100849699229,
0.00022061096387915313,
0.16425667703151703
] |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.