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": 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 type MarkdownIt = require('markdown-it');
import type Token = require('markdown-it/lib/token');
import * as vscode from 'vscode';
import { ILogger } from './logging';
import { MarkdownContributionProvider } from './markdownExtensions';
import { Slugifier } from './slugify';
import { ITextDocument } from './types/textDocument';
import { WebviewResourceProvider } from './util/resources';
import { isOfScheme, Schemes } from './util/schemes';
/**
* Adds begin line index to the output via the 'data-line' data attribute.
*/
const pluginSourceMap: MarkdownIt.PluginSimple = (md): void => {
// Set the attribute on every possible token.
md.core.ruler.push('source_map_data_attribute', (state): void => {
for (const token of state.tokens) {
if (token.map && token.type !== 'inline') {
token.attrSet('data-line', String(token.map[0]));
token.attrJoin('class', 'code-line');
token.attrJoin('dir', 'auto');
}
}
});
// The 'html_block' renderer doesn't respect `attrs`. We need to insert a marker.
const originalHtmlBlockRenderer = md.renderer.rules['html_block'];
if (originalHtmlBlockRenderer) {
md.renderer.rules['html_block'] = (tokens, idx, options, env, self) => (
`<div ${self.renderAttrs(tokens[idx])} ></div>\n` +
originalHtmlBlockRenderer(tokens, idx, options, env, self)
);
}
};
/**
* The markdown-it options that we expose in the settings.
*/
type MarkdownItConfig = Readonly<Required<Pick<MarkdownIt.Options, 'breaks' | 'linkify' | 'typographer'>>>;
class TokenCache {
private _cachedDocument?: {
readonly uri: vscode.Uri;
readonly version: number;
readonly config: MarkdownItConfig;
};
private _tokens?: Token[];
public tryGetCached(document: ITextDocument, config: MarkdownItConfig): Token[] | undefined {
if (this._cachedDocument
&& this._cachedDocument.uri.toString() === document.uri.toString()
&& this._cachedDocument.version === document.version
&& this._cachedDocument.config.breaks === config.breaks
&& this._cachedDocument.config.linkify === config.linkify
) {
return this._tokens;
}
return undefined;
}
public update(document: ITextDocument, config: MarkdownItConfig, tokens: Token[]) {
this._cachedDocument = {
uri: document.uri,
version: document.version,
config,
};
this._tokens = tokens;
}
public clean(): void {
this._cachedDocument = undefined;
this._tokens = undefined;
}
}
export interface RenderOutput {
html: string;
containingImages: Set<string>;
}
interface RenderEnv {
containingImages: Set<string>;
currentDocument: vscode.Uri | undefined;
resourceProvider: WebviewResourceProvider | undefined;
}
export interface IMdParser {
readonly slugifier: Slugifier;
tokenize(document: ITextDocument): Promise<Token[]>;
}
export class MarkdownItEngine implements IMdParser {
private _md?: Promise<MarkdownIt>;
private _slugCount = new Map<string, number>();
private _tokenCache = new TokenCache();
public readonly slugifier: Slugifier;
public constructor(
private readonly _contributionProvider: MarkdownContributionProvider,
slugifier: Slugifier,
private readonly _logger: ILogger,
) {
this.slugifier = slugifier;
_contributionProvider.onContributionsChanged(() => {
// Markdown plugin contributions may have changed
this._md = undefined;
this._tokenCache.clean();
});
}
private async _getEngine(config: MarkdownItConfig): Promise<MarkdownIt> {
if (!this._md) {
this._md = (async () => {
const markdownIt = await import('markdown-it');
let md: MarkdownIt = markdownIt(await getMarkdownOptions(() => md));
md.linkify.set({ fuzzyLink: false });
for (const plugin of this._contributionProvider.contributions.markdownItPlugins.values()) {
try {
md = (await plugin)(md);
} catch (e) {
console.error('Could not load markdown it plugin', e);
}
}
const frontMatterPlugin = await import('markdown-it-front-matter');
// Extract rules from front matter plugin and apply at a lower precedence
let fontMatterRule: any;
frontMatterPlugin({
block: {
ruler: {
before: (_id: any, _id2: any, rule: any) => { fontMatterRule = rule; }
}
}
}, () => { /* noop */ });
md.block.ruler.before('fence', 'front_matter', fontMatterRule, {
alt: ['paragraph', 'reference', 'blockquote', 'list']
});
this._addImageRenderer(md);
this._addFencedRenderer(md);
this._addLinkNormalizer(md);
this._addLinkValidator(md);
this._addNamedHeaders(md);
this._addLinkRenderer(md);
md.use(pluginSourceMap);
return md;
})();
}
const md = await this._md!;
md.set(config);
return md;
}
public reloadPlugins() {
this._md = undefined;
}
private _tokenizeDocument(
document: ITextDocument,
config: MarkdownItConfig,
engine: MarkdownIt
): Token[] {
const cached = this._tokenCache.tryGetCached(document, config);
if (cached) {
this._resetSlugCount();
return cached;
}
this._logger.verbose('MarkdownItEngine', `tokenizeDocument - ${document.uri}`);
const tokens = this._tokenizeString(document.getText(), engine);
this._tokenCache.update(document, config, tokens);
return tokens;
}
private _tokenizeString(text: string, engine: MarkdownIt) {
this._resetSlugCount();
return engine.parse(text, {});
}
private _resetSlugCount(): void {
this._slugCount = new Map<string, number>();
}
public async render(input: ITextDocument | string, resourceProvider?: WebviewResourceProvider): Promise<RenderOutput> {
const config = this._getConfig(typeof input === 'string' ? undefined : input.uri);
const engine = await this._getEngine(config);
const tokens = typeof input === 'string'
? this._tokenizeString(input, engine)
: this._tokenizeDocument(input, config, engine);
const env: RenderEnv = {
containingImages: new Set<string>(),
currentDocument: typeof input === 'string' ? undefined : input.uri,
resourceProvider,
};
const html = engine.renderer.render(tokens, {
...engine.options,
...config
}, env);
return {
html,
containingImages: env.containingImages
};
}
public async tokenize(document: ITextDocument): Promise<Token[]> {
const config = this._getConfig(document.uri);
const engine = await this._getEngine(config);
return this._tokenizeDocument(document, config, engine);
}
public cleanCache(): void {
this._tokenCache.clean();
}
private _getConfig(resource?: vscode.Uri): MarkdownItConfig {
const config = vscode.workspace.getConfiguration('markdown', resource ?? null);
return {
breaks: config.get<boolean>('preview.breaks', false),
linkify: config.get<boolean>('preview.linkify', true),
typographer: config.get<boolean>('preview.typographer', false)
};
}
private _addImageRenderer(md: MarkdownIt): void {
const original = md.renderer.rules.image;
md.renderer.rules.image = (tokens: Token[], idx: number, options, env: RenderEnv, self) => {
const token = tokens[idx];
const src = token.attrGet('src');
if (src) {
env.containingImages?.add(src);
if (!token.attrGet('data-src')) {
token.attrSet('src', this._toResourceUri(src, env.currentDocument, env.resourceProvider));
token.attrSet('data-src', src);
}
}
if (original) {
return original(tokens, idx, options, env, self);
} else {
return self.renderToken(tokens, idx, options);
}
};
}
private _addFencedRenderer(md: MarkdownIt): void {
const original = md.renderer.rules['fenced'];
md.renderer.rules['fenced'] = (tokens: Token[], idx: number, options, env, self) => {
const token = tokens[idx];
if (token.map?.length) {
token.attrJoin('class', 'hljs');
}
if (original) {
return original(tokens, idx, options, env, self);
} else {
return self.renderToken(tokens, idx, options);
}
};
}
private _addLinkNormalizer(md: MarkdownIt): void {
const normalizeLink = md.normalizeLink;
md.normalizeLink = (link: string) => {
try {
// Normalize VS Code schemes to target the current version
if (isOfScheme(Schemes.vscode, link) || isOfScheme(Schemes['vscode-insiders'], link)) {
return normalizeLink(vscode.Uri.parse(link).with({ scheme: vscode.env.uriScheme }).toString());
}
} catch (e) {
// noop
}
return normalizeLink(link);
};
}
private _addLinkValidator(md: MarkdownIt): void {
const validateLink = md.validateLink;
md.validateLink = (link: string) => {
return validateLink(link)
|| isOfScheme(Schemes.vscode, link)
|| isOfScheme(Schemes['vscode-insiders'], link)
|| /^data:image\/.*?;/.test(link);
};
}
private _addNamedHeaders(md: MarkdownIt): void {
const original = md.renderer.rules.heading_open;
md.renderer.rules.heading_open = (tokens: Token[], idx: number, options, env, self) => {
const title = tokens[idx + 1].children!.reduce<string>((acc, t) => acc + t.content, '');
let slug = this.slugifier.fromHeading(title);
if (this._slugCount.has(slug.value)) {
const count = this._slugCount.get(slug.value)!;
this._slugCount.set(slug.value, count + 1);
slug = this.slugifier.fromHeading(slug.value + '-' + (count + 1));
} else {
this._slugCount.set(slug.value, 0);
}
tokens[idx].attrSet('id', slug.value);
if (original) {
return original(tokens, idx, options, env, self);
} else {
return self.renderToken(tokens, idx, options);
}
};
}
private _addLinkRenderer(md: MarkdownIt): void {
const original = md.renderer.rules.link_open;
md.renderer.rules.link_open = (tokens: Token[], idx: number, options, env, self) => {
const token = tokens[idx];
const href = token.attrGet('href');
// A string, including empty string, may be `href`.
if (typeof href === 'string') {
token.attrSet('data-href', href);
}
if (original) {
return original(tokens, idx, options, env, self);
} else {
return self.renderToken(tokens, idx, options);
}
};
}
private _toResourceUri(href: string, currentDocument: vscode.Uri | undefined, resourceProvider: WebviewResourceProvider | undefined): string {
try {
// Support file:// links
if (isOfScheme(Schemes.file, href)) {
const uri = vscode.Uri.parse(href);
if (resourceProvider) {
return resourceProvider.asWebviewUri(uri).toString(true);
}
// Not sure how to resolve this
return href;
}
// If original link doesn't look like a url with a scheme, assume it must be a link to a file in workspace
if (!/^[a-z\-]+:/i.test(href)) {
// Use a fake scheme for parsing
let uri = vscode.Uri.parse('markdown-link:' + href);
// Relative paths should be resolved correctly inside the preview but we need to
// handle absolute paths specially to resolve them relative to the workspace root
if (uri.path[0] === '/' && currentDocument) {
const root = vscode.workspace.getWorkspaceFolder(currentDocument);
if (root) {
uri = vscode.Uri.joinPath(root.uri, uri.fsPath).with({
fragment: uri.fragment,
query: uri.query,
});
if (resourceProvider) {
return resourceProvider.asWebviewUri(uri).toString(true);
} else {
uri = uri.with({ scheme: 'markdown-link' });
}
}
}
return uri.toString(true).replace(/^markdown-link:/, '');
}
return href;
} catch {
return href;
}
}
}
async function getMarkdownOptions(md: () => MarkdownIt): Promise<MarkdownIt.Options> {
const hljs = (await import('highlight.js')).default;
return {
html: true,
highlight: (str: string, lang?: string) => {
lang = normalizeHighlightLang(lang);
if (lang && hljs.getLanguage(lang)) {
try {
return hljs.highlight(str, {
language: lang,
ignoreIllegals: true,
}).value;
}
catch (error) { }
}
return md().utils.escapeHtml(str);
}
};
}
function normalizeHighlightLang(lang: string | undefined) {
switch (lang && lang.toLowerCase()) {
case 'shell':
return 'sh';
case 'py3':
return 'python';
case 'tsx':
case 'typescriptreact':
// Workaround for highlight not supporting tsx: https://github.com/isagalaev/highlight.js/issues/1155
return 'jsx';
case 'json5':
case 'jsonc':
return 'json';
case 'c#':
case 'csharp':
return 'cs';
default:
return lang;
}
}
| extensions/markdown-language-features/src/markdownEngine.ts | 0 | https://github.com/microsoft/vscode/commit/48a9149e6ad2cbc0f7ebfdb2ce6143627c077d1e | [
0.00018058382556773722,
0.0001728329370962456,
0.00016421457985416055,
0.0001733182871248573,
0.0000029548932616307866
] |
{
"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 { EditorModel } from 'vs/workbench/common/editor/editorModel';
import { IResolvableEditorModel } from 'vs/platform/editor/common/editor';
/**
* The base editor model for the diff editor. It is made up of two editor models, the original version
* and the modified version.
*/
export class DiffEditorModel extends EditorModel {
protected readonly _originalModel: IResolvableEditorModel | undefined;
get originalModel(): IResolvableEditorModel | undefined { return this._originalModel; }
protected readonly _modifiedModel: IResolvableEditorModel | undefined;
get modifiedModel(): IResolvableEditorModel | undefined { return this._modifiedModel; }
constructor(originalModel: IResolvableEditorModel | undefined, modifiedModel: IResolvableEditorModel | undefined) {
super();
this._originalModel = originalModel;
this._modifiedModel = modifiedModel;
}
override async resolve(): Promise<void> {
await Promise.all([
this._originalModel?.resolve(),
this._modifiedModel?.resolve()
]);
}
override isResolved(): boolean {
return !!(this._originalModel?.isResolved() && this._modifiedModel?.isResolved());
}
override dispose(): void {
// Do not propagate the dispose() call to the two models inside. We never created the two models
// (original and modified) so we can not dispose them without sideeffects. Rather rely on the
// models getting disposed when their related inputs get disposed from the diffEditorInput.
super.dispose();
}
}
| src/vs/workbench/common/editor/diffEditorModel.ts | 0 | https://github.com/microsoft/vscode/commit/48a9149e6ad2cbc0f7ebfdb2ce6143627c077d1e | [
0.00017700131866149604,
0.00017193671374116093,
0.0001681924914009869,
0.00017004465917125344,
0.0000033249843909288757
] |
{
"id": 2,
"code_window": [
"\t\t\twholeRange = raw.wholeRange ? Range.lift(raw.wholeRange) : editor.getSelection();\n",
"\t\t}\n",
"\n",
"\t\t// expand to whole lines\n",
"\t\twholeRange = new Range(wholeRange.startLineNumber, 1, wholeRange.endLineNumber, textModel.getLineMaxColumn(wholeRange.endLineNumber));\n",
"\n",
"\t\t// install managed-marker for the decoration range\n",
"\t\tconst wholeRangeMgr = new SessionWholeRange(textModel, wholeRange);\n",
"\t\tstore.add(wholeRangeMgr);\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/contrib/inlineChat/browser/inlineChatSession.ts",
"type": "replace",
"edit_start_line_idx": 520
} | /*---------------------------------------------------------------------------------------------
* 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.003901397343724966,
0.000566031550988555,
0.00016241877165157348,
0.00017529928300064057,
0.0008377142949029803
] |
{
"id": 2,
"code_window": [
"\t\t\twholeRange = raw.wholeRange ? Range.lift(raw.wholeRange) : editor.getSelection();\n",
"\t\t}\n",
"\n",
"\t\t// expand to whole lines\n",
"\t\twholeRange = new Range(wholeRange.startLineNumber, 1, wholeRange.endLineNumber, textModel.getLineMaxColumn(wholeRange.endLineNumber));\n",
"\n",
"\t\t// install managed-marker for the decoration range\n",
"\t\tconst wholeRangeMgr = new SessionWholeRange(textModel, wholeRange);\n",
"\t\tstore.add(wholeRangeMgr);\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/contrib/inlineChat/browser/inlineChatSession.ts",
"type": "replace",
"edit_start_line_idx": 520
} | /*---------------------------------------------------------------------------------------------
* 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 { Disposable, DisposableStore } from 'vs/base/common/lifecycle';
import { isLinux, isWindows } from 'vs/base/common/platform';
import { isEqual } from 'vs/base/common/resources';
import { URI } from 'vs/base/common/uri';
import { ensureNoDisposablesAreLeakedInTestSuite } from 'vs/base/test/common/utils';
import { FileChangesEvent, FileChangeType, IFileChange } from 'vs/platform/files/common/files';
import { coalesceEvents, reviveFileChanges, parseWatcherPatterns } from 'vs/platform/files/common/watcher';
class TestFileWatcher extends Disposable {
private readonly _onDidFilesChange: Emitter<{ raw: IFileChange[]; event: FileChangesEvent }>;
constructor() {
super();
this._onDidFilesChange = this._register(new Emitter<{ raw: IFileChange[]; event: FileChangesEvent }>());
}
get onDidFilesChange(): Event<{ raw: IFileChange[]; event: FileChangesEvent }> {
return this._onDidFilesChange.event;
}
report(changes: IFileChange[]): void {
this.onRawFileEvents(changes);
}
private onRawFileEvents(events: IFileChange[]): void {
// Coalesce
const coalescedEvents = coalesceEvents(events);
// Emit through event emitter
if (coalescedEvents.length > 0) {
this._onDidFilesChange.fire({ raw: reviveFileChanges(coalescedEvents), event: this.toFileChangesEvent(coalescedEvents) });
}
}
private toFileChangesEvent(changes: IFileChange[]): FileChangesEvent {
return new FileChangesEvent(reviveFileChanges(changes), !isLinux);
}
}
enum Path {
UNIX,
WINDOWS,
UNC
}
suite('Watcher', () => {
(isWindows ? test.skip : test)('parseWatcherPatterns - posix', () => {
const path = '/users/data/src';
let parsedPattern = parseWatcherPatterns(path, ['*.js'])[0];
assert.strictEqual(parsedPattern('/users/data/src/foo.js'), true);
assert.strictEqual(parsedPattern('/users/data/src/foo.ts'), false);
assert.strictEqual(parsedPattern('/users/data/src/bar/foo.js'), false);
parsedPattern = parseWatcherPatterns(path, ['/users/data/src/*.js'])[0];
assert.strictEqual(parsedPattern('/users/data/src/foo.js'), true);
assert.strictEqual(parsedPattern('/users/data/src/foo.ts'), false);
assert.strictEqual(parsedPattern('/users/data/src/bar/foo.js'), false);
parsedPattern = parseWatcherPatterns(path, ['/users/data/src/bar/*.js'])[0];
assert.strictEqual(parsedPattern('/users/data/src/foo.js'), false);
assert.strictEqual(parsedPattern('/users/data/src/foo.ts'), false);
assert.strictEqual(parsedPattern('/users/data/src/bar/foo.js'), true);
parsedPattern = parseWatcherPatterns(path, ['**/*.js'])[0];
assert.strictEqual(parsedPattern('/users/data/src/foo.js'), true);
assert.strictEqual(parsedPattern('/users/data/src/foo.ts'), false);
assert.strictEqual(parsedPattern('/users/data/src/bar/foo.js'), true);
});
(!isWindows ? test.skip : test)('parseWatcherPatterns - windows', () => {
const path = 'c:\\users\\data\\src';
let parsedPattern = parseWatcherPatterns(path, ['*.js'])[0];
assert.strictEqual(parsedPattern('c:\\users\\data\\src\\foo.js'), true);
assert.strictEqual(parsedPattern('c:\\users\\data\\src\\foo.ts'), false);
assert.strictEqual(parsedPattern('c:\\users\\data\\src\\bar/foo.js'), false);
parsedPattern = parseWatcherPatterns(path, ['c:\\users\\data\\src\\*.js'])[0];
assert.strictEqual(parsedPattern('c:\\users\\data\\src\\foo.js'), true);
assert.strictEqual(parsedPattern('c:\\users\\data\\src\\foo.ts'), false);
assert.strictEqual(parsedPattern('c:\\users\\data\\src\\bar\\foo.js'), false);
parsedPattern = parseWatcherPatterns(path, ['c:\\users\\data\\src\\bar/*.js'])[0];
assert.strictEqual(parsedPattern('c:\\users\\data\\src\\foo.js'), false);
assert.strictEqual(parsedPattern('c:\\users\\data\\src\\foo.ts'), false);
assert.strictEqual(parsedPattern('c:\\users\\data\\src\\bar\\foo.js'), true);
parsedPattern = parseWatcherPatterns(path, ['**/*.js'])[0];
assert.strictEqual(parsedPattern('c:\\users\\data\\src\\foo.js'), true);
assert.strictEqual(parsedPattern('c:\\users\\data\\src\\foo.ts'), false);
assert.strictEqual(parsedPattern('c:\\users\\data\\src\\bar\\foo.js'), true);
});
ensureNoDisposablesAreLeakedInTestSuite();
});
suite('Watcher Events Normalizer', () => {
const disposables = new DisposableStore();
teardown(() => {
disposables.clear();
});
test('simple add/update/delete', done => {
const watch = disposables.add(new TestFileWatcher());
const added = URI.file('/users/data/src/added.txt');
const updated = URI.file('/users/data/src/updated.txt');
const deleted = URI.file('/users/data/src/deleted.txt');
const raw: IFileChange[] = [
{ resource: added, type: FileChangeType.ADDED },
{ resource: updated, type: FileChangeType.UPDATED },
{ resource: deleted, type: FileChangeType.DELETED },
];
disposables.add(watch.onDidFilesChange(({ event, raw }) => {
assert.ok(event);
assert.strictEqual(raw.length, 3);
assert.ok(event.contains(added, FileChangeType.ADDED));
assert.ok(event.contains(updated, FileChangeType.UPDATED));
assert.ok(event.contains(deleted, FileChangeType.DELETED));
done();
}));
watch.report(raw);
});
(isWindows ? [Path.WINDOWS, Path.UNC] : [Path.UNIX]).forEach(path => {
test(`delete only reported for top level folder (${path})`, done => {
const watch = disposables.add(new TestFileWatcher());
const deletedFolderA = URI.file(path === Path.UNIX ? '/users/data/src/todelete1' : path === Path.WINDOWS ? 'C:\\users\\data\\src\\todelete1' : '\\\\localhost\\users\\data\\src\\todelete1');
const deletedFolderB = URI.file(path === Path.UNIX ? '/users/data/src/todelete2' : path === Path.WINDOWS ? 'C:\\users\\data\\src\\todelete2' : '\\\\localhost\\users\\data\\src\\todelete2');
const deletedFolderBF1 = URI.file(path === Path.UNIX ? '/users/data/src/todelete2/file.txt' : path === Path.WINDOWS ? 'C:\\users\\data\\src\\todelete2\\file.txt' : '\\\\localhost\\users\\data\\src\\todelete2\\file.txt');
const deletedFolderBF2 = URI.file(path === Path.UNIX ? '/users/data/src/todelete2/more/test.txt' : path === Path.WINDOWS ? 'C:\\users\\data\\src\\todelete2\\more\\test.txt' : '\\\\localhost\\users\\data\\src\\todelete2\\more\\test.txt');
const deletedFolderBF3 = URI.file(path === Path.UNIX ? '/users/data/src/todelete2/super/bar/foo.txt' : path === Path.WINDOWS ? 'C:\\users\\data\\src\\todelete2\\super\\bar\\foo.txt' : '\\\\localhost\\users\\data\\src\\todelete2\\super\\bar\\foo.txt');
const deletedFileA = URI.file(path === Path.UNIX ? '/users/data/src/deleteme.txt' : path === Path.WINDOWS ? 'C:\\users\\data\\src\\deleteme.txt' : '\\\\localhost\\users\\data\\src\\deleteme.txt');
const addedFile = URI.file(path === Path.UNIX ? '/users/data/src/added.txt' : path === Path.WINDOWS ? 'C:\\users\\data\\src\\added.txt' : '\\\\localhost\\users\\data\\src\\added.txt');
const updatedFile = URI.file(path === Path.UNIX ? '/users/data/src/updated.txt' : path === Path.WINDOWS ? 'C:\\users\\data\\src\\updated.txt' : '\\\\localhost\\users\\data\\src\\updated.txt');
const raw: IFileChange[] = [
{ resource: deletedFolderA, type: FileChangeType.DELETED },
{ resource: deletedFolderB, type: FileChangeType.DELETED },
{ resource: deletedFolderBF1, type: FileChangeType.DELETED },
{ resource: deletedFolderBF2, type: FileChangeType.DELETED },
{ resource: deletedFolderBF3, type: FileChangeType.DELETED },
{ resource: deletedFileA, type: FileChangeType.DELETED },
{ resource: addedFile, type: FileChangeType.ADDED },
{ resource: updatedFile, type: FileChangeType.UPDATED }
];
disposables.add(watch.onDidFilesChange(({ event, raw }) => {
assert.ok(event);
assert.strictEqual(raw.length, 5);
assert.ok(event.contains(deletedFolderA, FileChangeType.DELETED));
assert.ok(event.contains(deletedFolderB, FileChangeType.DELETED));
assert.ok(event.contains(deletedFileA, FileChangeType.DELETED));
assert.ok(event.contains(addedFile, FileChangeType.ADDED));
assert.ok(event.contains(updatedFile, FileChangeType.UPDATED));
done();
}));
watch.report(raw);
});
});
test('event coalescer: ignore CREATE followed by DELETE', done => {
const watch = disposables.add(new TestFileWatcher());
const created = URI.file('/users/data/src/related');
const deleted = URI.file('/users/data/src/related');
const unrelated = URI.file('/users/data/src/unrelated');
const raw: IFileChange[] = [
{ resource: created, type: FileChangeType.ADDED },
{ resource: deleted, type: FileChangeType.DELETED },
{ resource: unrelated, type: FileChangeType.UPDATED },
];
disposables.add(watch.onDidFilesChange(({ event, raw }) => {
assert.ok(event);
assert.strictEqual(raw.length, 1);
assert.ok(event.contains(unrelated, FileChangeType.UPDATED));
done();
}));
watch.report(raw);
});
test('event coalescer: flatten DELETE followed by CREATE into CHANGE', done => {
const watch = disposables.add(new TestFileWatcher());
const deleted = URI.file('/users/data/src/related');
const created = URI.file('/users/data/src/related');
const unrelated = URI.file('/users/data/src/unrelated');
const raw: IFileChange[] = [
{ resource: deleted, type: FileChangeType.DELETED },
{ resource: created, type: FileChangeType.ADDED },
{ resource: unrelated, type: FileChangeType.UPDATED },
];
disposables.add(watch.onDidFilesChange(({ event, raw }) => {
assert.ok(event);
assert.strictEqual(raw.length, 2);
assert.ok(event.contains(deleted, FileChangeType.UPDATED));
assert.ok(event.contains(unrelated, FileChangeType.UPDATED));
done();
}));
watch.report(raw);
});
test('event coalescer: ignore UPDATE when CREATE received', done => {
const watch = disposables.add(new TestFileWatcher());
const created = URI.file('/users/data/src/related');
const updated = URI.file('/users/data/src/related');
const unrelated = URI.file('/users/data/src/unrelated');
const raw: IFileChange[] = [
{ resource: created, type: FileChangeType.ADDED },
{ resource: updated, type: FileChangeType.UPDATED },
{ resource: unrelated, type: FileChangeType.UPDATED },
];
disposables.add(watch.onDidFilesChange(({ event, raw }) => {
assert.ok(event);
assert.strictEqual(raw.length, 2);
assert.ok(event.contains(created, FileChangeType.ADDED));
assert.ok(!event.contains(created, FileChangeType.UPDATED));
assert.ok(event.contains(unrelated, FileChangeType.UPDATED));
done();
}));
watch.report(raw);
});
test('event coalescer: apply DELETE', done => {
const watch = disposables.add(new TestFileWatcher());
const updated = URI.file('/users/data/src/related');
const updated2 = URI.file('/users/data/src/related');
const deleted = URI.file('/users/data/src/related');
const unrelated = URI.file('/users/data/src/unrelated');
const raw: IFileChange[] = [
{ resource: updated, type: FileChangeType.UPDATED },
{ resource: updated2, type: FileChangeType.UPDATED },
{ resource: unrelated, type: FileChangeType.UPDATED },
{ resource: updated, type: FileChangeType.DELETED }
];
disposables.add(watch.onDidFilesChange(({ event, raw }) => {
assert.ok(event);
assert.strictEqual(raw.length, 2);
assert.ok(event.contains(deleted, FileChangeType.DELETED));
assert.ok(!event.contains(updated, FileChangeType.UPDATED));
assert.ok(event.contains(unrelated, FileChangeType.UPDATED));
done();
}));
watch.report(raw);
});
test('event coalescer: track case renames', done => {
const watch = disposables.add(new TestFileWatcher());
const oldPath = URI.file('/users/data/src/added');
const newPath = URI.file('/users/data/src/ADDED');
const raw: IFileChange[] = [
{ resource: newPath, type: FileChangeType.ADDED },
{ resource: oldPath, type: FileChangeType.DELETED }
];
disposables.add(watch.onDidFilesChange(({ event, raw }) => {
assert.ok(event);
assert.strictEqual(raw.length, 2);
for (const r of raw) {
if (isEqual(r.resource, oldPath)) {
assert.strictEqual(r.type, FileChangeType.DELETED);
} else if (isEqual(r.resource, newPath)) {
assert.strictEqual(r.type, FileChangeType.ADDED);
} else {
assert.fail();
}
}
done();
}));
watch.report(raw);
});
ensureNoDisposablesAreLeakedInTestSuite();
});
| src/vs/platform/files/test/common/watcher.test.ts | 0 | https://github.com/microsoft/vscode/commit/48a9149e6ad2cbc0f7ebfdb2ce6143627c077d1e | [
0.0016100247157737613,
0.0003793069627135992,
0.00015972767141647637,
0.00017613057570997626,
0.00039817532524466515
] |
{
"id": 2,
"code_window": [
"\t\t\twholeRange = raw.wholeRange ? Range.lift(raw.wholeRange) : editor.getSelection();\n",
"\t\t}\n",
"\n",
"\t\t// expand to whole lines\n",
"\t\twholeRange = new Range(wholeRange.startLineNumber, 1, wholeRange.endLineNumber, textModel.getLineMaxColumn(wholeRange.endLineNumber));\n",
"\n",
"\t\t// install managed-marker for the decoration range\n",
"\t\tconst wholeRangeMgr = new SessionWholeRange(textModel, wholeRange);\n",
"\t\tstore.add(wholeRangeMgr);\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/contrib/inlineChat/browser/inlineChatSession.ts",
"type": "replace",
"edit_start_line_idx": 520
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
declare let MonacoEnvironment: monaco.Environment | undefined;
interface Window {
MonacoEnvironment?: monaco.Environment | undefined;
}
declare namespace monaco {
export type Thenable<T> = PromiseLike<T>;
export interface Environment {
/**
* Define a global `monaco` symbol.
* This is true by default in AMD and false by default in ESM.
*/
globalAPI?: boolean;
/**
* The base url where the editor sources are found (which contains the vs folder)
*/
baseUrl?: string;
/**
* A web worker factory.
* NOTE: If `getWorker` is defined, `getWorkerUrl` is not invoked.
*/
getWorker?(workerId: string, label: string): Promise<Worker> | Worker;
/**
* Return the location for web worker scripts.
* NOTE: If `getWorker` is defined, `getWorkerUrl` is not invoked.
*/
getWorkerUrl?(workerId: string, label: string): string;
/**
* Create a trusted types policy (same API as window.trustedTypes.createPolicy)
*/
createTrustedTypesPolicy?(
policyName: string,
policyOptions?: ITrustedTypePolicyOptions,
): undefined | ITrustedTypePolicy;
}
export interface ITrustedTypePolicyOptions {
createHTML?: (input: string, ...arguments: any[]) => string;
createScript?: (input: string, ...arguments: any[]) => string;
createScriptURL?: (input: string, ...arguments: any[]) => string;
}
export interface ITrustedTypePolicy {
readonly name: string;
createHTML?(input: string): any;
createScript?(input: string): any;
createScriptURL?(input: string): any;
}
export interface IDisposable {
dispose(): void;
}
export interface IEvent<T> {
(listener: (e: T) => any, thisArg?: any): IDisposable;
}
/**
* A helper that allows to emit and listen to typed events
*/
export class Emitter<T> {
constructor();
readonly event: Event<T>;
fire(event: T): void;
dispose(): void;
}
#include(vs/platform/markers/common/markers): MarkerTag, MarkerSeverity
#include(vs/base/common/cancellation): CancellationTokenSource, CancellationToken
#include(vs/base/common/uri): URI, UriComponents
#include(vs/base/common/keyCodes): KeyCode
#include(vs/editor/common/services/editorBaseApi): KeyMod
#include(vs/base/common/htmlContent): IMarkdownString, MarkdownStringTrustedOptions
#include(vs/base/browser/keyboardEvent): IKeyboardEvent
#include(vs/base/browser/mouseEvent): IMouseEvent
#include(vs/editor/common/editorCommon): IScrollEvent
#include(vs/editor/common/core/position): IPosition, Position
#include(vs/editor/common/core/range): IRange, Range
#include(vs/editor/common/core/selection): ISelection, Selection, SelectionDirection
#include(vs/editor/common/languages): Token
}
declare namespace monaco.editor {
#includeAll(vs/editor/standalone/browser/standaloneEditor;languages.Token=>Token):
#include(vs/editor/standalone/common/standaloneTheme): BuiltinTheme, IStandaloneThemeData, IColors
#include(vs/editor/common/languages/supports/tokenization): ITokenThemeRule
#include(vs/editor/browser/services/webWorker): MonacoWebWorker, IWebWorkerOptions
#include(vs/editor/standalone/browser/standaloneCodeEditor): IActionDescriptor, IGlobalEditorOptions, IStandaloneEditorConstructionOptions, IStandaloneDiffEditorConstructionOptions, IStandaloneCodeEditor, IStandaloneDiffEditor
export interface ICommandHandler {
(...args: any[]): void;
}
export interface ILocalizedString {
original: string;
value: string;
}
export interface ICommandMetadata {
readonly description: ILocalizedString | string;
}
#include(vs/platform/contextkey/common/contextkey): IContextKey, ContextKeyValue
#include(vs/editor/standalone/browser/standaloneServices): IEditorOverrideServices
#include(vs/platform/markers/common/markers): IMarker, IMarkerData, IRelatedInformation
#include(vs/editor/standalone/browser/colorizer): IColorizerOptions, IColorizerElementOptions
#include(vs/base/common/scrollable): ScrollbarVisibility
#include(vs/base/common/themables): ThemeColor
#include(vs/editor/common/core/editOperation): ISingleEditOperation
#include(vs/editor/common/core/wordHelper): IWordAtPosition
#includeAll(vs/editor/common/model): IScrollEvent
#include(vs/editor/common/diff/legacyLinesDiffComputer): IChange, ICharChange, ILineChange
#include(vs/editor/common/core/dimension): IDimension
#includeAll(vs/editor/common/editorCommon): IScrollEvent
#includeAll(vs/editor/common/textModelEvents):
#includeAll(vs/editor/common/cursorEvents):
#include(vs/platform/accessibility/common/accessibility): AccessibilitySupport
#includeAll(vs/editor/common/config/editorOptions):
#include(vs/editor/browser/config/editorConfiguration): IEditorConstructionOptions
#includeAll(vs/editor/browser/editorBrowser;editorCommon.=>):
#include(vs/editor/common/config/fontInfo): FontInfo, BareFontInfo
#include(vs/editor/common/config/editorZoom): EditorZoom, IEditorZoom
//compatibility:
export type IReadOnlyModel = ITextModel;
export type IModel = ITextModel;
}
declare namespace monaco.languages {
#include(vs/base/common/glob): IRelativePattern
#include(vs/editor/common/languageSelector): LanguageSelector, LanguageFilter
#includeAll(vs/editor/standalone/browser/standaloneLanguages;languages.=>;editorCommon.=>editor.;model.=>editor.;IMarkerData=>editor.IMarkerData):
#includeAll(vs/editor/common/languages/languageConfiguration):
#includeAll(vs/editor/common/languages;IMarkerData=>editor.IMarkerData;ISingleEditOperation=>editor.ISingleEditOperation;model.=>editor.): Token
#include(vs/editor/common/languages/language): ILanguageExtensionPoint
#includeAll(vs/editor/standalone/common/monarch/monarchTypes):
}
declare namespace monaco.worker {
#include(vs/editor/common/model/mirrorTextModel): IMirrorTextModel
#includeAll(vs/editor/common/services/editorSimpleWorker;):
}
//dtsv=3
| build/monaco/monaco.d.ts.recipe | 0 | https://github.com/microsoft/vscode/commit/48a9149e6ad2cbc0f7ebfdb2ce6143627c077d1e | [
0.0001781211030902341,
0.00017106863379012793,
0.0001629901526030153,
0.00017177237896248698,
0.000004558959062705981
] |
{
"id": 2,
"code_window": [
"\t\t\twholeRange = raw.wholeRange ? Range.lift(raw.wholeRange) : editor.getSelection();\n",
"\t\t}\n",
"\n",
"\t\t// expand to whole lines\n",
"\t\twholeRange = new Range(wholeRange.startLineNumber, 1, wholeRange.endLineNumber, textModel.getLineMaxColumn(wholeRange.endLineNumber));\n",
"\n",
"\t\t// install managed-marker for the decoration range\n",
"\t\tconst wholeRangeMgr = new SessionWholeRange(textModel, wholeRange);\n",
"\t\tstore.add(wholeRangeMgr);\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/contrib/inlineChat/browser/inlineChatSession.ts",
"type": "replace",
"edit_start_line_idx": 520
} | {
parts: [
{
range: {
start: 0,
endExclusive: 6
},
editorRange: {
startLineNumber: 1,
startColumn: 1,
endLineNumber: 1,
endColumn: 7
},
agent: {
id: "agent",
metadata: { description: "" },
provideSlashCommands: [Function provideSlashCommands]
},
kind: "agent"
},
{
range: {
start: 6,
endExclusive: 35
},
editorRange: {
startLineNumber: 1,
startColumn: 7,
endLineNumber: 2,
endColumn: 21
},
text: " Please \ndo /subCommand with ",
kind: "text"
},
{
range: {
start: 35,
endExclusive: 45
},
editorRange: {
startLineNumber: 2,
startColumn: 21,
endLineNumber: 2,
endColumn: 31
},
variableName: "selection",
variableArg: "",
kind: "var"
},
{
range: {
start: 45,
endExclusive: 50
},
editorRange: {
startLineNumber: 2,
startColumn: 31,
endLineNumber: 3,
endColumn: 5
},
text: "\nand ",
kind: "text"
},
{
range: {
start: 50,
endExclusive: 63
},
editorRange: {
startLineNumber: 3,
startColumn: 5,
endLineNumber: 3,
endColumn: 18
},
variableName: "debugConsole",
variableArg: "",
kind: "var"
}
],
text: "@agent Please \ndo /subCommand with #selection\nand #debugConsole"
} | src/vs/workbench/contrib/chat/test/common/__snapshots__/ChatRequestParser_agents_and_variables_and_multiline__part2.0.snap | 0 | https://github.com/microsoft/vscode/commit/48a9149e6ad2cbc0f7ebfdb2ce6143627c077d1e | [
0.0002272766432724893,
0.00017446478886995465,
0.00016404273628722876,
0.00016626453725621104,
0.000019175435227225535
] |
{
"id": 3,
"code_window": [
"\n",
"\t\tassert.ok(ctrl.getWidgetPosition() === undefined);\n",
"\t});\n",
"\n",
"\ttest('wholeRange expands to whole lines, editor selection default', async function () {\n",
"\n",
"\t\teditor.setSelection(new Range(1, 1, 1, 3));\n",
"\t\tctrl = instaService.createInstance(TestController, editor);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\ttest('wholeRange does not expand to whole lines, editor selection default', async function () {\n"
],
"file_path": "src/vs/workbench/contrib/inlineChat/test/browser/inlineChatController.test.ts",
"type": "replace",
"edit_start_line_idx": 183
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { renderMarkdownAsPlaintext } from 'vs/base/browser/markdownRenderer';
import * as aria from 'vs/base/browser/ui/aria/aria';
import { coalesceInPlace } from 'vs/base/common/arrays';
import { Barrier, Queue, raceCancellation, raceCancellationError } from 'vs/base/common/async';
import { CancellationTokenSource } from 'vs/base/common/cancellation';
import { toErrorMessage } from 'vs/base/common/errorMessage';
import { onUnexpectedError } from 'vs/base/common/errors';
import { Emitter, Event } from 'vs/base/common/event';
import { MarkdownString } from 'vs/base/common/htmlContent';
import { Lazy } from 'vs/base/common/lazy';
import { DisposableStore, IDisposable, MutableDisposable, toDisposable } from 'vs/base/common/lifecycle';
import { MovingAverage } from 'vs/base/common/numbers';
import { StopWatch } from 'vs/base/common/stopwatch';
import { assertType } from 'vs/base/common/types';
import { generateUuid } from 'vs/base/common/uuid';
import { ICodeEditor } from 'vs/editor/browser/editorBrowser';
import { IBulkEditService } from 'vs/editor/browser/services/bulkEditService';
import { IPosition, Position } from 'vs/editor/common/core/position';
import { IRange, Range } from 'vs/editor/common/core/range';
import { ISelection, Selection } from 'vs/editor/common/core/selection';
import { IEditorContribution } from 'vs/editor/common/editorCommon';
import { TextEdit } from 'vs/editor/common/languages';
import { ModelDecorationOptions } from 'vs/editor/common/model/textModel';
import { IEditorWorkerService } from 'vs/editor/common/services/editorWorker';
import { InlineCompletionsController } from 'vs/editor/contrib/inlineCompletions/browser/inlineCompletionsController';
import { localize } from 'vs/nls';
import { IAccessibilityService } from 'vs/platform/accessibility/common/accessibility';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IContextKey, IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { IDialogService } from 'vs/platform/dialogs/common/dialogs';
import { IInstantiationService, ServicesAccessor } from 'vs/platform/instantiation/common/instantiation';
import { ILogService } from 'vs/platform/log/common/log';
import { Progress } from 'vs/platform/progress/common/progress';
import { IStorageService, StorageScope, StorageTarget } from 'vs/platform/storage/common/storage';
import { IChatAccessibilityService, IChatWidgetService } from 'vs/workbench/contrib/chat/browser/chat';
import { IChatAgentService } from 'vs/workbench/contrib/chat/common/chatAgents';
import { chatAgentLeader, chatSubcommandLeader } from 'vs/workbench/contrib/chat/common/chatParserTypes';
import { IChatService } from 'vs/workbench/contrib/chat/common/chatService';
import { EmptyResponse, ErrorResponse, ExpansionState, IInlineChatSessionService, ReplyResponse, Session, SessionExchange, SessionPrompt } from 'vs/workbench/contrib/inlineChat/browser/inlineChatSession';
import { EditModeStrategy, LivePreviewStrategy, LiveStrategy, PreviewStrategy, ProgressingEditsOptions } from 'vs/workbench/contrib/inlineChat/browser/inlineChatStrategies';
import { IInlineChatMessageAppender, InlineChatZoneWidget } from 'vs/workbench/contrib/inlineChat/browser/inlineChatWidget';
import { CTX_INLINE_CHAT_DID_EDIT, CTX_INLINE_CHAT_HAS_ACTIVE_REQUEST, CTX_INLINE_CHAT_HAS_STASHED_SESSION, CTX_INLINE_CHAT_LAST_FEEDBACK, CTX_INLINE_CHAT_RESPONSE_TYPES, CTX_INLINE_CHAT_SUPPORT_ISSUE_REPORTING, CTX_INLINE_CHAT_USER_DID_EDIT, EditMode, IInlineChatProgressItem, IInlineChatRequest, IInlineChatResponse, INLINE_CHAT_ID, InlineChatConfigKeys, InlineChatResponseFeedbackKind, InlineChatResponseTypes } from 'vs/workbench/contrib/inlineChat/common/inlineChat';
export const enum State {
CREATE_SESSION = 'CREATE_SESSION',
INIT_UI = 'INIT_UI',
WAIT_FOR_INPUT = 'WAIT_FOR_INPUT',
MAKE_REQUEST = 'MAKE_REQUEST',
APPLY_RESPONSE = 'APPLY_RESPONSE',
SHOW_RESPONSE = 'SHOW_RESPONSE',
PAUSE = 'PAUSE',
CANCEL = 'CANCEL',
ACCEPT = 'DONE',
}
const enum Message {
NONE = 0,
ACCEPT_SESSION = 1 << 0,
CANCEL_SESSION = 1 << 1,
PAUSE_SESSION = 1 << 2,
CANCEL_REQUEST = 1 << 3,
CANCEL_INPUT = 1 << 4,
ACCEPT_INPUT = 1 << 5,
RERUN_INPUT = 1 << 6,
}
export abstract class InlineChatRunOptions {
initialSelection?: ISelection;
initialRange?: IRange;
message?: string;
autoSend?: boolean;
existingSession?: Session;
isUnstashed?: boolean;
position?: IPosition;
static isInteractiveEditorOptions(options: any): options is InlineChatRunOptions {
const { initialSelection, initialRange, message, autoSend, position } = options;
if (
typeof message !== 'undefined' && typeof message !== 'string'
|| typeof autoSend !== 'undefined' && typeof autoSend !== 'boolean'
|| typeof initialRange !== 'undefined' && !Range.isIRange(initialRange)
|| typeof initialSelection !== 'undefined' && !Selection.isISelection(initialSelection)
|| typeof position !== 'undefined' && !Position.isIPosition(position)) {
return false;
}
return true;
}
}
export class InlineChatController implements IEditorContribution {
static get(editor: ICodeEditor) {
return editor.getContribution<InlineChatController>(INLINE_CHAT_ID);
}
private static _decoBlock = ModelDecorationOptions.register({
description: 'inline-chat',
showIfCollapsed: false,
isWholeLine: true,
className: 'inline-chat-block-selection',
});
private static _storageKey = 'inline-chat-history';
private static _promptHistory: string[] = [];
private _historyOffset: number = -1;
private _historyUpdate: (prompt: string) => void;
private readonly _store = new DisposableStore();
private readonly _zone: Lazy<InlineChatZoneWidget>;
private readonly _ctxHasActiveRequest: IContextKey<boolean>;
private readonly _ctxResponseTypes: IContextKey<undefined | InlineChatResponseTypes>;
private readonly _ctxDidEdit: IContextKey<boolean>;
private readonly _ctxUserDidEdit: IContextKey<boolean>;
private readonly _ctxLastFeedbackKind: IContextKey<'helpful' | 'unhelpful' | ''>;
private readonly _ctxSupportIssueReporting: IContextKey<boolean>;
private _messages = this._store.add(new Emitter<Message>());
private readonly _onWillStartSession = this._store.add(new Emitter<void>());
readonly onWillStartSession = this._onWillStartSession.event;
readonly onDidAcceptInput = Event.filter(this._messages.event, m => m === Message.ACCEPT_INPUT, this._store);
readonly onDidCancelInput = Event.filter(this._messages.event, m => m === Message.CANCEL_INPUT || m === Message.CANCEL_SESSION, this._store);
private readonly _sessionStore: DisposableStore = this._store.add(new DisposableStore());
private readonly _stashedSession: MutableDisposable<StashedSession> = this._store.add(new MutableDisposable());
private _activeSession?: Session;
private _strategy?: EditModeStrategy;
private _ignoreModelContentChanged = false;
constructor(
private readonly _editor: ICodeEditor,
@IInstantiationService private readonly _instaService: IInstantiationService,
@IInlineChatSessionService private readonly _inlineChatSessionService: IInlineChatSessionService,
@IEditorWorkerService private readonly _editorWorkerService: IEditorWorkerService,
@ILogService private readonly _logService: ILogService,
@IConfigurationService private readonly _configurationService: IConfigurationService,
@IDialogService private readonly _dialogService: IDialogService,
@IContextKeyService contextKeyService: IContextKeyService,
@IAccessibilityService private readonly _accessibilityService: IAccessibilityService,
@IChatAccessibilityService private readonly _chatAccessibilityService: IChatAccessibilityService,
@IChatAgentService private readonly _chatAgentService: IChatAgentService,
@IBulkEditService private readonly _bulkEditService: IBulkEditService,
@IStorageService private readonly _storageService: IStorageService,
) {
this._ctxHasActiveRequest = CTX_INLINE_CHAT_HAS_ACTIVE_REQUEST.bindTo(contextKeyService);
this._ctxDidEdit = CTX_INLINE_CHAT_DID_EDIT.bindTo(contextKeyService);
this._ctxUserDidEdit = CTX_INLINE_CHAT_USER_DID_EDIT.bindTo(contextKeyService);
this._ctxResponseTypes = CTX_INLINE_CHAT_RESPONSE_TYPES.bindTo(contextKeyService);
this._ctxLastFeedbackKind = CTX_INLINE_CHAT_LAST_FEEDBACK.bindTo(contextKeyService);
this._ctxSupportIssueReporting = CTX_INLINE_CHAT_SUPPORT_ISSUE_REPORTING.bindTo(contextKeyService);
this._zone = new Lazy(() => this._store.add(_instaService.createInstance(InlineChatZoneWidget, this._editor)));
this._store.add(this._editor.onDidChangeModel(async e => {
if (this._activeSession || !e.newModelUrl) {
return;
}
const existingSession = this._inlineChatSessionService.getSession(this._editor, e.newModelUrl);
if (!existingSession) {
return;
}
this._log('session RESUMING', e);
await this.run({ existingSession });
this._log('session done or paused');
}));
this._log('NEW controller');
InlineChatController._promptHistory = JSON.parse(_storageService.get(InlineChatController._storageKey, StorageScope.PROFILE, '[]'));
this._historyUpdate = (prompt: string) => {
const idx = InlineChatController._promptHistory.indexOf(prompt);
if (idx >= 0) {
InlineChatController._promptHistory.splice(idx, 1);
}
InlineChatController._promptHistory.unshift(prompt);
this._historyOffset = -1;
this._storageService.store(InlineChatController._storageKey, JSON.stringify(InlineChatController._promptHistory), StorageScope.PROFILE, StorageTarget.USER);
};
}
dispose(): void {
this._strategy?.dispose();
this._stashedSession.clear();
if (this._activeSession) {
this._inlineChatSessionService.releaseSession(this._activeSession);
}
this._store.dispose();
this._log('controller disposed');
}
private _log(message: string | Error, ...more: any[]): void {
if (message instanceof Error) {
this._logService.error(message, ...more);
} else {
this._logService.trace(`[IE] (editor:${this._editor.getId()})${message}`, ...more);
}
}
getMessage(): string | undefined {
return this._zone.value.widget.responseContent;
}
getId(): string {
return INLINE_CHAT_ID;
}
private _getMode(): EditMode {
const editMode = this._configurationService.inspect<EditMode>(InlineChatConfigKeys.Mode);
let editModeValue = editMode.value;
if (this._accessibilityService.isScreenReaderOptimized() && editModeValue === editMode.defaultValue) {
// By default, use preview mode for screen reader users
editModeValue = EditMode.Preview;
}
return editModeValue!;
}
getWidgetPosition(): Position | undefined {
return this._zone.value.position;
}
private _currentRun?: Promise<void>;
async run(options: InlineChatRunOptions | undefined = {}): Promise<void> {
try {
this.finishExistingSession();
if (this._currentRun) {
await this._currentRun;
}
this._stashedSession.clear();
if (options.initialSelection) {
this._editor.setSelection(options.initialSelection);
}
this._historyOffset = -1;
this._onWillStartSession.fire();
this._currentRun = this._nextState(State.CREATE_SESSION, options);
await this._currentRun;
} catch (error) {
// this should not happen but when it does make sure to tear down the UI and everything
onUnexpectedError(error);
if (this._activeSession) {
this._inlineChatSessionService.releaseSession(this._activeSession);
}
this[State.PAUSE]();
} finally {
this._currentRun = undefined;
}
}
joinCurrentRun(): Promise<void> | undefined {
return this._currentRun;
}
// ---- state machine
private _showWidget(initialRender: boolean = false, position?: Position) {
assertType(this._editor.hasModel());
let widgetPosition: Position;
if (position) {
// explicit position wins
widgetPosition = position;
} else if (this._zone.value.position) {
// already showing - special case of line 1
if (this._zone.value.position.lineNumber === 1) {
widgetPosition = this._zone.value.position.delta(-1);
} else {
widgetPosition = this._zone.value.position;
}
} else {
// default to ABOVE the selection
widgetPosition = this._editor.getSelection().getStartPosition().delta(-1);
}
let needsMargin = false;
if (initialRender) {
this._zone.value.setContainerMargins();
}
if (this._activeSession && !position && (this._activeSession.hasChangedText || this._activeSession.lastExchange)) {
widgetPosition = this._activeSession.wholeRange.value.getStartPosition().delta(-1);
}
if (this._activeSession) {
this._zone.value.updateBackgroundColor(widgetPosition, this._activeSession.wholeRange.value);
}
if (this._strategy) {
needsMargin = this._strategy.needsMargin();
}
if (!this._zone.value.position) {
this._zone.value.setWidgetMargins(widgetPosition, !needsMargin ? 0 : undefined);
this._zone.value.show(widgetPosition);
} else {
this._zone.value.updatePositionAndHeight(widgetPosition);
}
}
protected async _nextState(state: State, options: InlineChatRunOptions): Promise<void> {
let nextState: State | void = state;
while (nextState) {
this._log('setState to ', nextState);
nextState = await this[nextState](options);
}
}
private async [State.CREATE_SESSION](options: InlineChatRunOptions): Promise<State.CANCEL | State.INIT_UI | State.PAUSE> {
assertType(this._activeSession === undefined);
assertType(this._editor.hasModel());
let session: Session | undefined = options.existingSession;
let initPosition: Position | undefined;
if (options.position) {
initPosition = Position.lift(options.position).delta(-1);
delete options.position;
}
this._showWidget(true, initPosition);
this._updatePlaceholder();
if (!session) {
const createSessionCts = new CancellationTokenSource();
const msgListener = Event.once(this._messages.event)(m => {
this._log('state=_createSession) message received', m);
if (m === Message.ACCEPT_INPUT) {
// user accepted the input before having a session
options.autoSend = true;
this._zone.value.widget.updateProgress(true);
this._zone.value.widget.updateInfo(localize('welcome.2', "Getting ready..."));
} else {
createSessionCts.cancel();
}
});
session = await this._inlineChatSessionService.createSession(
this._editor,
{ editMode: this._getMode(), wholeRange: options.initialRange },
createSessionCts.token
);
createSessionCts.dispose();
msgListener.dispose();
if (createSessionCts.token.isCancellationRequested) {
return State.PAUSE;
}
}
delete options.initialRange;
delete options.existingSession;
if (!session) {
this._dialogService.info(localize('create.fail', "Failed to start editor chat"), localize('create.fail.detail', "Please consult the error log and try again later."));
return State.CANCEL;
}
switch (session.editMode) {
case EditMode.Live:
this._strategy = this._instaService.createInstance(LiveStrategy, session, this._editor, this._zone.value);
break;
case EditMode.Preview:
this._strategy = this._instaService.createInstance(PreviewStrategy, session, this._zone.value);
break;
case EditMode.LivePreview:
default:
this._strategy = this._instaService.createInstance(LivePreviewStrategy, session, this._editor, this._zone.value);
break;
}
this._activeSession = session;
return State.INIT_UI;
}
private async [State.INIT_UI](options: InlineChatRunOptions): Promise<State.WAIT_FOR_INPUT | State.SHOW_RESPONSE | State.APPLY_RESPONSE> {
assertType(this._activeSession);
assertType(this._strategy);
// hide/cancel inline completions when invoking IE
InlineCompletionsController.get(this._editor)?.hide();
this._sessionStore.clear();
const wholeRangeDecoration = this._editor.createDecorationsCollection();
const updateWholeRangeDecoration = () => {
const ranges = [this._activeSession!.wholeRange.value];//this._activeSession!.wholeRange.values;
const newDecorations = ranges.map(range => range.isEmpty() ? undefined : ({ range, options: InlineChatController._decoBlock }));
coalesceInPlace(newDecorations);
wholeRangeDecoration.set(newDecorations);
};
this._sessionStore.add(toDisposable(() => wholeRangeDecoration.clear()));
this._sessionStore.add(this._activeSession.wholeRange.onDidChange(updateWholeRangeDecoration));
updateWholeRangeDecoration();
this._zone.value.widget.updateSlashCommands(this._activeSession.session.slashCommands ?? []);
this._updatePlaceholder();
this._zone.value.widget.updateInfo(this._activeSession.session.message ?? localize('welcome.1', "AI-generated code may be incorrect"));
this._zone.value.widget.preferredExpansionState = this._activeSession.lastExpansionState;
this._zone.value.widget.value = this._activeSession.session.input ?? this._activeSession.lastInput?.value ?? this._zone.value.widget.value;
if (this._activeSession.session.input) {
this._zone.value.widget.selectAll();
}
this._showWidget(true);
this._sessionStore.add(this._editor.onDidChangeModel((e) => {
const msg = this._activeSession?.lastExchange
? Message.PAUSE_SESSION // pause when switching models/tabs and when having a previous exchange
: Message.CANCEL_SESSION;
this._log('model changed, pause or cancel session', msg, e);
this._messages.fire(msg);
}));
const altVersionNow = this._editor.getModel()?.getAlternativeVersionId();
this._sessionStore.add(this._editor.onDidChangeModelContent(e => {
if (!this._ignoreModelContentChanged && this._strategy?.hasFocus()) {
this._ctxUserDidEdit.set(altVersionNow !== this._editor.getModel()?.getAlternativeVersionId());
}
if (this._ignoreModelContentChanged || this._strategy?.hasFocus()) {
return;
}
const wholeRange = this._activeSession!.wholeRange;
let shouldFinishSession = false;
if (this._configurationService.getValue<boolean>(InlineChatConfigKeys.FinishOnType)) {
for (const { range } of e.changes) {
shouldFinishSession = !Range.areIntersectingOrTouching(range, wholeRange.value);
}
}
this._activeSession!.recordExternalEditOccurred(shouldFinishSession);
if (shouldFinishSession) {
this._log('text changed outside of whole range, FINISH session');
this.finishExistingSession();
}
}));
// Update context key
this._ctxSupportIssueReporting.set(this._activeSession.provider.supportIssueReporting ?? false);
if (!this._activeSession.lastExchange) {
return State.WAIT_FOR_INPUT;
} else if (options.isUnstashed) {
delete options.isUnstashed;
return State.APPLY_RESPONSE;
} else {
return State.SHOW_RESPONSE;
}
}
private _forcedPlaceholder: string | undefined = undefined;
setPlaceholder(text: string): void {
this._forcedPlaceholder = text;
this._updatePlaceholder();
}
resetPlaceholder(): void {
this._forcedPlaceholder = undefined;
this._updatePlaceholder();
}
private _updatePlaceholder(): void {
this._zone.value.widget.placeholder = this._getPlaceholderText();
}
private _getPlaceholderText(): string {
return this._forcedPlaceholder ?? this._activeSession?.session.placeholder ?? '';
}
private async [State.WAIT_FOR_INPUT](options: InlineChatRunOptions): Promise<State.ACCEPT | State.CANCEL | State.PAUSE | State.WAIT_FOR_INPUT | State.MAKE_REQUEST> {
assertType(this._activeSession);
assertType(this._strategy);
this._updatePlaceholder();
if (options.message) {
this.updateInput(options.message);
aria.alert(options.message);
delete options.message;
}
let message = Message.NONE;
if (options.autoSend) {
message = Message.ACCEPT_INPUT;
delete options.autoSend;
} else {
const barrier = new Barrier();
const store = new DisposableStore();
store.add(this._strategy.onDidAccept(() => this.acceptSession()));
store.add(this._strategy.onDidDiscard(() => this.cancelSession()));
store.add(Event.once(this._messages.event)(m => {
this._log('state=_waitForInput) message received', m);
message = m;
barrier.open();
}));
await barrier.wait();
store.dispose();
}
this._zone.value.widget.selectAll(false);
if (message & (Message.CANCEL_INPUT | Message.CANCEL_SESSION)) {
return State.CANCEL;
}
if (message & Message.ACCEPT_SESSION) {
return State.ACCEPT;
}
if (message & Message.PAUSE_SESSION) {
return State.PAUSE;
}
if (message & Message.RERUN_INPUT && this._activeSession.lastExchange) {
const { lastExchange } = this._activeSession;
this._activeSession.addInput(lastExchange.prompt.retry());
if (lastExchange.response instanceof ReplyResponse) {
try {
this._ignoreModelContentChanged = true;
await this._strategy.undoChanges(lastExchange.response.modelAltVersionId);
} finally {
this._ignoreModelContentChanged = false;
}
}
return State.MAKE_REQUEST;
}
if (!this.getInput()) {
return State.WAIT_FOR_INPUT;
}
const input = this.getInput();
this._historyUpdate(input);
const refer = this._activeSession.session.slashCommands?.some(value => value.refer && input!.startsWith(`/${value.command}`));
if (refer) {
this._log('[IE] seeing refer command, continuing outside editor', this._activeSession.provider.debugName);
this._editor.setSelection(this._activeSession.wholeRange.value);
let massagedInput = input;
if (input.startsWith(chatSubcommandLeader)) {
const withoutSubCommandLeader = input.slice(1);
const cts = new CancellationTokenSource();
this._sessionStore.add(cts);
for (const agent of this._chatAgentService.getAgents()) {
const commands = await agent.provideSlashCommands(cts.token);
if (commands.find((command) => withoutSubCommandLeader.startsWith(command.name))) {
massagedInput = `${chatAgentLeader}${agent.id} ${input}`;
break;
}
}
}
// if agent has a refer command, massage the input to include the agent name
this._instaService.invokeFunction(sendRequest, massagedInput);
if (!this._activeSession.lastExchange) {
// DONE when there wasn't any exchange yet. We used the inline chat only as trampoline
return State.ACCEPT;
}
return State.WAIT_FOR_INPUT;
}
this._activeSession.addInput(new SessionPrompt(input));
return State.MAKE_REQUEST;
}
private async [State.MAKE_REQUEST](): Promise<State.APPLY_RESPONSE | State.PAUSE | State.CANCEL | State.ACCEPT> {
assertType(this._editor.hasModel());
assertType(this._activeSession);
assertType(this._strategy);
assertType(this._activeSession.lastInput);
const requestCts = new CancellationTokenSource();
let message = Message.NONE;
const msgListener = Event.once(this._messages.event)(m => {
this._log('state=_makeRequest) message received', m);
message = m;
requestCts.cancel();
});
const typeListener = this._zone.value.widget.onDidChangeInput(() => requestCts.cancel());
const requestClock = StopWatch.create();
const request: IInlineChatRequest = {
requestId: generateUuid(),
prompt: this._activeSession.lastInput.value,
attempt: this._activeSession.lastInput.attempt,
selection: this._editor.getSelection(),
wholeRange: this._activeSession.wholeRange.value,
live: this._activeSession.editMode !== EditMode.Preview // TODO@jrieken let extension know what document is used for previewing
};
const modelAltVersionIdNow = this._activeSession.textModelN.getAlternativeVersionId();
const progressEdits: TextEdit[][] = [];
const progressiveEditsAvgDuration = new MovingAverage();
const progressiveEditsCts = new CancellationTokenSource(requestCts.token);
const progressiveEditsClock = StopWatch.create();
const progressiveEditsQueue = new Queue();
let progressiveChatResponse: IInlineChatMessageAppender | undefined;
const progress = new Progress<IInlineChatProgressItem>(data => {
this._log('received chunk', data, request);
if (requestCts.token.isCancellationRequested) {
return;
}
if (data.message) {
this._zone.value.widget.updateToolbar(false);
this._zone.value.widget.updateInfo(data.message);
}
if (data.slashCommand) {
const valueNow = this.getInput();
if (!valueNow.startsWith('/')) {
this._zone.value.widget.updateSlashCommandUsed(data.slashCommand);
}
}
if (data.edits?.length) {
if (!request.live) {
throw new Error('Progress in NOT supported in non-live mode');
}
progressEdits.push(data.edits);
progressiveEditsAvgDuration.update(progressiveEditsClock.elapsed());
progressiveEditsClock.reset();
progressiveEditsQueue.queue(async () => {
const startThen = this._activeSession!.wholeRange.value.getStartPosition();
// making changes goes into a queue because otherwise the async-progress time will
// influence the time it takes to receive the changes and progressive typing will
// become infinitely fast
await this._makeChanges(data.edits!, data.editsShouldBeInstant
? undefined
: { duration: progressiveEditsAvgDuration.value, token: progressiveEditsCts.token }
);
// reshow the widget if the start position changed or shows at the wrong position
const startNow = this._activeSession!.wholeRange.value.getStartPosition();
if (!startNow.equals(startThen) || !this._zone.value.position?.equals(startNow)) {
this._showWidget(false, startNow.delta(-1));
}
});
}
if (data.markdownFragment) {
if (!progressiveChatResponse) {
const message = {
message: new MarkdownString(data.markdownFragment, { supportThemeIcons: true, supportHtml: true, isTrusted: false }),
providerId: this._activeSession!.provider.debugName,
requestId: request.requestId,
};
progressiveChatResponse = this._zone.value.widget.updateChatMessage(message, true);
} else {
progressiveChatResponse.appendContent(data.markdownFragment);
}
}
});
let a11yResponse: string | undefined;
const a11yVerboseInlineChat = this._configurationService.getValue<boolean>('accessibility.verbosity.inlineChat') === true;
const requestId = this._chatAccessibilityService.acceptRequest();
const task = this._activeSession.provider.provideResponse(this._activeSession.session, request, progress, requestCts.token);
this._log('request started', this._activeSession.provider.debugName, this._activeSession.session, request);
let response: ReplyResponse | ErrorResponse | EmptyResponse;
let reply: IInlineChatResponse | null | undefined;
try {
this._zone.value.widget.updateChatMessage(undefined);
this._zone.value.widget.updateFollowUps(undefined);
this._zone.value.widget.updateProgress(true);
this._zone.value.widget.updateInfo(!this._activeSession.lastExchange ? localize('thinking', "Thinking\u2026") : '');
await this._strategy.start();
this._ctxHasActiveRequest.set(true);
reply = await raceCancellationError(Promise.resolve(task), requestCts.token);
if (progressiveEditsQueue.size > 0) {
// we must wait for all edits that came in via progress to complete
await Event.toPromise(progressiveEditsQueue.onDrained);
}
if (progressiveChatResponse) {
progressiveChatResponse.cancel();
}
if (!reply) {
response = new EmptyResponse();
a11yResponse = localize('empty', "No results, please refine your input and try again");
} else {
const markdownContents = reply.message ?? new MarkdownString('', { supportThemeIcons: true, supportHtml: true, isTrusted: false });
const replyResponse = response = this._instaService.createInstance(ReplyResponse, reply, markdownContents, this._activeSession.textModelN.uri, modelAltVersionIdNow, progressEdits, request.requestId);
for (let i = progressEdits.length; i < replyResponse.allLocalEdits.length; i++) {
await this._makeChanges(replyResponse.allLocalEdits[i], undefined);
}
const a11yMessageResponse = renderMarkdownAsPlaintext(replyResponse.mdContent);
a11yResponse = a11yVerboseInlineChat
? a11yMessageResponse ? localize('editResponseMessage2', "{0}, also review proposed changes in the diff editor.", a11yMessageResponse) : localize('editResponseMessage', "Review proposed changes in the diff editor.")
: a11yMessageResponse;
}
} catch (e) {
response = new ErrorResponse(e);
a11yResponse = (<ErrorResponse>response).message;
} finally {
this._ctxHasActiveRequest.set(false);
this._zone.value.widget.updateProgress(false);
this._zone.value.widget.updateInfo('');
this._zone.value.widget.updateToolbar(true);
this._log('request took', requestClock.elapsed(), this._activeSession.provider.debugName);
this._chatAccessibilityService.acceptResponse(a11yResponse, requestId);
}
// todo@jrieken we can likely remove 'trackEdit'
const diff = await this._editorWorkerService.computeDiff(this._activeSession.textModel0.uri, this._activeSession.textModelN.uri, { computeMoves: false, maxComputationTimeMs: Number.MAX_SAFE_INTEGER, ignoreTrimWhitespace: false }, 'advanced');
this._activeSession.wholeRange.fixup(diff?.changes ?? []);
progressiveEditsCts.dispose(true);
requestCts.dispose();
msgListener.dispose();
typeListener.dispose();
if (request.live && !(response instanceof ReplyResponse)) {
this._strategy?.undoChanges(modelAltVersionIdNow);
}
this._activeSession.addExchange(new SessionExchange(this._activeSession.lastInput, response));
if (message & Message.CANCEL_SESSION) {
return State.CANCEL;
} else if (message & Message.PAUSE_SESSION) {
return State.PAUSE;
} else if (message & Message.ACCEPT_SESSION) {
return State.ACCEPT;
} else {
return State.APPLY_RESPONSE;
}
}
private async[State.APPLY_RESPONSE](): Promise<State.SHOW_RESPONSE | State.CANCEL> {
assertType(this._activeSession);
assertType(this._strategy);
const { response } = this._activeSession.lastExchange!;
if (response instanceof ReplyResponse && response.workspaceEdit) {
// this reply cannot be applied in the normal inline chat UI and needs to be handled off to workspace edit
this._bulkEditService.apply(response.workspaceEdit, { showPreview: true });
return State.CANCEL;
}
return State.SHOW_RESPONSE;
}
private async _makeChanges(edits: TextEdit[], opts: ProgressingEditsOptions | undefined) {
assertType(this._activeSession);
assertType(this._strategy);
const moreMinimalEdits = await this._editorWorkerService.computeMoreMinimalEdits(this._activeSession.textModelN.uri, edits);
this._log('edits from PROVIDER and after making them MORE MINIMAL', this._activeSession.provider.debugName, edits, moreMinimalEdits);
if (moreMinimalEdits?.length === 0) {
// nothing left to do
return;
}
const actualEdits = !opts && moreMinimalEdits ? moreMinimalEdits : edits;
const editOperations = actualEdits.map(TextEdit.asEditOperation);
try {
this._ignoreModelContentChanged = true;
this._activeSession.wholeRange.trackEdits(editOperations);
if (opts) {
await this._strategy.makeProgressiveChanges(editOperations, opts);
} else {
await this._strategy.makeChanges(editOperations);
}
this._ctxDidEdit.set(this._activeSession.hasChangedText);
} finally {
this._ignoreModelContentChanged = false;
}
}
private async[State.SHOW_RESPONSE](): Promise<State.WAIT_FOR_INPUT> {
assertType(this._activeSession);
assertType(this._strategy);
const { response } = this._activeSession.lastExchange!;
let responseTypes: InlineChatResponseTypes | undefined;
for (const { response } of this._activeSession.exchanges) {
const thisType = response instanceof ReplyResponse
? response.responseType
: undefined;
if (responseTypes === undefined) {
responseTypes = thisType;
} else if (responseTypes !== thisType) {
responseTypes = InlineChatResponseTypes.Mixed;
break;
}
}
this._ctxResponseTypes.set(responseTypes);
this._ctxDidEdit.set(this._activeSession.hasChangedText);
let newPosition: Position | undefined;
if (response instanceof EmptyResponse) {
// show status message
const status = localize('empty', "No results, please refine your input and try again");
this._zone.value.widget.updateStatus(status, { classes: ['warn'] });
return State.WAIT_FOR_INPUT;
} else if (response instanceof ErrorResponse) {
// show error
if (!response.isCancellation) {
this._zone.value.widget.updateStatus(response.message, { classes: ['error'] });
}
} else if (response instanceof ReplyResponse) {
// real response -> complex...
this._zone.value.widget.updateStatus('');
const message = { message: response.mdContent, providerId: this._activeSession.provider.debugName, requestId: response.requestId };
this._zone.value.widget.updateChatMessage(message);
//this._zone.value.widget.updateMarkdownMessage(response.mdContent);
this._activeSession.lastExpansionState = this._zone.value.widget.expansionState;
this._zone.value.widget.updateToolbar(true);
newPosition = await this._strategy.renderChanges(response);
if (this._activeSession.provider.provideFollowups) {
const followupCts = new CancellationTokenSource();
const msgListener = Event.once(this._messages.event)(() => {
followupCts.cancel();
});
const followupTask = this._activeSession.provider.provideFollowups(this._activeSession.session, response.raw, followupCts.token);
this._log('followup request started', this._activeSession.provider.debugName, this._activeSession.session, response.raw);
raceCancellation(Promise.resolve(followupTask), followupCts.token).then(followupReply => {
if (followupReply && this._activeSession) {
this._log('followup request received', this._activeSession.provider.debugName, this._activeSession.session, followupReply);
this._zone.value.widget.updateFollowUps(followupReply, followup => {
this.updateInput(followup.message);
this.acceptInput();
});
}
}).finally(() => {
msgListener.dispose();
followupCts.dispose();
});
}
}
this._showWidget(false, newPosition);
return State.WAIT_FOR_INPUT;
}
private async[State.PAUSE]() {
this._ctxDidEdit.reset();
this._ctxUserDidEdit.reset();
this._ctxLastFeedbackKind.reset();
this._ctxSupportIssueReporting.reset();
this._zone.value.hide();
// Return focus to the editor only if the current focus is within the editor widget
if (this._editor.hasWidgetFocus()) {
this._editor.focus();
}
this._strategy?.dispose();
this._strategy = undefined;
this._activeSession = undefined;
}
private async[State.ACCEPT]() {
assertType(this._activeSession);
assertType(this._strategy);
this._sessionStore.clear();
try {
await this._strategy.apply();
} catch (err) {
this._dialogService.error(localize('err.apply', "Failed to apply changes.", toErrorMessage(err)));
this._log('FAILED to apply changes');
this._log(err);
}
this._inlineChatSessionService.releaseSession(this._activeSession);
this[State.PAUSE]();
}
private async[State.CANCEL]() {
assertType(this._activeSession);
assertType(this._strategy);
this._sessionStore.clear();
const mySession = this._activeSession;
try {
await this._strategy.cancel();
} catch (err) {
this._dialogService.error(localize('err.discard', "Failed to discard changes.", toErrorMessage(err)));
this._log('FAILED to discard changes');
this._log(err);
}
this[State.PAUSE]();
this._stashedSession.clear();
if (!mySession.isUnstashed && mySession.lastExchange) {
// only stash sessions that had edits
this._stashedSession.value = this._instaService.createInstance(StashedSession, this._editor, mySession);
} else {
this._inlineChatSessionService.releaseSession(mySession);
}
}
// ---- controller API
acceptInput(): void {
this._messages.fire(Message.ACCEPT_INPUT);
}
updateInput(text: string, selectAll = true): void {
this._zone.value.widget.value = text;
if (selectAll) {
this._zone.value.widget.selectAll();
}
}
getInput(): string {
return this._zone.value.widget.value;
}
regenerate(): void {
this._messages.fire(Message.RERUN_INPUT);
}
cancelCurrentRequest(): void {
this._messages.fire(Message.CANCEL_INPUT | Message.CANCEL_REQUEST);
}
arrowOut(up: boolean): void {
if (this._zone.value.position && this._editor.hasModel()) {
const { column } = this._editor.getPosition();
const { lineNumber } = this._zone.value.position;
const newLine = up ? lineNumber : lineNumber + 1;
this._editor.setPosition({ lineNumber: newLine, column });
this._editor.focus();
}
}
focus(): void {
this._zone.value.widget.focus();
}
hasFocus(): boolean {
return this._zone.value.widget.hasFocus();
}
populateHistory(up: boolean) {
const len = InlineChatController._promptHistory.length;
if (len === 0) {
return;
}
const pos = (len + this._historyOffset + (up ? 1 : -1)) % len;
const entry = InlineChatController._promptHistory[pos];
this._zone.value.widget.value = entry;
this._zone.value.widget.selectAll();
this._historyOffset = pos;
}
viewInChat() {
if (this._activeSession?.lastExchange?.response instanceof ReplyResponse) {
this._instaService.invokeFunction(showMessageResponse, this._activeSession.lastExchange.prompt.value, this._activeSession.lastExchange.response.mdContent.value);
}
}
updateExpansionState(expand: boolean) {
if (this._activeSession) {
const expansionState = expand ? ExpansionState.EXPANDED : ExpansionState.CROPPED;
this._zone.value.widget.updateChatMessageExpansionState(expansionState);
this._activeSession.lastExpansionState = expansionState;
}
}
toggleDiff() {
this._strategy?.toggleDiff?.();
}
feedbackLast(kind: InlineChatResponseFeedbackKind) {
if (this._activeSession?.lastExchange && this._activeSession.lastExchange.response instanceof ReplyResponse) {
this._activeSession.provider.handleInlineChatResponseFeedback?.(this._activeSession.session, this._activeSession.lastExchange.response.raw, kind);
switch (kind) {
case InlineChatResponseFeedbackKind.Helpful:
this._ctxLastFeedbackKind.set('helpful');
break;
case InlineChatResponseFeedbackKind.Unhelpful:
this._ctxLastFeedbackKind.set('unhelpful');
break;
default:
break;
}
this._zone.value.widget.updateStatus('Thank you for your feedback!', { resetAfter: 1250 });
}
}
createSnapshot(): void {
if (this._activeSession && !this._activeSession.textModel0.equalsTextBuffer(this._activeSession.textModelN.getTextBuffer())) {
this._activeSession.createSnapshot();
}
}
acceptSession(): void {
if (this._activeSession?.lastExchange && this._activeSession.lastExchange.response instanceof ReplyResponse) {
this._activeSession.provider.handleInlineChatResponseFeedback?.(this._activeSession.session, this._activeSession.lastExchange.response.raw, InlineChatResponseFeedbackKind.Accepted);
}
this._messages.fire(Message.ACCEPT_SESSION);
}
async cancelSession() {
let result: string | undefined;
if (this._activeSession) {
const diff = await this._editorWorkerService.computeDiff(this._activeSession.textModel0.uri, this._activeSession.textModelN.uri, { ignoreTrimWhitespace: false, maxComputationTimeMs: 5000, computeMoves: false }, 'advanced');
result = this._activeSession.asChangedText(diff?.changes ?? []);
if (this._activeSession.lastExchange && this._activeSession.lastExchange.response instanceof ReplyResponse) {
this._activeSession.provider.handleInlineChatResponseFeedback?.(this._activeSession.session, this._activeSession.lastExchange.response.raw, InlineChatResponseFeedbackKind.Undone);
}
}
this._messages.fire(Message.CANCEL_SESSION);
return result;
}
finishExistingSession(): void {
if (this._activeSession) {
if (this._activeSession.editMode === EditMode.Preview) {
this._log('finishing existing session, using CANCEL', this._activeSession.editMode);
this.cancelSession();
} else {
this._log('finishing existing session, using APPLY', this._activeSession.editMode);
this.acceptSession();
}
}
}
unstashLastSession(): Session | undefined {
return this._stashedSession.value?.unstash();
}
}
class StashedSession {
private readonly _listener: IDisposable;
private readonly _ctxHasStashedSession: IContextKey<boolean>;
private _session: Session | undefined;
constructor(
editor: ICodeEditor,
session: Session,
@IContextKeyService contextKeyService: IContextKeyService,
@IInlineChatSessionService private readonly _sessionService: IInlineChatSessionService,
@ILogService private readonly _logService: ILogService,
) {
this._ctxHasStashedSession = CTX_INLINE_CHAT_HAS_STASHED_SESSION.bindTo(contextKeyService);
// keep session for a little bit, only release when user continues to work (type, move cursor, etc.)
this._session = session;
this._ctxHasStashedSession.set(true);
this._listener = Event.once(Event.any(editor.onDidChangeCursorSelection, editor.onDidChangeModelContent, editor.onDidChangeModel))(() => {
this._session = undefined;
this._sessionService.releaseSession(session);
this._ctxHasStashedSession.reset();
});
}
dispose() {
this._listener.dispose();
this._ctxHasStashedSession.reset();
if (this._session) {
this._sessionService.releaseSession(this._session);
}
}
unstash(): Session | undefined {
if (!this._session) {
return undefined;
}
this._listener.dispose();
const result = this._session;
result.markUnstashed();
this._session = undefined;
this._logService.debug('[IE] Unstashed session');
return result;
}
}
async function showMessageResponse(accessor: ServicesAccessor, query: string, response: string) {
const chatService = accessor.get(IChatService);
const providerId = chatService.getProviderInfos()[0]?.id;
const chatWidgetService = accessor.get(IChatWidgetService);
const widget = await chatWidgetService.revealViewForProvider(providerId);
if (widget && widget.viewModel) {
chatService.addCompleteRequest(widget.viewModel.sessionId, query, { message: response });
widget.focusLastMessage();
}
}
async function sendRequest(accessor: ServicesAccessor, query: string) {
const chatService = accessor.get(IChatService);
const widgetService = accessor.get(IChatWidgetService);
const providerId = chatService.getProviderInfos()[0]?.id;
const widget = await widgetService.revealViewForProvider(providerId);
if (!widget) {
return;
}
widget.acceptInput(query);
}
| src/vs/workbench/contrib/inlineChat/browser/inlineChatController.ts | 1 | https://github.com/microsoft/vscode/commit/48a9149e6ad2cbc0f7ebfdb2ce6143627c077d1e | [
0.005958099849522114,
0.0003869272768497467,
0.00016230683831963688,
0.00017147081962320954,
0.0008383680833503604
] |
{
"id": 3,
"code_window": [
"\n",
"\t\tassert.ok(ctrl.getWidgetPosition() === undefined);\n",
"\t});\n",
"\n",
"\ttest('wholeRange expands to whole lines, editor selection default', async function () {\n",
"\n",
"\t\teditor.setSelection(new Range(1, 1, 1, 3));\n",
"\t\tctrl = instaService.createInstance(TestController, editor);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\ttest('wholeRange does not expand to whole lines, editor selection default', async function () {\n"
],
"file_path": "src/vs/workbench/contrib/inlineChat/test/browser/inlineChatController.test.ts",
"type": "replace",
"edit_start_line_idx": 183
} | parameters:
- name: VSCODE_QUALITY
type: string
- name: VSCODE_CIBUILD
type: boolean
- name: VSCODE_RUN_UNIT_TESTS
type: boolean
- name: VSCODE_RUN_INTEGRATION_TESTS
type: boolean
- name: VSCODE_RUN_SMOKE_TESTS
type: boolean
- name: VSCODE_ARCH
type: string
steps:
- ${{ if eq(parameters.VSCODE_QUALITY, 'oss') }}:
- checkout: self
fetchDepth: 1
retryCountOnTaskFailure: 3
- task: NodeTool@0
inputs:
versionSource: fromFile
versionFilePath: .nvmrc
nodejsMirror: https://github.com/joaomoreno/node-mirror/releases/download
- ${{ if ne(parameters.VSCODE_QUALITY, 'oss') }}:
- template: ../distro/download-distro.yml
- task: AzureKeyVault@1
displayName: "Azure Key Vault: Get Secrets"
inputs:
azureSubscription: "vscode-builds-subscription"
KeyVaultName: vscode-build-secrets
SecretsFilter: "github-distro-mixin-password,ESRP-PKI,esrp-aad-username,esrp-aad-password"
- task: DownloadPipelineArtifact@2
inputs:
artifact: Compilation
path: $(Build.ArtifactStagingDirectory)
displayName: Download compilation output
- script: tar -xzf $(Build.ArtifactStagingDirectory)/compilation.tar.gz
displayName: Extract compilation output
- script: |
set -e
# Start X server
sudo apt-get update
sudo apt-get install -y pkg-config \
dbus \
xvfb \
libgtk-3-0 \
libxkbfile-dev \
libkrb5-dev \
libgbm1 \
rpm
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
# Start dbus session
sudo mkdir -p /var/run/dbus
DBUS_LAUNCH_RESULT=$(sudo dbus-daemon --config-file=/usr/share/dbus-1/system.conf --print-address)
echo "##vso[task.setvariable variable=DBUS_SESSION_BUS_ADDRESS]$DBUS_LAUNCH_RESULT"
displayName: Setup system services
- script: node build/setup-npm-registry.js $NPM_REGISTRY
condition: and(succeeded(), ne(variables['NPM_REGISTRY'], 'none'))
displayName: Setup NPM Registry
- script: mkdir -p .build && node build/azure-pipelines/common/computeNodeModulesCacheKey.js linux $VSCODE_ARCH > .build/yarnlockhash
displayName: Prepare node_modules cache key
- task: Cache@2
inputs:
key: '"node_modules" | .build/yarnlockhash'
path: .build/node_modules_cache
cacheHitVar: NODE_MODULES_RESTORED
displayName: Restore node_modules cache
- script: tar -xzf .build/node_modules_cache/cache.tgz
condition: and(succeeded(), eq(variables.NODE_MODULES_RESTORED, 'true'))
displayName: Extract node_modules cache
- script: |
set -e
npm config set registry "$NPM_REGISTRY" --location=project
# npm >v7 deprecated the `always-auth` config option, refs npm/cli@72a7eeb
# following is a workaround for yarn to send authorization header
# for GET requests to the registry.
echo "always-auth=true" >> .npmrc
yarn config set registry "$NPM_REGISTRY"
condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true'), ne(variables['NPM_REGISTRY'], 'none'))
displayName: Setup NPM & Yarn
- task: npmAuthenticate@0
inputs:
workingFile: .npmrc
condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true'), ne(variables['NPM_REGISTRY'], 'none'))
displayName: Setup NPM Authentication
- ${{ if ne(parameters.VSCODE_QUALITY, 'oss') }}:
- script: |
set -e
for i in {1..5}; do # try 5 times
yarn --cwd build --frozen-lockfile --check-files && break
if [ $i -eq 3 ]; then
echo "Yarn failed too many times" >&2
exit 1
fi
echo "Yarn failed $i, trying again..."
done
./build/azure-pipelines/linux/install.sh
env:
npm_config_arch: $(NPM_ARCH)
VSCODE_ARCH: $(VSCODE_ARCH)
NPM_REGISTRY: "$(NPM_REGISTRY)"
ELECTRON_SKIP_BINARY_DOWNLOAD: 1
PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: 1
GITHUB_TOKEN: "$(github-distro-mixin-password)"
displayName: Install dependencies (non-OSS)
condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true'))
- script: |
set -e
TRIPLE="x86_64-linux-gnu"
if [ "$VSCODE_ARCH" == "arm64" ]; then
TRIPLE="aarch64-linux-gnu"
elif [ "$VSCODE_ARCH" == "armhf" ]; then
TRIPLE="arm-rpi-linux-gnueabihf"
fi
# Get all files with .node extension from remote/node_modules folder
files=$(find remote/node_modules -name "*.node")
# Check if any file has dependency of GLIBC > 2.28 or GLIBCXX > 3.4.25
for file in $files; do
glibc_version="2.28"
glibcxx_version="3.4.25"
while IFS= read -r line; do
if [[ $line == *"GLIBC_"* ]]; then
version=$(echo "$line" | awk '{print $5}' | tr -d '()')
version=${version#*_}
if [[ $(printf "%s\n%s" "$version" "$glibc_version" | sort -V | tail -n1) == "$version" ]]; then
glibc_version=$version
fi
elif [[ $line == *"GLIBCXX_"* ]]; then
version=$(echo "$line" | awk '{print $5}' | tr -d '()')
version=${version#*_}
if [[ $(printf "%s\n%s" "$version" "$glibcxx_version" | sort -V | tail -n1) == "$version" ]]; then
glibcxx_version=$version
fi
fi
done < <("$PWD/.build/sysroots/$TRIPLE/$TRIPLE/bin/objdump" -T "$file")
if [[ "$glibc_version" != "2.28" ]]; then
echo "Error: File $file has dependency on GLIBC > 2.28"
exit 1
fi
if [[ "$glibcxx_version" != "3.4.25" ]]; then
echo "Error: File $file has dependency on GLIBCXX > 3.4.25"
exit 1
fi
done
condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true'))
displayName: Check GLIBC and GLIBCXX dependencies in remote/node_modules
- script: node build/azure-pipelines/distro/mixin-npm
condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true'))
displayName: Mixin distro node modules
- ${{ else }}:
# Ref https://github.com/microsoft/vscode/issues/189019
# for the node-gyp rebuild step
- script: |
set -e
for i in {1..5}; do # try 5 times
yarn --frozen-lockfile --check-files && break
if [ $i -eq 3 ]; then
echo "Yarn failed too many times" >&2
exit 1
fi
echo "Yarn failed $i, trying again..."
done
cd node_modules/native-keymap && npx [email protected] -y rebuild --debug
cd ../.. && ./.github/workflows/check-clean-git-state.sh
env:
npm_config_arch: $(NPM_ARCH)
ELECTRON_SKIP_BINARY_DOWNLOAD: 1
PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: 1
GITHUB_TOKEN: "$(github-distro-mixin-password)"
displayName: Install dependencies (OSS)
condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true'))
- script: |
set -e
node build/azure-pipelines/common/listNodeModules.js .build/node_modules_list.txt
mkdir -p .build/node_modules_cache
tar -czf .build/node_modules_cache/cache.tgz --files-from .build/node_modules_list.txt
condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true'))
displayName: Create node_modules archive
- ${{ if ne(parameters.VSCODE_QUALITY, 'oss') }}:
- script: node build/azure-pipelines/distro/mixin-quality
displayName: Mixin distro quality
- template: ../common/install-builtin-extensions.yml
- ${{ if ne(parameters.VSCODE_QUALITY, 'oss') }}:
- script: |
set -e
yarn gulp vscode-linux-$(VSCODE_ARCH)-min-ci
ARCHIVE_PATH=".build/linux/client/code-${{ parameters.VSCODE_QUALITY }}-$(VSCODE_ARCH)-$(date +%s).tar.gz"
mkdir -p $(dirname $ARCHIVE_PATH)
echo "##vso[task.setvariable variable=CLIENT_PATH]$ARCHIVE_PATH"
env:
GITHUB_TOKEN: "$(github-distro-mixin-password)"
displayName: Build client
- ${{ if ne(parameters.VSCODE_CIBUILD, true) }}:
- task: DownloadPipelineArtifact@2
inputs:
artifact: $(ARTIFACT_PREFIX)vscode_cli_linux_$(VSCODE_ARCH)_cli
patterns: "**"
path: $(Build.ArtifactStagingDirectory)/cli
displayName: Download VS Code CLI
- script: |
set -e
tar -xzvf $(Build.ArtifactStagingDirectory)/cli/*.tar.gz -C $(Build.ArtifactStagingDirectory)/cli
CLI_APP_NAME=$(node -p "require(\"$(agent.builddirectory)/VSCode-linux-$(VSCODE_ARCH)/resources/app/product.json\").tunnelApplicationName")
APP_NAME=$(node -p "require(\"$(agent.builddirectory)/VSCode-linux-$(VSCODE_ARCH)/resources/app/product.json\").applicationName")
mv $(Build.ArtifactStagingDirectory)/cli/$APP_NAME $(agent.builddirectory)/VSCode-linux-$(VSCODE_ARCH)/bin/$CLI_APP_NAME
displayName: Mix in CLI
- script: |
set -e
tar -czf $CLIENT_PATH -C .. VSCode-linux-$(VSCODE_ARCH)
env:
GITHUB_TOKEN: "$(github-distro-mixin-password)"
displayName: Archive client
- script: |
set -e
yarn gulp vscode-reh-linux-$(VSCODE_ARCH)-min-ci
mv ../vscode-reh-linux-$(VSCODE_ARCH) ../vscode-server-linux-$(VSCODE_ARCH) # TODO@joaomoreno
ARCHIVE_PATH=".build/linux/server/vscode-server-linux-$(VSCODE_ARCH).tar.gz"
mkdir -p $(dirname $ARCHIVE_PATH)
tar --owner=0 --group=0 -czf $ARCHIVE_PATH -C .. vscode-server-linux-$(VSCODE_ARCH)
echo "##vso[task.setvariable variable=SERVER_PATH]$ARCHIVE_PATH"
env:
GITHUB_TOKEN: "$(github-distro-mixin-password)"
displayName: Build server
- script: |
set -e
yarn gulp vscode-reh-web-linux-$(VSCODE_ARCH)-min-ci
mv ../vscode-reh-web-linux-$(VSCODE_ARCH) ../vscode-server-linux-$(VSCODE_ARCH)-web # TODO@joaomoreno
ARCHIVE_PATH=".build/linux/web/vscode-server-linux-$(VSCODE_ARCH)-web.tar.gz"
mkdir -p $(dirname $ARCHIVE_PATH)
tar --owner=0 --group=0 -czf $ARCHIVE_PATH -C .. vscode-server-linux-$(VSCODE_ARCH)-web
echo "##vso[task.setvariable variable=WEB_PATH]$ARCHIVE_PATH"
env:
GITHUB_TOKEN: "$(github-distro-mixin-password)"
displayName: Build server (web)
- ${{ else }}:
- script: yarn gulp "transpile-client-swc" "transpile-extensions"
env:
GITHUB_TOKEN: "$(github-distro-mixin-password)"
displayName: Transpile client and extensions
- ${{ if or(eq(parameters.VSCODE_RUN_UNIT_TESTS, true), eq(parameters.VSCODE_RUN_INTEGRATION_TESTS, true), eq(parameters.VSCODE_RUN_SMOKE_TESTS, true)) }}:
- template: product-build-linux-test.yml
parameters:
VSCODE_QUALITY: ${{ parameters.VSCODE_QUALITY }}
VSCODE_RUN_UNIT_TESTS: ${{ parameters.VSCODE_RUN_UNIT_TESTS }}
VSCODE_RUN_INTEGRATION_TESTS: ${{ parameters.VSCODE_RUN_INTEGRATION_TESTS }}
VSCODE_RUN_SMOKE_TESTS: ${{ parameters.VSCODE_RUN_SMOKE_TESTS }}
- ${{ if and(ne(parameters.VSCODE_CIBUILD, true), ne(parameters.VSCODE_QUALITY, 'oss')) }}:
- script: |
set -e
yarn gulp "vscode-linux-$(VSCODE_ARCH)-prepare-deb"
displayName: Prepare deb package
- script: |
set -e
yarn gulp "vscode-linux-$(VSCODE_ARCH)-build-deb"
echo "##vso[task.setvariable variable=DEB_PATH]$(ls .build/linux/deb/*/deb/*.deb)"
displayName: Build deb package
- script: |
set -e
yarn gulp "vscode-linux-$(VSCODE_ARCH)-prepare-rpm"
displayName: Prepare rpm package
- script: |
set -e
yarn gulp "vscode-linux-$(VSCODE_ARCH)-build-rpm"
echo "##vso[task.setvariable variable=RPM_PATH]$(ls .build/linux/rpm/*/*.rpm)"
displayName: Build rpm package
- script: |
set -e
yarn gulp "vscode-linux-$(VSCODE_ARCH)-prepare-snap"
ARCHIVE_PATH=".build/linux/snap-tarball/snap-$(VSCODE_ARCH).tar.gz"
mkdir -p $(dirname $ARCHIVE_PATH)
tar -czf $ARCHIVE_PATH -C .build/linux snap
echo "##vso[task.setvariable variable=SNAP_PATH]$ARCHIVE_PATH"
displayName: Prepare snap package
- task: UseDotNet@2
inputs:
version: 6.x
- task: EsrpClientTool@1
continueOnError: true
displayName: Download ESRPClient
- script: node build/azure-pipelines/common/sign $(Agent.ToolsDirectory)/esrpclient/*/*/net6.0/esrpcli.dll sign-pgp $(ESRP-PKI) $(esrp-aad-username) $(esrp-aad-password) .build/linux/deb '*.deb'
displayName: Codesign deb
- script: node build/azure-pipelines/common/sign $(Agent.ToolsDirectory)/esrpclient/*/*/net6.0/esrpcli.dll sign-pgp $(ESRP-PKI) $(esrp-aad-username) $(esrp-aad-password) .build/linux/rpm '*.rpm'
displayName: Codesign rpm
- script: echo "##vso[task.setvariable variable=ARTIFACT_PREFIX]attempt$(System.JobAttempt)_"
condition: and(succeededOrFailed(), notIn(variables['Agent.JobStatus'], 'Succeeded', 'SucceededWithIssues'))
displayName: Generate artifact prefix
- task: AzureArtifacts.manifest-generator-task.manifest-generator-task.ManifestGeneratorTask@0
displayName: Generate SBOM (client)
inputs:
BuildDropPath: $(agent.builddirectory)/VSCode-linux-$(VSCODE_ARCH)
PackageName: Visual Studio Code
- task: AzureArtifacts.manifest-generator-task.manifest-generator-task.ManifestGeneratorTask@0
displayName: Generate SBOM (server)
inputs:
BuildComponentPath: $(Build.SourcesDirectory)/remote
BuildDropPath: $(agent.builddirectory)/vscode-server-linux-$(VSCODE_ARCH)
PackageName: Visual Studio Code Server
- publish: $(agent.builddirectory)/VSCode-linux-$(VSCODE_ARCH)/_manifest
displayName: Publish SBOM (client)
artifact: $(ARTIFACT_PREFIX)sbom_vscode_client_linux_$(VSCODE_ARCH)
- publish: $(agent.builddirectory)/vscode-server-linux-$(VSCODE_ARCH)/_manifest
displayName: Publish SBOM (server)
artifact: $(ARTIFACT_PREFIX)sbom_vscode_server_linux_$(VSCODE_ARCH)
- publish: $(CLIENT_PATH)
artifact: $(ARTIFACT_PREFIX)vscode_client_linux_$(VSCODE_ARCH)_archive-unsigned
condition: and(succeededOrFailed(), ne(variables['CLIENT_PATH'], ''))
displayName: Publish client archive
- publish: $(SERVER_PATH)
artifact: $(ARTIFACT_PREFIX)vscode_server_linux_$(VSCODE_ARCH)_archive-unsigned
condition: and(succeededOrFailed(), ne(variables['SERVER_PATH'], ''))
displayName: Publish server archive
- publish: $(WEB_PATH)
artifact: $(ARTIFACT_PREFIX)vscode_web_linux_$(VSCODE_ARCH)_archive-unsigned
condition: and(succeededOrFailed(), ne(variables['WEB_PATH'], ''))
displayName: Publish web server archive
- publish: $(DEB_PATH)
artifact: $(ARTIFACT_PREFIX)vscode_client_linux_$(VSCODE_ARCH)_deb-package
condition: and(succeededOrFailed(), ne(variables['DEB_PATH'], ''))
displayName: Publish deb package
- publish: $(RPM_PATH)
artifact: $(ARTIFACT_PREFIX)vscode_client_linux_$(VSCODE_ARCH)_rpm-package
condition: and(succeededOrFailed(), ne(variables['RPM_PATH'], ''))
displayName: Publish rpm package
- publish: $(SNAP_PATH)
artifact: $(ARTIFACT_PREFIX)snap-$(VSCODE_ARCH)
condition: and(succeededOrFailed(), ne(variables['SNAP_PATH'], ''))
displayName: Publish snap pre-package
| build/azure-pipelines/linux/product-build-linux.yml | 0 | https://github.com/microsoft/vscode/commit/48a9149e6ad2cbc0f7ebfdb2ce6143627c077d1e | [
0.00017787024262361228,
0.0001734889519866556,
0.0001656210224609822,
0.0001738250139169395,
0.0000022576682567887474
] |
{
"id": 3,
"code_window": [
"\n",
"\t\tassert.ok(ctrl.getWidgetPosition() === undefined);\n",
"\t});\n",
"\n",
"\ttest('wholeRange expands to whole lines, editor selection default', async function () {\n",
"\n",
"\t\teditor.setSelection(new Range(1, 1, 1, 3));\n",
"\t\tctrl = instaService.createInstance(TestController, editor);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\ttest('wholeRange does not expand to whole lines, editor selection default', async function () {\n"
],
"file_path": "src/vs/workbench/contrib/inlineChat/test/browser/inlineChatController.test.ts",
"type": "replace",
"edit_start_line_idx": 183
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as vscode from 'vscode';
import { isJsConfigOrTsConfigFileName } from '../configuration/languageDescription';
import { isSupportedLanguageMode } from '../configuration/languageIds';
import { Disposable } from '../utils/dispose';
/**
* Tracks the active JS/TS editor.
*
* This tries to handle the case where the user focuses in the output view / debug console.
* When this happens, we want to treat the last real focused editor as the active editor,
* instead of using `vscode.window.activeTextEditor`
*/
export class ActiveJsTsEditorTracker extends Disposable {
private _activeJsTsEditor: vscode.TextEditor | undefined;
private readonly _onDidChangeActiveJsTsEditor = this._register(new vscode.EventEmitter<vscode.TextEditor | undefined>());
public readonly onDidChangeActiveJsTsEditor = this._onDidChangeActiveJsTsEditor.event;
public constructor() {
super();
vscode.window.onDidChangeActiveTextEditor(this.onDidChangeActiveTextEditor, this, this._disposables);
vscode.window.onDidChangeVisibleTextEditors(() => {
// Make sure the active editor is still in the visible set.
// This can happen if the output view is focused and the last active TS file is closed
if (this._activeJsTsEditor) {
if (!vscode.window.visibleTextEditors.some(visibleEditor => visibleEditor === this._activeJsTsEditor)) {
this.onDidChangeActiveTextEditor(undefined);
}
}
}, this, this._disposables);
this.onDidChangeActiveTextEditor(vscode.window.activeTextEditor);
}
public get activeJsTsEditor(): vscode.TextEditor | undefined {
return this._activeJsTsEditor;
}
private onDidChangeActiveTextEditor(editor: vscode.TextEditor | undefined): any {
if (editor === this._activeJsTsEditor) {
return;
}
if (editor && !editor.viewColumn) {
// viewColumn is undefined for the debug/output panel, but we still want
// to show the version info for the previous editor
return;
}
if (editor && this.isManagedFile(editor)) {
this._activeJsTsEditor = editor;
} else {
this._activeJsTsEditor = undefined;
}
this._onDidChangeActiveJsTsEditor.fire(this._activeJsTsEditor);
}
private isManagedFile(editor: vscode.TextEditor): boolean {
return this.isManagedScriptFile(editor) || this.isManagedConfigFile(editor);
}
private isManagedScriptFile(editor: vscode.TextEditor): boolean {
return isSupportedLanguageMode(editor.document);
}
private isManagedConfigFile(editor: vscode.TextEditor): boolean {
return isJsConfigOrTsConfigFileName(editor.document.fileName);
}
}
| extensions/typescript-language-features/src/ui/activeJsTsEditorTracker.ts | 0 | https://github.com/microsoft/vscode/commit/48a9149e6ad2cbc0f7ebfdb2ce6143627c077d1e | [
0.00022469856776297092,
0.00017961458070203662,
0.00016613997286185622,
0.00017041797400452197,
0.00001956945015990641
] |
{
"id": 3,
"code_window": [
"\n",
"\t\tassert.ok(ctrl.getWidgetPosition() === undefined);\n",
"\t});\n",
"\n",
"\ttest('wholeRange expands to whole lines, editor selection default', async function () {\n",
"\n",
"\t\teditor.setSelection(new Range(1, 1, 1, 3));\n",
"\t\tctrl = instaService.createInstance(TestController, editor);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\ttest('wholeRange does not expand to whole lines, editor selection default', async function () {\n"
],
"file_path": "src/vs/workbench/contrib/inlineChat/test/browser/inlineChatController.test.ts",
"type": "replace",
"edit_start_line_idx": 183
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as DOM from 'vs/base/browser/dom';
import { ToolBar } from 'vs/base/browser/ui/toolbar/toolbar';
import { IAction } from 'vs/base/common/actions';
import { disposableTimeout } from 'vs/base/common/async';
import { Emitter, Event } from 'vs/base/common/event';
import { MarshalledId } from 'vs/base/common/marshallingIds';
import { ServicesAccessor } from 'vs/editor/browser/editorExtensions';
import { createActionViewItem, createAndFillInActionBarActions, MenuEntryActionViewItem } from 'vs/platform/actions/browser/menuEntryActionViewItem';
import { IMenu, IMenuService, MenuId, MenuItemAction } from 'vs/platform/actions/common/actions';
import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { IContextMenuService } from 'vs/platform/contextview/browser/contextView';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { INotebookCellActionContext } from 'vs/workbench/contrib/notebook/browser/controller/coreActions';
import { ICellViewModel, INotebookEditorDelegate } from 'vs/workbench/contrib/notebook/browser/notebookBrowser';
import { CodiconActionViewItem } from 'vs/workbench/contrib/notebook/browser/view/cellParts/cellActionView';
import { CellOverlayPart } from 'vs/workbench/contrib/notebook/browser/view/cellPart';
import { registerCellToolbarStickyScroll } from 'vs/workbench/contrib/notebook/browser/view/cellParts/cellToolbarStickyScroll';
import { WorkbenchToolBar } from 'vs/platform/actions/browser/toolbar';
export class BetweenCellToolbar extends CellOverlayPart {
private _betweenCellToolbar: ToolBar | undefined;
constructor(
private readonly _notebookEditor: INotebookEditorDelegate,
_titleToolbarContainer: HTMLElement,
private readonly _bottomCellToolbarContainer: HTMLElement,
@IInstantiationService private readonly instantiationService: IInstantiationService,
@IContextMenuService private readonly contextMenuService: IContextMenuService,
@IContextKeyService private readonly contextKeyService: IContextKeyService,
@IMenuService private readonly menuService: IMenuService
) {
super();
}
private _initialize(): ToolBar {
if (this._betweenCellToolbar) {
return this._betweenCellToolbar;
}
const betweenCellToolbar = this._register(new ToolBar(this._bottomCellToolbarContainer, this.contextMenuService, {
actionViewItemProvider: action => {
if (action instanceof MenuItemAction) {
if (this._notebookEditor.notebookOptions.getDisplayOptions().insertToolbarAlignment === 'center') {
return this.instantiationService.createInstance(CodiconActionViewItem, action, undefined);
} else {
return this.instantiationService.createInstance(MenuEntryActionViewItem, action, undefined);
}
}
return undefined;
}
}));
this._betweenCellToolbar = betweenCellToolbar;
const menu = this._register(this.menuService.createMenu(this._notebookEditor.creationOptions.menuIds.cellInsertToolbar, this.contextKeyService));
const updateActions = () => {
const actions = getCellToolbarActions(menu);
betweenCellToolbar.setActions(actions.primary, actions.secondary);
};
this._register(menu.onDidChange(() => updateActions()));
this._register(this._notebookEditor.notebookOptions.onDidChangeOptions((e) => {
if (e.insertToolbarAlignment) {
updateActions();
}
}));
updateActions();
return betweenCellToolbar;
}
override didRenderCell(element: ICellViewModel): void {
const betweenCellToolbar = this._initialize();
betweenCellToolbar.context = <INotebookCellActionContext>{
ui: true,
cell: element,
notebookEditor: this._notebookEditor,
$mid: MarshalledId.NotebookCellActionContext
};
this.updateInternalLayoutNow(element);
}
override updateInternalLayoutNow(element: ICellViewModel) {
const bottomToolbarOffset = element.layoutInfo.bottomToolbarOffset;
this._bottomCellToolbarContainer.style.transform = `translateY(${bottomToolbarOffset}px)`;
}
}
export interface ICssClassDelegate {
toggle: (className: string, force?: boolean) => void;
}
interface CellTitleToolbarModel {
titleMenu: IMenu;
actions: { primary: IAction[]; secondary: IAction[] };
deleteMenu: IMenu;
deleteActions: { primary: IAction[]; secondary: IAction[] };
}
interface CellTitleToolbarView {
toolbar: ToolBar;
deleteToolbar: ToolBar;
}
export class CellTitleToolbarPart extends CellOverlayPart {
private _model: CellTitleToolbarModel | undefined;
private _view: CellTitleToolbarView | undefined;
private readonly _onDidUpdateActions: Emitter<void> = this._register(new Emitter<void>());
readonly onDidUpdateActions: Event<void> = this._onDidUpdateActions.event;
get hasActions(): boolean {
if (!this._model) {
return false;
}
return this._model.actions.primary.length
+ this._model.actions.secondary.length
+ this._model.deleteActions.primary.length
+ this._model.deleteActions.secondary.length
> 0;
}
constructor(
private readonly toolbarContainer: HTMLElement,
private readonly _rootClassDelegate: ICssClassDelegate,
private readonly toolbarId: MenuId,
private readonly deleteToolbarId: MenuId,
private readonly _notebookEditor: INotebookEditorDelegate,
@IContextKeyService private readonly contextKeyService: IContextKeyService,
@IMenuService private readonly menuService: IMenuService,
@IInstantiationService private readonly instantiationService: IInstantiationService,
) {
super();
}
private _initializeModel(): CellTitleToolbarModel {
if (this._model) {
return this._model;
}
const titleMenu = this._register(this.menuService.createMenu(this.toolbarId, this.contextKeyService));
const deleteMenu = this._register(this.menuService.createMenu(this.deleteToolbarId, this.contextKeyService));
const actions = getCellToolbarActions(titleMenu);
const deleteActions = getCellToolbarActions(deleteMenu);
this._model = {
titleMenu,
actions,
deleteMenu,
deleteActions
};
return this._model;
}
private _initialize(model: CellTitleToolbarModel, element: ICellViewModel): CellTitleToolbarView {
if (this._view) {
return this._view;
}
const toolbar = this._register(this.instantiationService.createInstance(WorkbenchToolBar, this.toolbarContainer, {
actionViewItemProvider: action => {
return createActionViewItem(this.instantiationService, action);
},
renderDropdownAsChildElement: true
}));
const deleteToolbar = this._register(this.instantiationService.invokeFunction(accessor => createDeleteToolbar(accessor, this.toolbarContainer, 'cell-delete-toolbar')));
if (model.deleteActions.primary.length !== 0 || model.deleteActions.secondary.length !== 0) {
deleteToolbar.setActions(model.deleteActions.primary, model.deleteActions.secondary);
}
this.setupChangeListeners(toolbar, model.titleMenu, model.actions);
this.setupChangeListeners(deleteToolbar, model.deleteMenu, model.deleteActions);
this._view = {
toolbar,
deleteToolbar
};
return this._view;
}
override prepareRenderCell(element: ICellViewModel): void {
this._initializeModel();
}
override didRenderCell(element: ICellViewModel): void {
const model = this._initializeModel();
const view = this._initialize(model, element);
this.cellDisposables.add(registerCellToolbarStickyScroll(this._notebookEditor, element, this.toolbarContainer, { extraOffset: 4, min: -14 }));
this.updateContext(view, <INotebookCellActionContext>{
ui: true,
cell: element,
notebookEditor: this._notebookEditor,
$mid: MarshalledId.NotebookCellActionContext
});
}
private updateContext(view: CellTitleToolbarView, toolbarContext: INotebookCellActionContext) {
view.toolbar.context = toolbarContext;
view.deleteToolbar.context = toolbarContext;
}
private setupChangeListeners(toolbar: ToolBar, menu: IMenu, initActions: { primary: IAction[]; secondary: IAction[] }): void {
// #103926
let dropdownIsVisible = false;
let deferredUpdate: (() => void) | undefined;
this.updateActions(toolbar, initActions);
this._register(menu.onDidChange(() => {
if (dropdownIsVisible) {
const actions = getCellToolbarActions(menu);
deferredUpdate = () => this.updateActions(toolbar, actions);
return;
}
const actions = getCellToolbarActions(menu);
this.updateActions(toolbar, actions);
}));
this._rootClassDelegate.toggle('cell-toolbar-dropdown-active', false);
this._register(toolbar.onDidChangeDropdownVisibility(visible => {
dropdownIsVisible = visible;
this._rootClassDelegate.toggle('cell-toolbar-dropdown-active', visible);
if (deferredUpdate && !visible) {
disposableTimeout(() => {
deferredUpdate?.();
}, 0, this._store);
deferredUpdate = undefined;
}
}));
}
private updateActions(toolbar: ToolBar, actions: { primary: IAction[]; secondary: IAction[] }) {
const hadFocus = DOM.isAncestorOfActiveElement(toolbar.getElement());
toolbar.setActions(actions.primary, actions.secondary);
if (hadFocus) {
this._notebookEditor.focus();
}
if (actions.primary.length || actions.secondary.length) {
this._rootClassDelegate.toggle('cell-has-toolbar-actions', true);
this._onDidUpdateActions.fire();
} else {
this._rootClassDelegate.toggle('cell-has-toolbar-actions', false);
this._onDidUpdateActions.fire();
}
}
}
function getCellToolbarActions(menu: IMenu): { primary: IAction[]; secondary: IAction[] } {
const primary: IAction[] = [];
const secondary: IAction[] = [];
const result = { primary, secondary };
createAndFillInActionBarActions(menu, { shouldForwardArgs: true }, result, g => /^inline/.test(g));
return result;
}
function createDeleteToolbar(accessor: ServicesAccessor, container: HTMLElement, elementClass?: string): ToolBar {
const contextMenuService = accessor.get(IContextMenuService);
const keybindingService = accessor.get(IKeybindingService);
const instantiationService = accessor.get(IInstantiationService);
const toolbar = new ToolBar(container, contextMenuService, {
getKeyBinding: action => keybindingService.lookupKeybinding(action.id),
actionViewItemProvider: action => {
return createActionViewItem(instantiationService, action);
},
renderDropdownAsChildElement: true
});
if (elementClass) {
toolbar.getElement().classList.add(elementClass);
}
return toolbar;
}
| src/vs/workbench/contrib/notebook/browser/view/cellParts/cellToolbars.ts | 0 | https://github.com/microsoft/vscode/commit/48a9149e6ad2cbc0f7ebfdb2ce6143627c077d1e | [
0.0001756614656187594,
0.00017070950707420707,
0.0001628697500564158,
0.00017090339679270983,
0.0000030329297260323074
] |
{
"id": 4,
"code_window": [
"\t\tctrl.run({});\n",
"\t\tawait Event.toPromise(Event.filter(ctrl.onDidChangeState, e => e === State.WAIT_FOR_INPUT));\n",
"\n",
"\t\tconst session = inlineChatSessionService.getSession(editor, editor.getModel()!.uri);\n",
"\t\tassert.ok(session);\n",
"\t\tassert.deepStrictEqual(session.wholeRange.value, new Range(1, 1, 1, 6));\n",
"\n",
"\t\tawait ctrl.cancelSession();\n",
"\t\td.dispose();\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tassert.deepStrictEqual(session.wholeRange.value, new Range(1, 1, 1, 3));\n"
],
"file_path": "src/vs/workbench/contrib/inlineChat/test/browser/inlineChatController.test.ts",
"type": "replace",
"edit_start_line_idx": 206
} | /*---------------------------------------------------------------------------------------------
* 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.9985198378562927,
0.17256183922290802,
0.0001632347994018346,
0.0027403917629271746,
0.35761794447898865
] |
{
"id": 4,
"code_window": [
"\t\tctrl.run({});\n",
"\t\tawait Event.toPromise(Event.filter(ctrl.onDidChangeState, e => e === State.WAIT_FOR_INPUT));\n",
"\n",
"\t\tconst session = inlineChatSessionService.getSession(editor, editor.getModel()!.uri);\n",
"\t\tassert.ok(session);\n",
"\t\tassert.deepStrictEqual(session.wholeRange.value, new Range(1, 1, 1, 6));\n",
"\n",
"\t\tawait ctrl.cancelSession();\n",
"\t\td.dispose();\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tassert.deepStrictEqual(session.wholeRange.value, new Range(1, 1, 1, 3));\n"
],
"file_path": "src/vs/workbench/contrib/inlineChat/test/browser/inlineChatController.test.ts",
"type": "replace",
"edit_start_line_idx": 206
} | /*---------------------------------------------------------------------------------------------
* 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 { onUnexpectedError } from 'vs/base/common/errors';
import { Selection } from 'vs/editor/common/core/selection';
import { EndOfLineSequence, ICursorStateComputer, IValidEditOperation, ITextModel } from 'vs/editor/common/model';
import { TextModel } from 'vs/editor/common/model/textModel';
import { IUndoRedoService, IResourceUndoRedoElement, UndoRedoElementType, IWorkspaceUndoRedoElement, UndoRedoGroup } from 'vs/platform/undoRedo/common/undoRedo';
import { URI } from 'vs/base/common/uri';
import { TextChange, compressConsecutiveTextChanges } from 'vs/editor/common/core/textChange';
import * as buffer from 'vs/base/common/buffer';
import { IDisposable } from 'vs/base/common/lifecycle';
import { basename } from 'vs/base/common/resources';
import { ISingleEditOperation } from 'vs/editor/common/core/editOperation';
function uriGetComparisonKey(resource: URI): string {
return resource.toString();
}
export class SingleModelEditStackData {
public static create(model: ITextModel, beforeCursorState: Selection[] | null): SingleModelEditStackData {
const alternativeVersionId = model.getAlternativeVersionId();
const eol = getModelEOL(model);
return new SingleModelEditStackData(
alternativeVersionId,
alternativeVersionId,
eol,
eol,
beforeCursorState,
beforeCursorState,
[]
);
}
constructor(
public readonly beforeVersionId: number,
public afterVersionId: number,
public readonly beforeEOL: EndOfLineSequence,
public afterEOL: EndOfLineSequence,
public readonly beforeCursorState: Selection[] | null,
public afterCursorState: Selection[] | null,
public changes: TextChange[]
) { }
public append(model: ITextModel, textChanges: TextChange[], afterEOL: EndOfLineSequence, afterVersionId: number, afterCursorState: Selection[] | null): void {
if (textChanges.length > 0) {
this.changes = compressConsecutiveTextChanges(this.changes, textChanges);
}
this.afterEOL = afterEOL;
this.afterVersionId = afterVersionId;
this.afterCursorState = afterCursorState;
}
private static _writeSelectionsSize(selections: Selection[] | null): number {
return 4 + 4 * 4 * (selections ? selections.length : 0);
}
private static _writeSelections(b: Uint8Array, selections: Selection[] | null, offset: number): number {
buffer.writeUInt32BE(b, (selections ? selections.length : 0), offset); offset += 4;
if (selections) {
for (const selection of selections) {
buffer.writeUInt32BE(b, selection.selectionStartLineNumber, offset); offset += 4;
buffer.writeUInt32BE(b, selection.selectionStartColumn, offset); offset += 4;
buffer.writeUInt32BE(b, selection.positionLineNumber, offset); offset += 4;
buffer.writeUInt32BE(b, selection.positionColumn, offset); offset += 4;
}
}
return offset;
}
private static _readSelections(b: Uint8Array, offset: number, dest: Selection[]): number {
const count = buffer.readUInt32BE(b, offset); offset += 4;
for (let i = 0; i < count; i++) {
const selectionStartLineNumber = buffer.readUInt32BE(b, offset); offset += 4;
const selectionStartColumn = buffer.readUInt32BE(b, offset); offset += 4;
const positionLineNumber = buffer.readUInt32BE(b, offset); offset += 4;
const positionColumn = buffer.readUInt32BE(b, offset); offset += 4;
dest.push(new Selection(selectionStartLineNumber, selectionStartColumn, positionLineNumber, positionColumn));
}
return offset;
}
public serialize(): ArrayBuffer {
let necessarySize = (
+ 4 // beforeVersionId
+ 4 // afterVersionId
+ 1 // beforeEOL
+ 1 // afterEOL
+ SingleModelEditStackData._writeSelectionsSize(this.beforeCursorState)
+ SingleModelEditStackData._writeSelectionsSize(this.afterCursorState)
+ 4 // change count
);
for (const change of this.changes) {
necessarySize += change.writeSize();
}
const b = new Uint8Array(necessarySize);
let offset = 0;
buffer.writeUInt32BE(b, this.beforeVersionId, offset); offset += 4;
buffer.writeUInt32BE(b, this.afterVersionId, offset); offset += 4;
buffer.writeUInt8(b, this.beforeEOL, offset); offset += 1;
buffer.writeUInt8(b, this.afterEOL, offset); offset += 1;
offset = SingleModelEditStackData._writeSelections(b, this.beforeCursorState, offset);
offset = SingleModelEditStackData._writeSelections(b, this.afterCursorState, offset);
buffer.writeUInt32BE(b, this.changes.length, offset); offset += 4;
for (const change of this.changes) {
offset = change.write(b, offset);
}
return b.buffer;
}
public static deserialize(source: ArrayBuffer): SingleModelEditStackData {
const b = new Uint8Array(source);
let offset = 0;
const beforeVersionId = buffer.readUInt32BE(b, offset); offset += 4;
const afterVersionId = buffer.readUInt32BE(b, offset); offset += 4;
const beforeEOL = buffer.readUInt8(b, offset); offset += 1;
const afterEOL = buffer.readUInt8(b, offset); offset += 1;
const beforeCursorState: Selection[] = [];
offset = SingleModelEditStackData._readSelections(b, offset, beforeCursorState);
const afterCursorState: Selection[] = [];
offset = SingleModelEditStackData._readSelections(b, offset, afterCursorState);
const changeCount = buffer.readUInt32BE(b, offset); offset += 4;
const changes: TextChange[] = [];
for (let i = 0; i < changeCount; i++) {
offset = TextChange.read(b, offset, changes);
}
return new SingleModelEditStackData(
beforeVersionId,
afterVersionId,
beforeEOL,
afterEOL,
beforeCursorState,
afterCursorState,
changes
);
}
}
export interface IUndoRedoDelegate {
prepareUndoRedo(element: MultiModelEditStackElement): Promise<IDisposable> | IDisposable | void;
}
export class SingleModelEditStackElement implements IResourceUndoRedoElement {
public model: ITextModel | URI;
private _data: SingleModelEditStackData | ArrayBuffer;
public get type(): UndoRedoElementType.Resource {
return UndoRedoElementType.Resource;
}
public get resource(): URI {
if (URI.isUri(this.model)) {
return this.model;
}
return this.model.uri;
}
constructor(
public readonly label: string,
public readonly code: string,
model: ITextModel,
beforeCursorState: Selection[] | null
) {
this.model = model;
this._data = SingleModelEditStackData.create(model, beforeCursorState);
}
public toString(): string {
const data = (this._data instanceof SingleModelEditStackData ? this._data : SingleModelEditStackData.deserialize(this._data));
return data.changes.map(change => change.toString()).join(', ');
}
public matchesResource(resource: URI): boolean {
const uri = (URI.isUri(this.model) ? this.model : this.model.uri);
return (uri.toString() === resource.toString());
}
public setModel(model: ITextModel | URI): void {
this.model = model;
}
public canAppend(model: ITextModel): boolean {
return (this.model === model && this._data instanceof SingleModelEditStackData);
}
public append(model: ITextModel, textChanges: TextChange[], afterEOL: EndOfLineSequence, afterVersionId: number, afterCursorState: Selection[] | null): void {
if (this._data instanceof SingleModelEditStackData) {
this._data.append(model, textChanges, afterEOL, afterVersionId, afterCursorState);
}
}
public close(): void {
if (this._data instanceof SingleModelEditStackData) {
this._data = this._data.serialize();
}
}
public open(): void {
if (!(this._data instanceof SingleModelEditStackData)) {
this._data = SingleModelEditStackData.deserialize(this._data);
}
}
public undo(): void {
if (URI.isUri(this.model)) {
// don't have a model
throw new Error(`Invalid SingleModelEditStackElement`);
}
if (this._data instanceof SingleModelEditStackData) {
this._data = this._data.serialize();
}
const data = SingleModelEditStackData.deserialize(this._data);
this.model._applyUndo(data.changes, data.beforeEOL, data.beforeVersionId, data.beforeCursorState);
}
public redo(): void {
if (URI.isUri(this.model)) {
// don't have a model
throw new Error(`Invalid SingleModelEditStackElement`);
}
if (this._data instanceof SingleModelEditStackData) {
this._data = this._data.serialize();
}
const data = SingleModelEditStackData.deserialize(this._data);
this.model._applyRedo(data.changes, data.afterEOL, data.afterVersionId, data.afterCursorState);
}
public heapSize(): number {
if (this._data instanceof SingleModelEditStackData) {
this._data = this._data.serialize();
}
return this._data.byteLength + 168/*heap overhead*/;
}
}
export class MultiModelEditStackElement implements IWorkspaceUndoRedoElement {
public readonly type = UndoRedoElementType.Workspace;
private _isOpen: boolean;
private readonly _editStackElementsArr: SingleModelEditStackElement[];
private readonly _editStackElementsMap: Map<string, SingleModelEditStackElement>;
private _delegate: IUndoRedoDelegate | null;
public get resources(): readonly URI[] {
return this._editStackElementsArr.map(editStackElement => editStackElement.resource);
}
constructor(
public readonly label: string,
public readonly code: string,
editStackElements: SingleModelEditStackElement[]
) {
this._isOpen = true;
this._editStackElementsArr = editStackElements.slice(0);
this._editStackElementsMap = new Map<string, SingleModelEditStackElement>();
for (const editStackElement of this._editStackElementsArr) {
const key = uriGetComparisonKey(editStackElement.resource);
this._editStackElementsMap.set(key, editStackElement);
}
this._delegate = null;
}
public setDelegate(delegate: IUndoRedoDelegate): void {
this._delegate = delegate;
}
public prepareUndoRedo(): Promise<IDisposable> | IDisposable | void {
if (this._delegate) {
return this._delegate.prepareUndoRedo(this);
}
}
public getMissingModels(): URI[] {
const result: URI[] = [];
for (const editStackElement of this._editStackElementsArr) {
if (URI.isUri(editStackElement.model)) {
result.push(editStackElement.model);
}
}
return result;
}
public matchesResource(resource: URI): boolean {
const key = uriGetComparisonKey(resource);
return (this._editStackElementsMap.has(key));
}
public setModel(model: ITextModel | URI): void {
const key = uriGetComparisonKey(URI.isUri(model) ? model : model.uri);
if (this._editStackElementsMap.has(key)) {
this._editStackElementsMap.get(key)!.setModel(model);
}
}
public canAppend(model: ITextModel): boolean {
if (!this._isOpen) {
return false;
}
const key = uriGetComparisonKey(model.uri);
if (this._editStackElementsMap.has(key)) {
const editStackElement = this._editStackElementsMap.get(key)!;
return editStackElement.canAppend(model);
}
return false;
}
public append(model: ITextModel, textChanges: TextChange[], afterEOL: EndOfLineSequence, afterVersionId: number, afterCursorState: Selection[] | null): void {
const key = uriGetComparisonKey(model.uri);
const editStackElement = this._editStackElementsMap.get(key)!;
editStackElement.append(model, textChanges, afterEOL, afterVersionId, afterCursorState);
}
public close(): void {
this._isOpen = false;
}
public open(): void {
// cannot reopen
}
public undo(): void {
this._isOpen = false;
for (const editStackElement of this._editStackElementsArr) {
editStackElement.undo();
}
}
public redo(): void {
for (const editStackElement of this._editStackElementsArr) {
editStackElement.redo();
}
}
public heapSize(resource: URI): number {
const key = uriGetComparisonKey(resource);
if (this._editStackElementsMap.has(key)) {
const editStackElement = this._editStackElementsMap.get(key)!;
return editStackElement.heapSize();
}
return 0;
}
public split(): IResourceUndoRedoElement[] {
return this._editStackElementsArr;
}
public toString(): string {
const result: string[] = [];
for (const editStackElement of this._editStackElementsArr) {
result.push(`${basename(editStackElement.resource)}: ${editStackElement}`);
}
return `{${result.join(', ')}}`;
}
}
export type EditStackElement = SingleModelEditStackElement | MultiModelEditStackElement;
function getModelEOL(model: ITextModel): EndOfLineSequence {
const eol = model.getEOL();
if (eol === '\n') {
return EndOfLineSequence.LF;
} else {
return EndOfLineSequence.CRLF;
}
}
export function isEditStackElement(element: IResourceUndoRedoElement | IWorkspaceUndoRedoElement | null): element is EditStackElement {
if (!element) {
return false;
}
return ((element instanceof SingleModelEditStackElement) || (element instanceof MultiModelEditStackElement));
}
export class EditStack {
private readonly _model: TextModel;
private readonly _undoRedoService: IUndoRedoService;
constructor(model: TextModel, undoRedoService: IUndoRedoService) {
this._model = model;
this._undoRedoService = undoRedoService;
}
public pushStackElement(): void {
const lastElement = this._undoRedoService.getLastElement(this._model.uri);
if (isEditStackElement(lastElement)) {
lastElement.close();
}
}
public popStackElement(): void {
const lastElement = this._undoRedoService.getLastElement(this._model.uri);
if (isEditStackElement(lastElement)) {
lastElement.open();
}
}
public clear(): void {
this._undoRedoService.removeElements(this._model.uri);
}
private _getOrCreateEditStackElement(beforeCursorState: Selection[] | null, group: UndoRedoGroup | undefined): EditStackElement {
const lastElement = this._undoRedoService.getLastElement(this._model.uri);
if (isEditStackElement(lastElement) && lastElement.canAppend(this._model)) {
return lastElement;
}
const newElement = new SingleModelEditStackElement(nls.localize('edit', "Typing"), 'undoredo.textBufferEdit', this._model, beforeCursorState);
this._undoRedoService.pushElement(newElement, group);
return newElement;
}
public pushEOL(eol: EndOfLineSequence): void {
const editStackElement = this._getOrCreateEditStackElement(null, undefined);
this._model.setEOL(eol);
editStackElement.append(this._model, [], getModelEOL(this._model), this._model.getAlternativeVersionId(), null);
}
public pushEditOperation(beforeCursorState: Selection[] | null, editOperations: ISingleEditOperation[], cursorStateComputer: ICursorStateComputer | null, group?: UndoRedoGroup): Selection[] | null {
const editStackElement = this._getOrCreateEditStackElement(beforeCursorState, group);
const inverseEditOperations = this._model.applyEdits(editOperations, true);
const afterCursorState = EditStack._computeCursorState(cursorStateComputer, inverseEditOperations);
const textChanges = inverseEditOperations.map((op, index) => ({ index: index, textChange: op.textChange }));
textChanges.sort((a, b) => {
if (a.textChange.oldPosition === b.textChange.oldPosition) {
return a.index - b.index;
}
return a.textChange.oldPosition - b.textChange.oldPosition;
});
editStackElement.append(this._model, textChanges.map(op => op.textChange), getModelEOL(this._model), this._model.getAlternativeVersionId(), afterCursorState);
return afterCursorState;
}
private static _computeCursorState(cursorStateComputer: ICursorStateComputer | null, inverseEditOperations: IValidEditOperation[]): Selection[] | null {
try {
return cursorStateComputer ? cursorStateComputer(inverseEditOperations) : null;
} catch (e) {
onUnexpectedError(e);
return null;
}
}
}
| src/vs/editor/common/model/editStack.ts | 0 | https://github.com/microsoft/vscode/commit/48a9149e6ad2cbc0f7ebfdb2ce6143627c077d1e | [
0.0001775515265762806,
0.00017182357260026038,
0.0001621391566004604,
0.00017243108595721424,
0.000003308884970465442
] |
{
"id": 4,
"code_window": [
"\t\tctrl.run({});\n",
"\t\tawait Event.toPromise(Event.filter(ctrl.onDidChangeState, e => e === State.WAIT_FOR_INPUT));\n",
"\n",
"\t\tconst session = inlineChatSessionService.getSession(editor, editor.getModel()!.uri);\n",
"\t\tassert.ok(session);\n",
"\t\tassert.deepStrictEqual(session.wholeRange.value, new Range(1, 1, 1, 6));\n",
"\n",
"\t\tawait ctrl.cancelSession();\n",
"\t\td.dispose();\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tassert.deepStrictEqual(session.wholeRange.value, new Range(1, 1, 1, 3));\n"
],
"file_path": "src/vs/workbench/contrib/inlineChat/test/browser/inlineChatController.test.ts",
"type": "replace",
"edit_start_line_idx": 206
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { flatten, tail, coalesce } from 'vs/base/common/arrays';
import { IStringDictionary } from 'vs/base/common/collections';
import { Emitter, Event } from 'vs/base/common/event';
import { JSONVisitor, visit } from 'vs/base/common/json';
import { Disposable, IReference } from 'vs/base/common/lifecycle';
import { URI } from 'vs/base/common/uri';
import { IRange, Range } from 'vs/editor/common/core/range';
import { Selection } from 'vs/editor/common/core/selection';
import { ITextModel } from 'vs/editor/common/model';
import { ISingleEditOperation } from 'vs/editor/common/core/editOperation';
import { ITextEditorModel } from 'vs/editor/common/services/resolverService';
import * as nls from 'vs/nls';
import { ConfigurationTarget, IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { ConfigurationScope, Extensions, IConfigurationNode, IConfigurationPropertySchema, IConfigurationRegistry, IExtensionInfo, IRegisteredConfigurationPropertySchema, OVERRIDE_PROPERTY_REGEX } from 'vs/platform/configuration/common/configurationRegistry';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { Registry } from 'vs/platform/registry/common/platform';
import { EditorModel } from 'vs/workbench/common/editor/editorModel';
import { IFilterMetadata, IFilterResult, IGroupFilter, IKeybindingsEditorModel, ISearchResultGroup, ISetting, ISettingMatch, ISettingMatcher, ISettingsEditorModel, ISettingsGroup, SettingMatchType } from 'vs/workbench/services/preferences/common/preferences';
import { FOLDER_SCOPES, WORKSPACE_SCOPES } from 'vs/workbench/services/configuration/common/configuration';
import { createValidator } from 'vs/workbench/services/preferences/common/preferencesValidation';
export const nullRange: IRange = { startLineNumber: -1, startColumn: -1, endLineNumber: -1, endColumn: -1 };
function isNullRange(range: IRange): boolean { return range.startLineNumber === -1 && range.startColumn === -1 && range.endLineNumber === -1 && range.endColumn === -1; }
abstract class AbstractSettingsModel extends EditorModel {
protected _currentResultGroups = new Map<string, ISearchResultGroup>();
updateResultGroup(id: string, resultGroup: ISearchResultGroup | undefined): IFilterResult | undefined {
if (resultGroup) {
this._currentResultGroups.set(id, resultGroup);
} else {
this._currentResultGroups.delete(id);
}
this.removeDuplicateResults();
return this.update();
}
/**
* Remove duplicates between result groups, preferring results in earlier groups
*/
private removeDuplicateResults(): void {
const settingKeys = new Set<string>();
[...this._currentResultGroups.keys()]
.sort((a, b) => this._currentResultGroups.get(a)!.order - this._currentResultGroups.get(b)!.order)
.forEach(groupId => {
const group = this._currentResultGroups.get(groupId)!;
group.result.filterMatches = group.result.filterMatches.filter(s => !settingKeys.has(s.setting.key));
group.result.filterMatches.forEach(s => settingKeys.add(s.setting.key));
});
}
filterSettings(filter: string, groupFilter: IGroupFilter, settingMatcher: ISettingMatcher): ISettingMatch[] {
const allGroups = this.filterGroups;
const filterMatches: ISettingMatch[] = [];
for (const group of allGroups) {
const groupMatched = groupFilter(group);
for (const section of group.sections) {
for (const setting of section.settings) {
const settingMatchResult = settingMatcher(setting, group);
if (groupMatched || settingMatchResult) {
filterMatches.push({
setting,
matches: settingMatchResult && settingMatchResult.matches,
matchType: settingMatchResult?.matchType ?? SettingMatchType.None,
score: settingMatchResult?.score ?? 0
});
}
}
}
}
return filterMatches;
}
getPreference(key: string): ISetting | undefined {
for (const group of this.settingsGroups) {
for (const section of group.sections) {
for (const setting of section.settings) {
if (key === setting.key) {
return setting;
}
}
}
}
return undefined;
}
protected collectMetadata(groups: ISearchResultGroup[]): IStringDictionary<IFilterMetadata> {
const metadata = Object.create(null);
let hasMetadata = false;
groups.forEach(g => {
if (g.result.metadata) {
metadata[g.id] = g.result.metadata;
hasMetadata = true;
}
});
return hasMetadata ? metadata : null;
}
protected get filterGroups(): ISettingsGroup[] {
return this.settingsGroups;
}
abstract settingsGroups: ISettingsGroup[];
abstract findValueMatches(filter: string, setting: ISetting): IRange[];
protected abstract update(): IFilterResult | undefined;
}
export class SettingsEditorModel extends AbstractSettingsModel implements ISettingsEditorModel {
private _settingsGroups: ISettingsGroup[] | undefined;
protected settingsModel: ITextModel;
private readonly _onDidChangeGroups: Emitter<void> = this._register(new Emitter<void>());
readonly onDidChangeGroups: Event<void> = this._onDidChangeGroups.event;
constructor(reference: IReference<ITextEditorModel>, private _configurationTarget: ConfigurationTarget) {
super();
this.settingsModel = reference.object.textEditorModel!;
this._register(this.onWillDispose(() => reference.dispose()));
this._register(this.settingsModel.onDidChangeContent(() => {
this._settingsGroups = undefined;
this._onDidChangeGroups.fire();
}));
}
get uri(): URI {
return this.settingsModel.uri;
}
get configurationTarget(): ConfigurationTarget {
return this._configurationTarget;
}
get settingsGroups(): ISettingsGroup[] {
if (!this._settingsGroups) {
this.parse();
}
return this._settingsGroups!;
}
get content(): string {
return this.settingsModel.getValue();
}
findValueMatches(filter: string, setting: ISetting): IRange[] {
return this.settingsModel.findMatches(filter, setting.valueRange, false, false, null, false).map(match => match.range);
}
protected isSettingsProperty(property: string, previousParents: string[]): boolean {
return previousParents.length === 0; // Settings is root
}
protected parse(): void {
this._settingsGroups = parse(this.settingsModel, (property: string, previousParents: string[]): boolean => this.isSettingsProperty(property, previousParents));
}
protected update(): IFilterResult | undefined {
const resultGroups = [...this._currentResultGroups.values()];
if (!resultGroups.length) {
return undefined;
}
// Transform resultGroups into IFilterResult - ISetting ranges are already correct here
const filteredSettings: ISetting[] = [];
const matches: IRange[] = [];
resultGroups.forEach(group => {
group.result.filterMatches.forEach(filterMatch => {
filteredSettings.push(filterMatch.setting);
if (filterMatch.matches) {
matches.push(...filterMatch.matches);
}
});
});
let filteredGroup: ISettingsGroup | undefined;
const modelGroup = this.settingsGroups[0]; // Editable model has one or zero groups
if (modelGroup) {
filteredGroup = {
id: modelGroup.id,
range: modelGroup.range,
sections: [{
settings: filteredSettings
}],
title: modelGroup.title,
titleRange: modelGroup.titleRange,
order: modelGroup.order,
extensionInfo: modelGroup.extensionInfo
};
}
const metadata = this.collectMetadata(resultGroups);
return {
allGroups: this.settingsGroups,
filteredGroups: filteredGroup ? [filteredGroup] : [],
matches,
metadata
};
}
}
export class Settings2EditorModel extends AbstractSettingsModel implements ISettingsEditorModel {
private readonly _onDidChangeGroups: Emitter<void> = this._register(new Emitter<void>());
readonly onDidChangeGroups: Event<void> = this._onDidChangeGroups.event;
private additionalGroups: ISettingsGroup[] | undefined;
private dirty = false;
constructor(
private _defaultSettings: DefaultSettings,
@IConfigurationService configurationService: IConfigurationService,
) {
super();
this._register(configurationService.onDidChangeConfiguration(e => {
if (e.source === ConfigurationTarget.DEFAULT) {
this.dirty = true;
this._onDidChangeGroups.fire();
}
}));
this._register(Registry.as<IConfigurationRegistry>(Extensions.Configuration).onDidSchemaChange(e => {
this.dirty = true;
this._onDidChangeGroups.fire();
}));
}
/** Doesn't include the "Commonly Used" group */
protected override get filterGroups(): ISettingsGroup[] {
return this.settingsGroups.slice(1);
}
get settingsGroups(): ISettingsGroup[] {
const groups = this._defaultSettings.getSettingsGroups(this.dirty);
if (this.additionalGroups?.length) {
groups.push(...this.additionalGroups);
}
this.dirty = false;
return groups;
}
/** For programmatically added groups outside of registered configurations */
setAdditionalGroups(groups: ISettingsGroup[]) {
this.additionalGroups = groups;
}
findValueMatches(filter: string, setting: ISetting): IRange[] {
// TODO @roblou
return [];
}
protected update(): IFilterResult {
throw new Error('Not supported');
}
}
function parse(model: ITextModel, isSettingsProperty: (currentProperty: string, previousParents: string[]) => boolean): ISettingsGroup[] {
const settings: ISetting[] = [];
let overrideSetting: ISetting | null = null;
let currentProperty: string | null = null;
let currentParent: any = [];
const previousParents: any[] = [];
let settingsPropertyIndex: number = -1;
const range = {
startLineNumber: 0,
startColumn: 0,
endLineNumber: 0,
endColumn: 0
};
function onValue(value: any, offset: number, length: number) {
if (Array.isArray(currentParent)) {
(<any[]>currentParent).push(value);
} else if (currentProperty) {
currentParent[currentProperty] = value;
}
if (previousParents.length === settingsPropertyIndex + 1 || (previousParents.length === settingsPropertyIndex + 2 && overrideSetting !== null)) {
// settings value started
const setting = previousParents.length === settingsPropertyIndex + 1 ? settings[settings.length - 1] : overrideSetting!.overrides![overrideSetting!.overrides!.length - 1];
if (setting) {
const valueStartPosition = model.getPositionAt(offset);
const valueEndPosition = model.getPositionAt(offset + length);
setting.value = value;
setting.valueRange = {
startLineNumber: valueStartPosition.lineNumber,
startColumn: valueStartPosition.column,
endLineNumber: valueEndPosition.lineNumber,
endColumn: valueEndPosition.column
};
setting.range = Object.assign(setting.range, {
endLineNumber: valueEndPosition.lineNumber,
endColumn: valueEndPosition.column
});
}
}
}
const visitor: JSONVisitor = {
onObjectBegin: (offset: number, length: number) => {
if (isSettingsProperty(currentProperty!, previousParents)) {
// Settings started
settingsPropertyIndex = previousParents.length;
const position = model.getPositionAt(offset);
range.startLineNumber = position.lineNumber;
range.startColumn = position.column;
}
const object = {};
onValue(object, offset, length);
currentParent = object;
currentProperty = null;
previousParents.push(currentParent);
},
onObjectProperty: (name: string, offset: number, length: number) => {
currentProperty = name;
if (previousParents.length === settingsPropertyIndex + 1 || (previousParents.length === settingsPropertyIndex + 2 && overrideSetting !== null)) {
// setting started
const settingStartPosition = model.getPositionAt(offset);
const setting: ISetting = {
description: [],
descriptionIsMarkdown: false,
key: name,
keyRange: {
startLineNumber: settingStartPosition.lineNumber,
startColumn: settingStartPosition.column + 1,
endLineNumber: settingStartPosition.lineNumber,
endColumn: settingStartPosition.column + length
},
range: {
startLineNumber: settingStartPosition.lineNumber,
startColumn: settingStartPosition.column,
endLineNumber: 0,
endColumn: 0
},
value: null,
valueRange: nullRange,
descriptionRanges: [],
overrides: [],
overrideOf: overrideSetting ?? undefined,
};
if (previousParents.length === settingsPropertyIndex + 1) {
settings.push(setting);
if (OVERRIDE_PROPERTY_REGEX.test(name)) {
overrideSetting = setting;
}
} else {
overrideSetting!.overrides!.push(setting);
}
}
},
onObjectEnd: (offset: number, length: number) => {
currentParent = previousParents.pop();
if (settingsPropertyIndex !== -1 && (previousParents.length === settingsPropertyIndex + 1 || (previousParents.length === settingsPropertyIndex + 2 && overrideSetting !== null))) {
// setting ended
const setting = previousParents.length === settingsPropertyIndex + 1 ? settings[settings.length - 1] : overrideSetting!.overrides![overrideSetting!.overrides!.length - 1];
if (setting) {
const valueEndPosition = model.getPositionAt(offset + length);
setting.valueRange = Object.assign(setting.valueRange, {
endLineNumber: valueEndPosition.lineNumber,
endColumn: valueEndPosition.column
});
setting.range = Object.assign(setting.range, {
endLineNumber: valueEndPosition.lineNumber,
endColumn: valueEndPosition.column
});
}
if (previousParents.length === settingsPropertyIndex + 1) {
overrideSetting = null;
}
}
if (previousParents.length === settingsPropertyIndex) {
// settings ended
const position = model.getPositionAt(offset);
range.endLineNumber = position.lineNumber;
range.endColumn = position.column;
settingsPropertyIndex = -1;
}
},
onArrayBegin: (offset: number, length: number) => {
const array: any[] = [];
onValue(array, offset, length);
previousParents.push(currentParent);
currentParent = array;
currentProperty = null;
},
onArrayEnd: (offset: number, length: number) => {
currentParent = previousParents.pop();
if (previousParents.length === settingsPropertyIndex + 1 || (previousParents.length === settingsPropertyIndex + 2 && overrideSetting !== null)) {
// setting value ended
const setting = previousParents.length === settingsPropertyIndex + 1 ? settings[settings.length - 1] : overrideSetting!.overrides![overrideSetting!.overrides!.length - 1];
if (setting) {
const valueEndPosition = model.getPositionAt(offset + length);
setting.valueRange = Object.assign(setting.valueRange, {
endLineNumber: valueEndPosition.lineNumber,
endColumn: valueEndPosition.column
});
setting.range = Object.assign(setting.range, {
endLineNumber: valueEndPosition.lineNumber,
endColumn: valueEndPosition.column
});
}
}
},
onLiteralValue: onValue,
onError: (error) => {
const setting = settings[settings.length - 1];
if (setting && (isNullRange(setting.range) || isNullRange(setting.keyRange) || isNullRange(setting.valueRange))) {
settings.pop();
}
}
};
if (!model.isDisposed()) {
visit(model.getValue(), visitor);
}
return settings.length > 0 ? [<ISettingsGroup>{
sections: [
{
settings
}
],
title: '',
titleRange: nullRange,
range
}] : [];
}
export class WorkspaceConfigurationEditorModel extends SettingsEditorModel {
private _configurationGroups: ISettingsGroup[] = [];
get configurationGroups(): ISettingsGroup[] {
return this._configurationGroups;
}
protected override parse(): void {
super.parse();
this._configurationGroups = parse(this.settingsModel, (property: string, previousParents: string[]): boolean => previousParents.length === 0);
}
protected override isSettingsProperty(property: string, previousParents: string[]): boolean {
return property === 'settings' && previousParents.length === 1;
}
}
export class DefaultSettings extends Disposable {
private _allSettingsGroups: ISettingsGroup[] | undefined;
private _content: string | undefined;
private _contentWithoutMostCommonlyUsed: string | undefined;
private _settingsByName = new Map<string, ISetting>();
readonly _onDidChange: Emitter<void> = this._register(new Emitter<void>());
readonly onDidChange: Event<void> = this._onDidChange.event;
constructor(
private _mostCommonlyUsedSettingsKeys: string[],
readonly target: ConfigurationTarget,
) {
super();
}
getContent(forceUpdate = false): string {
if (!this._content || forceUpdate) {
this.initialize();
}
return this._content!;
}
getContentWithoutMostCommonlyUsed(forceUpdate = false): string {
if (!this._contentWithoutMostCommonlyUsed || forceUpdate) {
this.initialize();
}
return this._contentWithoutMostCommonlyUsed!;
}
getSettingsGroups(forceUpdate = false): ISettingsGroup[] {
if (!this._allSettingsGroups || forceUpdate) {
this.initialize();
}
return this._allSettingsGroups!;
}
private initialize(): void {
this._allSettingsGroups = this.parse();
this._content = this.toContent(this._allSettingsGroups, 0);
this._contentWithoutMostCommonlyUsed = this.toContent(this._allSettingsGroups, 1);
}
private parse(): ISettingsGroup[] {
const settingsGroups = this.getRegisteredGroups();
this.initAllSettingsMap(settingsGroups);
const mostCommonlyUsed = this.getMostCommonlyUsedSettings(settingsGroups);
return [mostCommonlyUsed, ...settingsGroups];
}
getRegisteredGroups(): ISettingsGroup[] {
const configurations = Registry.as<IConfigurationRegistry>(Extensions.Configuration).getConfigurations().slice();
const groups = this.removeEmptySettingsGroups(configurations.sort(this.compareConfigurationNodes)
.reduce<ISettingsGroup[]>((result, config, index, array) => this.parseConfig(config, result, array), []));
return this.sortGroups(groups);
}
private sortGroups(groups: ISettingsGroup[]): ISettingsGroup[] {
groups.forEach(group => {
group.sections.forEach(section => {
section.settings.sort((a, b) => a.key.localeCompare(b.key));
});
});
return groups;
}
private initAllSettingsMap(allSettingsGroups: ISettingsGroup[]): void {
this._settingsByName = new Map<string, ISetting>();
for (const group of allSettingsGroups) {
for (const section of group.sections) {
for (const setting of section.settings) {
this._settingsByName.set(setting.key, setting);
}
}
}
}
private getMostCommonlyUsedSettings(allSettingsGroups: ISettingsGroup[]): ISettingsGroup {
const settings = coalesce(this._mostCommonlyUsedSettingsKeys.map(key => {
const setting = this._settingsByName.get(key);
if (setting) {
return <ISetting>{
description: setting.description,
key: setting.key,
value: setting.value,
keyRange: nullRange,
range: nullRange,
valueRange: nullRange,
overrides: [],
scope: ConfigurationScope.RESOURCE,
type: setting.type,
enum: setting.enum,
enumDescriptions: setting.enumDescriptions,
descriptionRanges: []
};
}
return null;
}));
return <ISettingsGroup>{
id: 'mostCommonlyUsed',
range: nullRange,
title: nls.localize('commonlyUsed', "Commonly Used"),
titleRange: nullRange,
sections: [
{
settings
}
]
};
}
private parseConfig(config: IConfigurationNode, result: ISettingsGroup[], configurations: IConfigurationNode[], settingsGroup?: ISettingsGroup, seenSettings?: { [key: string]: boolean }): ISettingsGroup[] {
seenSettings = seenSettings ? seenSettings : {};
let title = config.title;
if (!title) {
const configWithTitleAndSameId = configurations.find(c => (c.id === config.id) && c.title);
if (configWithTitleAndSameId) {
title = configWithTitleAndSameId.title;
}
}
if (title) {
if (!settingsGroup) {
settingsGroup = result.find(g => g.title === title && g.extensionInfo?.id === config.extensionInfo?.id);
if (!settingsGroup) {
settingsGroup = { sections: [{ settings: [] }], id: config.id || '', title: title || '', titleRange: nullRange, order: config.order, range: nullRange, extensionInfo: config.extensionInfo };
result.push(settingsGroup);
}
} else {
settingsGroup.sections[settingsGroup.sections.length - 1].title = title;
}
}
if (config.properties) {
if (!settingsGroup) {
settingsGroup = { sections: [{ settings: [] }], id: config.id || '', title: config.id || '', titleRange: nullRange, order: config.order, range: nullRange, extensionInfo: config.extensionInfo };
result.push(settingsGroup);
}
const configurationSettings: ISetting[] = [];
for (const setting of [...settingsGroup.sections[settingsGroup.sections.length - 1].settings, ...this.parseSettings(config)]) {
if (!seenSettings[setting.key]) {
configurationSettings.push(setting);
seenSettings[setting.key] = true;
}
}
if (configurationSettings.length) {
settingsGroup.sections[settingsGroup.sections.length - 1].settings = configurationSettings;
}
}
config.allOf?.forEach(c => this.parseConfig(c, result, configurations, settingsGroup, seenSettings));
return result;
}
private removeEmptySettingsGroups(settingsGroups: ISettingsGroup[]): ISettingsGroup[] {
const result: ISettingsGroup[] = [];
for (const settingsGroup of settingsGroups) {
settingsGroup.sections = settingsGroup.sections.filter(section => section.settings.length > 0);
if (settingsGroup.sections.length) {
result.push(settingsGroup);
}
}
return result;
}
private parseSettings(config: IConfigurationNode): ISetting[] {
const result: ISetting[] = [];
const settingsObject = config.properties;
const extensionInfo = config.extensionInfo;
// Try using the title if the category id wasn't given
// (in which case the category id is the same as the extension id)
const categoryLabel = config.extensionInfo?.id === config.id ? config.title : config.id;
for (const key in settingsObject) {
const prop: IConfigurationPropertySchema = settingsObject[key];
if (this.matchesScope(prop)) {
const value = prop.default;
let description = (prop.markdownDescription || prop.description || '');
if (typeof description !== 'string') {
description = '';
}
const descriptionLines = description.split('\n');
const overrides = OVERRIDE_PROPERTY_REGEX.test(key) ? this.parseOverrideSettings(prop.default) : [];
let listItemType: string | undefined;
if (prop.type === 'array' && prop.items && !Array.isArray(prop.items) && prop.items.type) {
if (prop.items.enum) {
listItemType = 'enum';
} else if (!Array.isArray(prop.items.type)) {
listItemType = prop.items.type;
}
}
const objectProperties = prop.type === 'object' ? prop.properties : undefined;
const objectPatternProperties = prop.type === 'object' ? prop.patternProperties : undefined;
const objectAdditionalProperties = prop.type === 'object' ? prop.additionalProperties : undefined;
let enumToUse = prop.enum;
let enumDescriptions = prop.markdownEnumDescriptions ?? prop.enumDescriptions;
let enumDescriptionsAreMarkdown = !!prop.markdownEnumDescriptions;
if (listItemType === 'enum' && !Array.isArray(prop.items)) {
enumToUse = prop.items!.enum;
enumDescriptions = prop.items!.markdownEnumDescriptions ?? prop.items!.enumDescriptions;
enumDescriptionsAreMarkdown = !!prop.items!.markdownEnumDescriptions;
}
let allKeysAreBoolean = false;
if (prop.type === 'object' && !prop.additionalProperties && prop.properties && Object.keys(prop.properties).length) {
allKeysAreBoolean = Object.keys(prop.properties).every(key => {
return prop.properties![key].type === 'boolean';
});
}
let isLanguageTagSetting = false;
if (OVERRIDE_PROPERTY_REGEX.test(key)) {
isLanguageTagSetting = true;
}
let defaultValueSource: string | IExtensionInfo | undefined;
if (!isLanguageTagSetting) {
const registeredConfigurationProp = prop as IRegisteredConfigurationPropertySchema;
if (registeredConfigurationProp && registeredConfigurationProp.defaultValueSource) {
defaultValueSource = registeredConfigurationProp.defaultValueSource;
}
}
if (!enumToUse && (prop.enumItemLabels || enumDescriptions || enumDescriptionsAreMarkdown)) {
console.error(`The setting ${key} has enum-related fields, but doesn't have an enum field. This setting may render improperly in the Settings editor.`);
}
result.push({
key,
value,
description: descriptionLines,
descriptionIsMarkdown: !!prop.markdownDescription,
range: nullRange,
keyRange: nullRange,
valueRange: nullRange,
descriptionRanges: [],
overrides,
scope: prop.scope,
type: prop.type,
arrayItemType: listItemType,
objectProperties,
objectPatternProperties,
objectAdditionalProperties,
enum: enumToUse,
enumDescriptions: enumDescriptions,
enumDescriptionsAreMarkdown: enumDescriptionsAreMarkdown,
enumItemLabels: prop.enumItemLabels,
uniqueItems: prop.uniqueItems,
tags: prop.tags,
disallowSyncIgnore: prop.disallowSyncIgnore,
restricted: prop.restricted,
extensionInfo: extensionInfo,
deprecationMessage: prop.markdownDeprecationMessage || prop.deprecationMessage,
deprecationMessageIsMarkdown: !!prop.markdownDeprecationMessage,
validator: createValidator(prop),
allKeysAreBoolean,
editPresentation: prop.editPresentation,
order: prop.order,
nonLanguageSpecificDefaultValueSource: defaultValueSource,
isLanguageTagSetting,
categoryLabel
});
}
}
return result;
}
private parseOverrideSettings(overrideSettings: any): ISetting[] {
return Object.keys(overrideSettings).map((key) => ({
key,
value: overrideSettings[key],
description: [],
descriptionIsMarkdown: false,
range: nullRange,
keyRange: nullRange,
valueRange: nullRange,
descriptionRanges: [],
overrides: []
}));
}
private matchesScope(property: IConfigurationNode): boolean {
if (!property.scope) {
return true;
}
if (this.target === ConfigurationTarget.WORKSPACE_FOLDER) {
return FOLDER_SCOPES.indexOf(property.scope) !== -1;
}
if (this.target === ConfigurationTarget.WORKSPACE) {
return WORKSPACE_SCOPES.indexOf(property.scope) !== -1;
}
return true;
}
private compareConfigurationNodes(c1: IConfigurationNode, c2: IConfigurationNode): number {
if (typeof c1.order !== 'number') {
return 1;
}
if (typeof c2.order !== 'number') {
return -1;
}
if (c1.order === c2.order) {
const title1 = c1.title || '';
const title2 = c2.title || '';
return title1.localeCompare(title2);
}
return c1.order - c2.order;
}
private toContent(settingsGroups: ISettingsGroup[], startIndex: number): string {
const builder = new SettingsContentBuilder();
for (let i = startIndex; i < settingsGroups.length; i++) {
builder.pushGroup(settingsGroups[i], i === startIndex, i === settingsGroups.length - 1);
}
return builder.getContent();
}
}
export class DefaultSettingsEditorModel extends AbstractSettingsModel implements ISettingsEditorModel {
private _model: ITextModel;
private readonly _onDidChangeGroups: Emitter<void> = this._register(new Emitter<void>());
readonly onDidChangeGroups: Event<void> = this._onDidChangeGroups.event;
constructor(
private _uri: URI,
reference: IReference<ITextEditorModel>,
private readonly defaultSettings: DefaultSettings
) {
super();
this._register(defaultSettings.onDidChange(() => this._onDidChangeGroups.fire()));
this._model = reference.object.textEditorModel!;
this._register(this.onWillDispose(() => reference.dispose()));
}
get uri(): URI {
return this._uri;
}
get target(): ConfigurationTarget {
return this.defaultSettings.target;
}
get settingsGroups(): ISettingsGroup[] {
return this.defaultSettings.getSettingsGroups();
}
protected override get filterGroups(): ISettingsGroup[] {
// Don't look at "commonly used" for filter
return this.settingsGroups.slice(1);
}
protected update(): IFilterResult | undefined {
if (this._model.isDisposed()) {
return undefined;
}
// Grab current result groups, only render non-empty groups
const resultGroups = [...this._currentResultGroups.values()]
.sort((a, b) => a.order - b.order);
const nonEmptyResultGroups = resultGroups.filter(group => group.result.filterMatches.length);
const startLine = tail(this.settingsGroups).range.endLineNumber + 2;
const { settingsGroups: filteredGroups, matches } = this.writeResultGroups(nonEmptyResultGroups, startLine);
const metadata = this.collectMetadata(resultGroups);
return resultGroups.length ?
<IFilterResult>{
allGroups: this.settingsGroups,
filteredGroups,
matches,
metadata
} :
undefined;
}
/**
* Translate the ISearchResultGroups to text, and write it to the editor model
*/
private writeResultGroups(groups: ISearchResultGroup[], startLine: number): { matches: IRange[]; settingsGroups: ISettingsGroup[] } {
const contentBuilderOffset = startLine - 1;
const builder = new SettingsContentBuilder(contentBuilderOffset);
const settingsGroups: ISettingsGroup[] = [];
const matches: IRange[] = [];
if (groups.length) {
builder.pushLine(',');
groups.forEach(resultGroup => {
const settingsGroup = this.getGroup(resultGroup);
settingsGroups.push(settingsGroup);
matches.push(...this.writeSettingsGroupToBuilder(builder, settingsGroup, resultGroup.result.filterMatches));
});
}
// note: 1-indexed line numbers here
const groupContent = builder.getContent() + '\n';
const groupEndLine = this._model.getLineCount();
const cursorPosition = new Selection(startLine, 1, startLine, 1);
const edit: ISingleEditOperation = {
text: groupContent,
forceMoveMarkers: true,
range: new Range(startLine, 1, groupEndLine, 1)
};
this._model.pushEditOperations([cursorPosition], [edit], () => [cursorPosition]);
// Force tokenization now - otherwise it may be slightly delayed, causing a flash of white text
const tokenizeTo = Math.min(startLine + 60, this._model.getLineCount());
this._model.tokenization.forceTokenization(tokenizeTo);
return { matches, settingsGroups };
}
private writeSettingsGroupToBuilder(builder: SettingsContentBuilder, settingsGroup: ISettingsGroup, filterMatches: ISettingMatch[]): IRange[] {
filterMatches = filterMatches
.map(filteredMatch => {
// Fix match ranges to offset from setting start line
return <ISettingMatch>{
setting: filteredMatch.setting,
score: filteredMatch.score,
matches: filteredMatch.matches && filteredMatch.matches.map(match => {
return new Range(
match.startLineNumber - filteredMatch.setting.range.startLineNumber,
match.startColumn,
match.endLineNumber - filteredMatch.setting.range.startLineNumber,
match.endColumn);
})
};
});
builder.pushGroup(settingsGroup);
// builder has rewritten settings ranges, fix match ranges
const fixedMatches = flatten(
filterMatches
.map(m => m.matches || [])
.map((settingMatches, i) => {
const setting = settingsGroup.sections[0].settings[i];
return settingMatches.map(range => {
return new Range(
range.startLineNumber + setting.range.startLineNumber,
range.startColumn,
range.endLineNumber + setting.range.startLineNumber,
range.endColumn);
});
}));
return fixedMatches;
}
private copySetting(setting: ISetting): ISetting {
return {
description: setting.description,
scope: setting.scope,
type: setting.type,
enum: setting.enum,
enumDescriptions: setting.enumDescriptions,
key: setting.key,
value: setting.value,
range: setting.range,
overrides: [],
overrideOf: setting.overrideOf,
tags: setting.tags,
deprecationMessage: setting.deprecationMessage,
keyRange: nullRange,
valueRange: nullRange,
descriptionIsMarkdown: undefined,
descriptionRanges: []
};
}
findValueMatches(filter: string, setting: ISetting): IRange[] {
return [];
}
override getPreference(key: string): ISetting | undefined {
for (const group of this.settingsGroups) {
for (const section of group.sections) {
for (const setting of section.settings) {
if (setting.key === key) {
return setting;
}
}
}
}
return undefined;
}
private getGroup(resultGroup: ISearchResultGroup): ISettingsGroup {
return <ISettingsGroup>{
id: resultGroup.id,
range: nullRange,
title: resultGroup.label,
titleRange: nullRange,
sections: [
{
settings: resultGroup.result.filterMatches.map(m => this.copySetting(m.setting))
}
]
};
}
}
class SettingsContentBuilder {
private _contentByLines: string[];
private get lineCountWithOffset(): number {
return this._contentByLines.length + this._rangeOffset;
}
private get lastLine(): string {
return this._contentByLines[this._contentByLines.length - 1] || '';
}
constructor(private _rangeOffset = 0) {
this._contentByLines = [];
}
pushLine(...lineText: string[]): void {
this._contentByLines.push(...lineText);
}
pushGroup(settingsGroups: ISettingsGroup, isFirst?: boolean, isLast?: boolean): void {
this._contentByLines.push(isFirst ? '[{' : '{');
const lastSetting = this._pushGroup(settingsGroups, ' ');
if (lastSetting) {
// Strip the comma from the last setting
const lineIdx = lastSetting.range.endLineNumber - this._rangeOffset;
const content = this._contentByLines[lineIdx - 2];
this._contentByLines[lineIdx - 2] = content.substring(0, content.length - 1);
}
this._contentByLines.push(isLast ? '}]' : '},');
}
protected _pushGroup(group: ISettingsGroup, indent: string): ISetting | null {
let lastSetting: ISetting | null = null;
const groupStart = this.lineCountWithOffset + 1;
for (const section of group.sections) {
if (section.title) {
const sectionTitleStart = this.lineCountWithOffset + 1;
this.addDescription([section.title], indent, this._contentByLines);
section.titleRange = { startLineNumber: sectionTitleStart, startColumn: 1, endLineNumber: this.lineCountWithOffset, endColumn: this.lastLine.length };
}
if (section.settings.length) {
for (const setting of section.settings) {
this.pushSetting(setting, indent);
lastSetting = setting;
}
}
}
group.range = { startLineNumber: groupStart, startColumn: 1, endLineNumber: this.lineCountWithOffset, endColumn: this.lastLine.length };
return lastSetting;
}
getContent(): string {
return this._contentByLines.join('\n');
}
private pushSetting(setting: ISetting, indent: string): void {
const settingStart = this.lineCountWithOffset + 1;
this.pushSettingDescription(setting, indent);
let preValueContent = indent;
const keyString = JSON.stringify(setting.key);
preValueContent += keyString;
setting.keyRange = { startLineNumber: this.lineCountWithOffset + 1, startColumn: preValueContent.indexOf(setting.key) + 1, endLineNumber: this.lineCountWithOffset + 1, endColumn: setting.key.length };
preValueContent += ': ';
const valueStart = this.lineCountWithOffset + 1;
this.pushValue(setting, preValueContent, indent);
setting.valueRange = { startLineNumber: valueStart, startColumn: preValueContent.length + 1, endLineNumber: this.lineCountWithOffset, endColumn: this.lastLine.length + 1 };
this._contentByLines[this._contentByLines.length - 1] += ',';
this._contentByLines.push('');
setting.range = { startLineNumber: settingStart, startColumn: 1, endLineNumber: this.lineCountWithOffset, endColumn: this.lastLine.length };
}
private pushSettingDescription(setting: ISetting, indent: string): void {
const fixSettingLink = (line: string) => line.replace(/`#(.*)#`/g, (match, settingName) => `\`${settingName}\``);
setting.descriptionRanges = [];
const descriptionPreValue = indent + '// ';
const deprecationMessageLines = setting.deprecationMessage?.split(/\n/g) ?? [];
for (let line of [...deprecationMessageLines, ...setting.description]) {
line = fixSettingLink(line);
this._contentByLines.push(descriptionPreValue + line);
setting.descriptionRanges.push({ startLineNumber: this.lineCountWithOffset, startColumn: this.lastLine.indexOf(line) + 1, endLineNumber: this.lineCountWithOffset, endColumn: this.lastLine.length });
}
if (setting.enum && setting.enumDescriptions?.some(desc => !!desc)) {
setting.enumDescriptions.forEach((desc, i) => {
const displayEnum = escapeInvisibleChars(String(setting.enum![i]));
const line = desc ?
`${displayEnum}: ${fixSettingLink(desc)}` :
displayEnum;
const lines = line.split(/\n/g);
lines[0] = ' - ' + lines[0];
this._contentByLines.push(...lines.map(l => `${indent}// ${l}`));
setting.descriptionRanges.push({ startLineNumber: this.lineCountWithOffset, startColumn: this.lastLine.indexOf(line) + 1, endLineNumber: this.lineCountWithOffset, endColumn: this.lastLine.length });
});
}
}
private pushValue(setting: ISetting, preValueConent: string, indent: string): void {
const valueString = JSON.stringify(setting.value, null, indent);
if (valueString && (typeof setting.value === 'object')) {
if (setting.overrides && setting.overrides.length) {
this._contentByLines.push(preValueConent + ' {');
for (const subSetting of setting.overrides) {
this.pushSetting(subSetting, indent + indent);
this._contentByLines.pop();
}
const lastSetting = setting.overrides[setting.overrides.length - 1];
const content = this._contentByLines[lastSetting.range.endLineNumber - 2];
this._contentByLines[lastSetting.range.endLineNumber - 2] = content.substring(0, content.length - 1);
this._contentByLines.push(indent + '}');
} else {
const mulitLineValue = valueString.split('\n');
this._contentByLines.push(preValueConent + mulitLineValue[0]);
for (let i = 1; i < mulitLineValue.length; i++) {
this._contentByLines.push(indent + mulitLineValue[i]);
}
}
} else {
this._contentByLines.push(preValueConent + valueString);
}
}
private addDescription(description: string[], indent: string, result: string[]) {
for (const line of description) {
result.push(indent + '// ' + line);
}
}
}
class RawSettingsContentBuilder extends SettingsContentBuilder {
constructor(private indent: string = '\t') {
super(0);
}
override pushGroup(settingsGroups: ISettingsGroup): void {
this._pushGroup(settingsGroups, this.indent);
}
}
export class DefaultRawSettingsEditorModel extends Disposable {
private _content: string | null = null;
constructor(private defaultSettings: DefaultSettings) {
super();
this._register(defaultSettings.onDidChange(() => this._content = null));
}
get content(): string {
if (this._content === null) {
const builder = new RawSettingsContentBuilder();
builder.pushLine('{');
for (const settingsGroup of this.defaultSettings.getRegisteredGroups()) {
builder.pushGroup(settingsGroup);
}
builder.pushLine('}');
this._content = builder.getContent();
}
return this._content;
}
}
function escapeInvisibleChars(enumValue: string): string {
return enumValue && enumValue
.replace(/\n/g, '\\n')
.replace(/\r/g, '\\r');
}
export function defaultKeybindingsContents(keybindingService: IKeybindingService): string {
const defaultsHeader = '// ' + nls.localize('defaultKeybindingsHeader', "Override key bindings by placing them into your key bindings file.");
return defaultsHeader + '\n' + keybindingService.getDefaultKeybindingsContent();
}
export class DefaultKeybindingsEditorModel implements IKeybindingsEditorModel<any> {
private _content: string | undefined;
constructor(private _uri: URI,
@IKeybindingService private readonly keybindingService: IKeybindingService) {
}
get uri(): URI {
return this._uri;
}
get content(): string {
if (!this._content) {
this._content = defaultKeybindingsContents(this.keybindingService);
}
return this._content;
}
getPreference(): any {
return null;
}
dispose(): void {
// Not disposable
}
}
| src/vs/workbench/services/preferences/common/preferencesModels.ts | 0 | https://github.com/microsoft/vscode/commit/48a9149e6ad2cbc0f7ebfdb2ce6143627c077d1e | [
0.0010964777320623398,
0.00018166123481933028,
0.00016233130008913577,
0.00017132158973254263,
0.00008677082951180637
] |
{
"id": 4,
"code_window": [
"\t\tctrl.run({});\n",
"\t\tawait Event.toPromise(Event.filter(ctrl.onDidChangeState, e => e === State.WAIT_FOR_INPUT));\n",
"\n",
"\t\tconst session = inlineChatSessionService.getSession(editor, editor.getModel()!.uri);\n",
"\t\tassert.ok(session);\n",
"\t\tassert.deepStrictEqual(session.wholeRange.value, new Range(1, 1, 1, 6));\n",
"\n",
"\t\tawait ctrl.cancelSession();\n",
"\t\td.dispose();\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tassert.deepStrictEqual(session.wholeRange.value, new Range(1, 1, 1, 3));\n"
],
"file_path": "src/vs/workbench/contrib/inlineChat/test/browser/inlineChatController.test.ts",
"type": "replace",
"edit_start_line_idx": 206
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { sha1Hex } from 'vs/base/browser/hash';
import { onUnexpectedError } from 'vs/base/common/errors';
import { URI } from 'vs/base/common/uri';
import { IFileService, IFileStat } from 'vs/platform/files/common/files';
import { ITelemetryService, TelemetryLevel } from 'vs/platform/telemetry/common/telemetry';
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
import { IWorkbenchContribution } from 'vs/workbench/common/contributions';
import { ITextFileService, } from 'vs/workbench/services/textfile/common/textfiles';
import { IWorkspaceTagsService, Tags, getHashedRemotesFromConfig as baseGetHashedRemotesFromConfig } from 'vs/workbench/contrib/tags/common/workspaceTags';
import { IDiagnosticsService, IWorkspaceInformation } from 'vs/platform/diagnostics/common/diagnostics';
import { IRequestService } from 'vs/platform/request/common/request';
import { isWindows } from 'vs/base/common/platform';
import { AllowedSecondLevelDomains, getDomainsOfRemotes } from 'vs/platform/extensionManagement/common/configRemotes';
import { INativeHostService } from 'vs/platform/native/common/native';
import { IProductService } from 'vs/platform/product/common/productService';
export async function getHashedRemotesFromConfig(text: string, stripEndingDotGit: boolean = false): Promise<string[]> {
return baseGetHashedRemotesFromConfig(text, stripEndingDotGit, remote => sha1Hex(remote));
}
export class WorkspaceTags implements IWorkbenchContribution {
constructor(
@IFileService private readonly fileService: IFileService,
@IWorkspaceContextService private readonly contextService: IWorkspaceContextService,
@ITelemetryService private readonly telemetryService: ITelemetryService,
@IRequestService private readonly requestService: IRequestService,
@ITextFileService private readonly textFileService: ITextFileService,
@IWorkspaceTagsService private readonly workspaceTagsService: IWorkspaceTagsService,
@IDiagnosticsService private readonly diagnosticsService: IDiagnosticsService,
@IProductService private readonly productService: IProductService,
@INativeHostService private readonly nativeHostService: INativeHostService
) {
if (this.telemetryService.telemetryLevel === TelemetryLevel.USAGE) {
this.report();
}
}
private async report(): Promise<void> {
// Windows-only Edition Event
this.reportWindowsEdition();
// Workspace Tags
this.workspaceTagsService.getTags()
.then(tags => this.reportWorkspaceTags(tags), error => onUnexpectedError(error));
// Cloud Stats
this.reportCloudStats();
this.reportProxyStats();
this.getWorkspaceInformation().then(stats => this.diagnosticsService.reportWorkspaceStats(stats));
}
private async reportWindowsEdition(): Promise<void> {
if (!isWindows) {
return;
}
let value = await this.nativeHostService.windowsGetStringRegKey('HKEY_LOCAL_MACHINE', 'SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion', 'EditionID');
if (value === undefined) {
value = 'Unknown';
}
this.telemetryService.publicLog2<{ edition: string }, { owner: 'sbatten'; comment: 'Information about the Windows edition.'; edition: { classification: 'SystemMetaData'; purpose: 'BusinessInsight'; comment: 'The Windows edition.' } }>('windowsEdition', { edition: value });
}
private async getWorkspaceInformation(): Promise<IWorkspaceInformation> {
const workspace = this.contextService.getWorkspace();
const state = this.contextService.getWorkbenchState();
const telemetryId = await this.workspaceTagsService.getTelemetryWorkspaceId(workspace, state);
return {
id: workspace.id,
telemetryId,
rendererSessionId: this.telemetryService.sessionId,
folders: workspace.folders,
transient: workspace.transient,
configuration: workspace.configuration
};
}
private reportWorkspaceTags(tags: Tags): void {
/* __GDPR__
"workspce.tags" : {
"owner": "lramos15",
"${include}": [
"${WorkspaceTags}"
]
}
*/
this.telemetryService.publicLog('workspce.tags', tags);
}
private reportRemoteDomains(workspaceUris: URI[]): void {
Promise.all<string[]>(workspaceUris.map(workspaceUri => {
const path = workspaceUri.path;
const uri = workspaceUri.with({ path: `${path !== '/' ? path : ''}/.git/config` });
return this.fileService.exists(uri).then(exists => {
if (!exists) {
return [];
}
return this.textFileService.read(uri, { acceptTextOnly: true }).then(
content => getDomainsOfRemotes(content.value, AllowedSecondLevelDomains),
err => [] // ignore missing or binary file
);
});
})).then(domains => {
const set = domains.reduce((set, list) => list.reduce((set, item) => set.add(item), set), new Set<string>());
const list: string[] = [];
set.forEach(item => list.push(item));
/* __GDPR__
"workspace.remotes" : {
"owner": "lramos15",
"domains" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
}
*/
this.telemetryService.publicLog('workspace.remotes', { domains: list.sort() });
}, onUnexpectedError);
}
private reportRemotes(workspaceUris: URI[]): void {
Promise.all<string[]>(workspaceUris.map(workspaceUri => {
return this.workspaceTagsService.getHashedRemotesFromUri(workspaceUri, true);
})).then(() => { }, onUnexpectedError);
}
/* __GDPR__FRAGMENT__
"AzureTags" : {
"node" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }
}
*/
private reportAzureNode(workspaceUris: URI[], tags: Tags): Promise<Tags> {
// TODO: should also work for `node_modules` folders several levels down
const uris = workspaceUris.map(workspaceUri => {
const path = workspaceUri.path;
return workspaceUri.with({ path: `${path !== '/' ? path : ''}/node_modules` });
});
return this.fileService.resolveAll(uris.map(resource => ({ resource }))).then(
results => {
const names = (<IFileStat[]>[]).concat(...results.map(result => result.success ? (result.stat!.children || []) : [])).map(c => c.name);
const referencesAzure = WorkspaceTags.searchArray(names, /azure/i);
if (referencesAzure) {
tags['node'] = true;
}
return tags;
},
err => {
return tags;
});
}
private static searchArray(arr: string[], regEx: RegExp): boolean | undefined {
return arr.some(v => v.search(regEx) > -1) || undefined;
}
/* __GDPR__FRAGMENT__
"AzureTags" : {
"java" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }
}
*/
private reportAzureJava(workspaceUris: URI[], tags: Tags): Promise<Tags> {
return Promise.all(workspaceUris.map(workspaceUri => {
const path = workspaceUri.path;
const uri = workspaceUri.with({ path: `${path !== '/' ? path : ''}/pom.xml` });
return this.fileService.exists(uri).then(exists => {
if (!exists) {
return false;
}
return this.textFileService.read(uri, { acceptTextOnly: true }).then(
content => !!content.value.match(/azure/i),
err => false
);
});
})).then(javas => {
if (javas.indexOf(true) !== -1) {
tags['java'] = true;
}
return tags;
});
}
private reportAzure(uris: URI[]) {
const tags: Tags = Object.create(null);
this.reportAzureNode(uris, tags).then((tags) => {
return this.reportAzureJava(uris, tags);
}).then((tags) => {
if (Object.keys(tags).length) {
/* __GDPR__
"workspace.azure" : {
"owner": "lramos15",
"${include}": [
"${AzureTags}"
]
}
*/
this.telemetryService.publicLog('workspace.azure', tags);
}
}).then(undefined, onUnexpectedError);
}
private reportCloudStats(): void {
const uris = this.contextService.getWorkspace().folders.map(folder => folder.uri);
if (uris.length && this.fileService) {
this.reportRemoteDomains(uris);
this.reportRemotes(uris);
this.reportAzure(uris);
}
}
private reportProxyStats() {
const downloadUrl = this.productService.downloadUrl;
if (!downloadUrl) {
return;
}
this.requestService.resolveProxy(downloadUrl)
.then(proxy => {
let type = proxy ? String(proxy).trim().split(/\s+/, 1)[0] : 'EMPTY';
if (['DIRECT', 'PROXY', 'HTTPS', 'SOCKS', 'EMPTY'].indexOf(type) === -1) {
type = 'UNKNOWN';
}
}).then(undefined, onUnexpectedError);
}
}
| src/vs/workbench/contrib/tags/electron-sandbox/workspaceTags.ts | 0 | https://github.com/microsoft/vscode/commit/48a9149e6ad2cbc0f7ebfdb2ce6143627c077d1e | [
0.00017584128363523632,
0.0001719688589219004,
0.00016308421618305147,
0.00017250212840735912,
0.000002890482846851228
] |
{
"id": 5,
"code_window": [
"\n",
"\t\tconst session = inlineChatSessionService.getSession(editor, editor.getModel()!.uri);\n",
"\t\tassert.ok(session);\n",
"\t\tassert.deepStrictEqual(session.wholeRange.value, new Range(1, 1, 1, 6));\n",
"\n",
"\t\tawait ctrl.cancelSession();\n",
"\t\td.dispose();\n",
"\t});\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tassert.deepStrictEqual(session.wholeRange.value, new Range(1, 1, 1, 3));\n"
],
"file_path": "src/vs/workbench/contrib/inlineChat/test/browser/inlineChatController.test.ts",
"type": "replace",
"edit_start_line_idx": 236
} | /*---------------------------------------------------------------------------------------------
* 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.998358428478241,
0.13694308698177338,
0.00016345690528396517,
0.0017425266560167074,
0.33384639024734497
] |
{
"id": 5,
"code_window": [
"\n",
"\t\tconst session = inlineChatSessionService.getSession(editor, editor.getModel()!.uri);\n",
"\t\tassert.ok(session);\n",
"\t\tassert.deepStrictEqual(session.wholeRange.value, new Range(1, 1, 1, 6));\n",
"\n",
"\t\tawait ctrl.cancelSession();\n",
"\t\td.dispose();\n",
"\t});\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tassert.deepStrictEqual(session.wholeRange.value, new Range(1, 1, 1, 3));\n"
],
"file_path": "src/vs/workbench/contrib/inlineChat/test/browser/inlineChatController.test.ts",
"type": "replace",
"edit_start_line_idx": 236
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { compareBy, equals, numberComparator, tieBreakComparators } from 'vs/base/common/arrays';
import { BugIndicatingError } from 'vs/base/common/errors';
import { splitLines } from 'vs/base/common/strings';
import { Constants } from 'vs/base/common/uint';
import { Position } from 'vs/editor/common/core/position';
import { Range } from 'vs/editor/common/core/range';
import { ITextModel } from 'vs/editor/common/model';
import { LineRangeEdit, RangeEdit } from 'vs/workbench/contrib/mergeEditor/browser/model/editing';
import { LineRange } from 'vs/workbench/contrib/mergeEditor/browser/model/lineRange';
import { DetailedLineRangeMapping, MappingAlignment } from 'vs/workbench/contrib/mergeEditor/browser/model/mapping';
import { concatArrays } from 'vs/workbench/contrib/mergeEditor/browser/utils';
/**
* Describes modifications in input 1 and input 2 for a specific range in base.
*
* The UI offers a mechanism to either apply all changes from input 1 or input 2 or both.
*
* Immutable.
*/
export class ModifiedBaseRange {
public static fromDiffs(
diffs1: readonly DetailedLineRangeMapping[],
diffs2: readonly DetailedLineRangeMapping[],
baseTextModel: ITextModel,
input1TextModel: ITextModel,
input2TextModel: ITextModel
): ModifiedBaseRange[] {
const alignments = MappingAlignment.compute(diffs1, diffs2);
return alignments.map(
(a) => new ModifiedBaseRange(
a.inputRange,
baseTextModel,
a.output1Range,
input1TextModel,
a.output1LineMappings,
a.output2Range,
input2TextModel,
a.output2LineMappings
)
);
}
public readonly input1CombinedDiff = DetailedLineRangeMapping.join(this.input1Diffs);
public readonly input2CombinedDiff = DetailedLineRangeMapping.join(this.input2Diffs);
public readonly isEqualChange = equals(this.input1Diffs, this.input2Diffs, (a, b) => a.getLineEdit().equals(b.getLineEdit()));
constructor(
public readonly baseRange: LineRange,
public readonly baseTextModel: ITextModel,
public readonly input1Range: LineRange,
public readonly input1TextModel: ITextModel,
/**
* From base to input1
*/
public readonly input1Diffs: readonly DetailedLineRangeMapping[],
public readonly input2Range: LineRange,
public readonly input2TextModel: ITextModel,
/**
* From base to input2
*/
public readonly input2Diffs: readonly DetailedLineRangeMapping[]
) {
if (this.input1Diffs.length === 0 && this.input2Diffs.length === 0) {
throw new BugIndicatingError('must have at least one diff');
}
}
public getInputRange(inputNumber: 1 | 2): LineRange {
return inputNumber === 1 ? this.input1Range : this.input2Range;
}
public getInputCombinedDiff(inputNumber: 1 | 2): DetailedLineRangeMapping | undefined {
return inputNumber === 1 ? this.input1CombinedDiff : this.input2CombinedDiff;
}
public getInputDiffs(inputNumber: 1 | 2): readonly DetailedLineRangeMapping[] {
return inputNumber === 1 ? this.input1Diffs : this.input2Diffs;
}
public get isConflicting(): boolean {
return this.input1Diffs.length > 0 && this.input2Diffs.length > 0;
}
public get canBeCombined(): boolean {
return this.smartCombineInputs(1) !== undefined;
}
public get isOrderRelevant(): boolean {
const input1 = this.smartCombineInputs(1);
const input2 = this.smartCombineInputs(2);
if (!input1 || !input2) {
return false;
}
return !input1.equals(input2);
}
public getEditForBase(state: ModifiedBaseRangeState): { edit: LineRangeEdit | undefined; effectiveState: ModifiedBaseRangeState } {
const diffs: { diff: DetailedLineRangeMapping; inputNumber: InputNumber }[] = [];
if (state.includesInput1 && this.input1CombinedDiff) {
diffs.push({ diff: this.input1CombinedDiff, inputNumber: 1 });
}
if (state.includesInput2 && this.input2CombinedDiff) {
diffs.push({ diff: this.input2CombinedDiff, inputNumber: 2 });
}
if (diffs.length === 0) {
return { edit: undefined, effectiveState: ModifiedBaseRangeState.base };
}
if (diffs.length === 1) {
return { edit: diffs[0].diff.getLineEdit(), effectiveState: ModifiedBaseRangeState.base.withInputValue(diffs[0].inputNumber, true, false) };
}
if (state.kind !== ModifiedBaseRangeStateKind.both) {
throw new BugIndicatingError();
}
const smartCombinedEdit = state.smartCombination ? this.smartCombineInputs(state.firstInput) : this.dumbCombineInputs(state.firstInput);
if (smartCombinedEdit) {
return { edit: smartCombinedEdit, effectiveState: state };
}
return {
edit: diffs[getOtherInputNumber(state.firstInput) - 1].diff.getLineEdit(),
effectiveState: ModifiedBaseRangeState.base.withInputValue(
getOtherInputNumber(state.firstInput),
true,
false
),
};
}
private smartInput1LineRangeEdit: LineRangeEdit | undefined | null = null;
private smartInput2LineRangeEdit: LineRangeEdit | undefined | null = null;
private smartCombineInputs(firstInput: 1 | 2): LineRangeEdit | undefined {
if (firstInput === 1 && this.smartInput1LineRangeEdit !== null) {
return this.smartInput1LineRangeEdit;
} else if (firstInput === 2 && this.smartInput2LineRangeEdit !== null) {
return this.smartInput2LineRangeEdit;
}
const combinedDiffs = concatArrays(
this.input1Diffs.flatMap((diffs) =>
diffs.rangeMappings.map((diff) => ({ diff, input: 1 as const }))
),
this.input2Diffs.flatMap((diffs) =>
diffs.rangeMappings.map((diff) => ({ diff, input: 2 as const }))
)
).sort(
tieBreakComparators(
compareBy((d) => d.diff.inputRange, Range.compareRangesUsingStarts),
compareBy((d) => (d.input === firstInput ? 1 : 2), numberComparator)
)
);
const sortedEdits = combinedDiffs.map(d => {
const sourceTextModel = d.input === 1 ? this.input1TextModel : this.input2TextModel;
return new RangeEdit(d.diff.inputRange, sourceTextModel.getValueInRange(d.diff.outputRange));
});
const result = editsToLineRangeEdit(this.baseRange, sortedEdits, this.baseTextModel);
if (firstInput === 1) {
this.smartInput1LineRangeEdit = result;
} else {
this.smartInput2LineRangeEdit = result;
}
return result;
}
private dumbInput1LineRangeEdit: LineRangeEdit | undefined | null = null;
private dumbInput2LineRangeEdit: LineRangeEdit | undefined | null = null;
private dumbCombineInputs(firstInput: 1 | 2): LineRangeEdit | undefined {
if (firstInput === 1 && this.dumbInput1LineRangeEdit !== null) {
return this.dumbInput1LineRangeEdit;
} else if (firstInput === 2 && this.dumbInput2LineRangeEdit !== null) {
return this.dumbInput2LineRangeEdit;
}
let input1Lines = this.input1Range.getLines(this.input1TextModel);
let input2Lines = this.input2Range.getLines(this.input2TextModel);
if (firstInput === 2) {
[input1Lines, input2Lines] = [input2Lines, input1Lines];
}
const result = new LineRangeEdit(this.baseRange, input1Lines.concat(input2Lines));
if (firstInput === 1) {
this.dumbInput1LineRangeEdit = result;
} else {
this.dumbInput2LineRangeEdit = result;
}
return result;
}
}
function editsToLineRangeEdit(range: LineRange, sortedEdits: RangeEdit[], textModel: ITextModel): LineRangeEdit | undefined {
let text = '';
const startsLineBefore = range.startLineNumber > 1;
let currentPosition = startsLineBefore
? new Position(
range.startLineNumber - 1,
textModel.getLineMaxColumn(range.startLineNumber - 1)
)
: new Position(range.startLineNumber, 1);
for (const edit of sortedEdits) {
const diffStart = edit.range.getStartPosition();
if (!currentPosition.isBeforeOrEqual(diffStart)) {
return undefined;
}
let originalText = textModel.getValueInRange(Range.fromPositions(currentPosition, diffStart));
if (diffStart.lineNumber > textModel.getLineCount()) {
// assert diffStart.lineNumber === textModel.getLineCount() + 1
// getValueInRange doesn't include this virtual line break, as the document ends the line before.
// endsLineAfter will be false.
originalText += '\n';
}
text += originalText;
text += edit.newText;
currentPosition = edit.range.getEndPosition();
}
const endsLineAfter = range.endLineNumberExclusive <= textModel.getLineCount();
const end = endsLineAfter ? new Position(
range.endLineNumberExclusive,
1
) : new Position(range.endLineNumberExclusive - 1, Constants.MAX_SAFE_SMALL_INTEGER);
const originalText = textModel.getValueInRange(
Range.fromPositions(currentPosition, end)
);
text += originalText;
const lines = splitLines(text);
if (startsLineBefore) {
if (lines[0] !== '') {
return undefined;
}
lines.shift();
}
if (endsLineAfter) {
if (lines[lines.length - 1] !== '') {
return undefined;
}
lines.pop();
}
return new LineRangeEdit(range, lines);
}
export enum ModifiedBaseRangeStateKind {
base,
input1,
input2,
both,
unrecognized,
}
export type InputNumber = 1 | 2;
export function getOtherInputNumber(inputNumber: InputNumber): InputNumber {
return inputNumber === 1 ? 2 : 1;
}
export abstract class AbstractModifiedBaseRangeState {
constructor() { }
abstract get kind(): ModifiedBaseRangeStateKind;
public get includesInput1(): boolean { return false; }
public get includesInput2(): boolean { return false; }
public includesInput(inputNumber: InputNumber): boolean {
return inputNumber === 1 ? this.includesInput1 : this.includesInput2;
}
public isInputIncluded(inputNumber: InputNumber): boolean {
return inputNumber === 1 ? this.includesInput1 : this.includesInput2;
}
public abstract toString(): string;
public abstract swap(): ModifiedBaseRangeState;
public abstract withInputValue(inputNumber: InputNumber, value: boolean, smartCombination?: boolean): ModifiedBaseRangeState;
public abstract equals(other: ModifiedBaseRangeState): boolean;
public toggle(inputNumber: InputNumber) {
return this.withInputValue(inputNumber, !this.includesInput(inputNumber), true);
}
public getInput(inputNumber: 1 | 2): InputState {
if (!this.isInputIncluded(inputNumber)) {
return InputState.excluded;
}
return InputState.first;
}
}
export class ModifiedBaseRangeStateBase extends AbstractModifiedBaseRangeState {
override get kind(): ModifiedBaseRangeStateKind.base { return ModifiedBaseRangeStateKind.base; }
public override toString(): string { return 'base'; }
public override swap(): ModifiedBaseRangeState { return this; }
public override withInputValue(inputNumber: InputNumber, value: boolean, smartCombination: boolean = false): ModifiedBaseRangeState {
if (inputNumber === 1) {
return value ? new ModifiedBaseRangeStateInput1() : this;
} else {
return value ? new ModifiedBaseRangeStateInput2() : this;
}
}
public override equals(other: ModifiedBaseRangeState): boolean {
return other.kind === ModifiedBaseRangeStateKind.base;
}
}
export class ModifiedBaseRangeStateInput1 extends AbstractModifiedBaseRangeState {
override get kind(): ModifiedBaseRangeStateKind.input1 { return ModifiedBaseRangeStateKind.input1; }
override get includesInput1(): boolean { return true; }
public toString(): string { return '1✓'; }
public override swap(): ModifiedBaseRangeState { return new ModifiedBaseRangeStateInput2(); }
public override withInputValue(inputNumber: InputNumber, value: boolean, smartCombination: boolean = false): ModifiedBaseRangeState {
if (inputNumber === 1) {
return value ? this : new ModifiedBaseRangeStateBase();
} else {
return value ? new ModifiedBaseRangeStateBoth(1, smartCombination) : new ModifiedBaseRangeStateInput2();
}
}
public override equals(other: ModifiedBaseRangeState): boolean {
return other.kind === ModifiedBaseRangeStateKind.input1;
}
}
export class ModifiedBaseRangeStateInput2 extends AbstractModifiedBaseRangeState {
override get kind(): ModifiedBaseRangeStateKind.input2 { return ModifiedBaseRangeStateKind.input2; }
override get includesInput2(): boolean { return true; }
public toString(): string { return '2✓'; }
public override swap(): ModifiedBaseRangeState { return new ModifiedBaseRangeStateInput1(); }
public withInputValue(inputNumber: InputNumber, value: boolean, smartCombination: boolean = false): ModifiedBaseRangeState {
if (inputNumber === 2) {
return value ? this : new ModifiedBaseRangeStateBase();
} else {
return value ? new ModifiedBaseRangeStateBoth(2, smartCombination) : new ModifiedBaseRangeStateInput2();
}
}
public override equals(other: ModifiedBaseRangeState): boolean {
return other.kind === ModifiedBaseRangeStateKind.input2;
}
}
export class ModifiedBaseRangeStateBoth extends AbstractModifiedBaseRangeState {
constructor(
public readonly firstInput: InputNumber,
public readonly smartCombination: boolean
) {
super();
}
override get kind(): ModifiedBaseRangeStateKind.both { return ModifiedBaseRangeStateKind.both; }
override get includesInput1(): boolean { return true; }
override get includesInput2(): boolean { return true; }
public toString(): string {
return '2✓';
}
public override swap(): ModifiedBaseRangeState { return new ModifiedBaseRangeStateBoth(getOtherInputNumber(this.firstInput), this.smartCombination); }
public withInputValue(inputNumber: InputNumber, value: boolean, smartCombination: boolean = false): ModifiedBaseRangeState {
if (value) {
return this;
}
return inputNumber === 1 ? new ModifiedBaseRangeStateInput2() : new ModifiedBaseRangeStateInput1();
}
public override equals(other: ModifiedBaseRangeState): boolean {
return other.kind === ModifiedBaseRangeStateKind.both && this.firstInput === other.firstInput && this.smartCombination === other.smartCombination;
}
public override getInput(inputNumber: 1 | 2): InputState {
return inputNumber === this.firstInput ? InputState.first : InputState.second;
}
}
export class ModifiedBaseRangeStateUnrecognized extends AbstractModifiedBaseRangeState {
override get kind(): ModifiedBaseRangeStateKind.unrecognized { return ModifiedBaseRangeStateKind.unrecognized; }
public override toString(): string { return 'unrecognized'; }
public override swap(): ModifiedBaseRangeState { return this; }
public withInputValue(inputNumber: InputNumber, value: boolean, smartCombination: boolean = false): ModifiedBaseRangeState {
if (!value) {
return this;
}
return inputNumber === 1 ? new ModifiedBaseRangeStateInput1() : new ModifiedBaseRangeStateInput2();
}
public override equals(other: ModifiedBaseRangeState): boolean {
return other.kind === ModifiedBaseRangeStateKind.unrecognized;
}
}
export type ModifiedBaseRangeState = ModifiedBaseRangeStateBase | ModifiedBaseRangeStateInput1 | ModifiedBaseRangeStateInput2 | ModifiedBaseRangeStateInput2 | ModifiedBaseRangeStateBoth | ModifiedBaseRangeStateUnrecognized;
export namespace ModifiedBaseRangeState {
export const base = new ModifiedBaseRangeStateBase();
export const unrecognized = new ModifiedBaseRangeStateUnrecognized();
}
export const enum InputState {
excluded = 0,
first = 1,
second = 2,
unrecognized = 3
}
| src/vs/workbench/contrib/mergeEditor/browser/model/modifiedBaseRange.ts | 0 | https://github.com/microsoft/vscode/commit/48a9149e6ad2cbc0f7ebfdb2ce6143627c077d1e | [
0.00020336336456239223,
0.00017298033344559371,
0.00016485042579006404,
0.00017261681205127388,
0.00000562651666768943
] |
{
"id": 5,
"code_window": [
"\n",
"\t\tconst session = inlineChatSessionService.getSession(editor, editor.getModel()!.uri);\n",
"\t\tassert.ok(session);\n",
"\t\tassert.deepStrictEqual(session.wholeRange.value, new Range(1, 1, 1, 6));\n",
"\n",
"\t\tawait ctrl.cancelSession();\n",
"\t\td.dispose();\n",
"\t});\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tassert.deepStrictEqual(session.wholeRange.value, new Range(1, 1, 1, 3));\n"
],
"file_path": "src/vs/workbench/contrib/inlineChat/test/browser/inlineChatController.test.ts",
"type": "replace",
"edit_start_line_idx": 236
} | # THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.
# yarn lockfile v1
| extensions/clojure/yarn.lock | 0 | https://github.com/microsoft/vscode/commit/48a9149e6ad2cbc0f7ebfdb2ce6143627c077d1e | [
0.0001746717025525868,
0.0001746717025525868,
0.0001746717025525868,
0.0001746717025525868,
0
] |
{
"id": 5,
"code_window": [
"\n",
"\t\tconst session = inlineChatSessionService.getSession(editor, editor.getModel()!.uri);\n",
"\t\tassert.ok(session);\n",
"\t\tassert.deepStrictEqual(session.wholeRange.value, new Range(1, 1, 1, 6));\n",
"\n",
"\t\tawait ctrl.cancelSession();\n",
"\t\td.dispose();\n",
"\t});\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tassert.deepStrictEqual(session.wholeRange.value, new Range(1, 1, 1, 3));\n"
],
"file_path": "src/vs/workbench/contrib/inlineChat/test/browser/inlineChatController.test.ts",
"type": "replace",
"edit_start_line_idx": 236
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { UriComponents } from 'vs/base/common/uri';
import { IExtensionDescription } from 'vs/platform/extensions/common/extensions';
import type { Dto } from 'vs/workbench/services/extensions/common/proxyIdentifier';
export interface ITaskDefinitionDTO {
type: string;
[name: string]: any;
}
export interface ITaskPresentationOptionsDTO {
reveal?: number;
echo?: boolean;
focus?: boolean;
panel?: number;
showReuseMessage?: boolean;
clear?: boolean;
group?: string;
close?: boolean;
}
export interface IRunOptionsDTO {
reevaluateOnRerun?: boolean;
}
export interface IExecutionOptionsDTO {
cwd?: string;
env?: { [key: string]: string };
}
export interface IProcessExecutionOptionsDTO extends IExecutionOptionsDTO {
}
export interface IProcessExecutionDTO {
process: string;
args: string[];
options?: IProcessExecutionOptionsDTO;
}
export interface IShellQuotingOptionsDTO {
escape?: string | {
escapeChar: string;
charsToEscape: string;
};
strong?: string;
weak?: string;
}
export interface IShellExecutionOptionsDTO extends IExecutionOptionsDTO {
executable?: string;
shellArgs?: string[];
shellQuoting?: IShellQuotingOptionsDTO;
}
export interface IShellQuotedStringDTO {
value: string;
quoting: number;
}
export interface IShellExecutionDTO {
commandLine?: string;
command?: string | IShellQuotedStringDTO;
args?: Array<string | IShellQuotedStringDTO>;
options?: IShellExecutionOptionsDTO;
}
export interface ICustomExecutionDTO {
customExecution: 'customExecution';
}
export interface ITaskSourceDTO {
label: string;
extensionId?: string;
scope?: number | UriComponents;
color?: string;
icon?: string;
hide?: boolean;
}
export interface ITaskHandleDTO {
id: string;
workspaceFolder: UriComponents | string;
}
export interface ITaskGroupDTO {
isDefault?: boolean;
_id: string;
}
export interface ITaskDTO {
_id: string;
name?: string;
execution: IProcessExecutionDTO | IShellExecutionDTO | ICustomExecutionDTO | undefined;
definition: ITaskDefinitionDTO;
isBackground?: boolean;
source: ITaskSourceDTO;
group?: ITaskGroupDTO;
detail?: string;
presentationOptions?: ITaskPresentationOptionsDTO;
problemMatchers: string[];
hasDefinedMatchers: boolean;
runOptions?: IRunOptionsDTO;
}
export interface ITaskSetDTO {
tasks: ITaskDTO[];
extension: Dto<IExtensionDescription>;
}
export interface ITaskExecutionDTO {
id: string;
task: ITaskDTO | undefined;
}
export interface ITaskProcessStartedDTO {
id: string;
processId: number;
}
export interface ITaskProcessEndedDTO {
id: string;
exitCode: number | undefined;
}
export interface ITaskFilterDTO {
version?: string;
type?: string;
}
export interface ITaskSystemInfoDTO {
scheme: string;
authority: string;
platform: string;
}
| src/vs/workbench/api/common/shared/tasks.ts | 0 | https://github.com/microsoft/vscode/commit/48a9149e6ad2cbc0f7ebfdb2ce6143627c077d1e | [
0.00018468062626197934,
0.00017495642532594502,
0.0001685310562606901,
0.00017445889534428716,
0.0000043706736505555455
] |
{
"id": 6,
"code_window": [
"\n",
"\t\tawait p;\n",
"\n",
"\t\tconst session = inlineChatSessionService.getSession(editor, editor.getModel()!.uri);\n",
"\t\tassert.ok(session);\n",
"\t\tassert.deepStrictEqual(session.wholeRange.value, new Range(1, 1, 1, 11));\n",
"\n",
"\t\teditor.setSelection(new Range(2, 1, 2, 1));\n",
"\t\teditor.trigger('test', 'type', { text: 'a' });\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tassert.deepStrictEqual(session.wholeRange.value, new Range(1, 1, 1, 6));\n"
],
"file_path": "src/vs/workbench/contrib/inlineChat/test/browser/inlineChatController.test.ts",
"type": "replace",
"edit_start_line_idx": 254
} | /*---------------------------------------------------------------------------------------------
* 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.9984182119369507,
0.09923316538333893,
0.0001629744510864839,
0.0021262532100081444,
0.2726459801197052
] |
{
"id": 6,
"code_window": [
"\n",
"\t\tawait p;\n",
"\n",
"\t\tconst session = inlineChatSessionService.getSession(editor, editor.getModel()!.uri);\n",
"\t\tassert.ok(session);\n",
"\t\tassert.deepStrictEqual(session.wholeRange.value, new Range(1, 1, 1, 11));\n",
"\n",
"\t\teditor.setSelection(new Range(2, 1, 2, 1));\n",
"\t\teditor.trigger('test', 'type', { text: 'a' });\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tassert.deepStrictEqual(session.wholeRange.value, new Range(1, 1, 1, 6));\n"
],
"file_path": "src/vs/workbench/contrib/inlineChat/test/browser/inlineChatController.test.ts",
"type": "replace",
"edit_start_line_idx": 254
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { InstantiationType, registerSingleton } from 'vs/platform/instantiation/common/extensions';
import { IWorkspacesService, IWorkspaceFolderCreationData, IEnterWorkspaceResult, IRecentlyOpened, restoreRecentlyOpened, IRecent, isRecentFile, isRecentFolder, toStoreData, IStoredWorkspaceFolder, getStoredWorkspaceFolder, IStoredWorkspace, isRecentWorkspace } from 'vs/platform/workspaces/common/workspaces';
import { URI } from 'vs/base/common/uri';
import { Emitter } from 'vs/base/common/event';
import { IStorageService, StorageScope, StorageTarget } from 'vs/platform/storage/common/storage';
import { isTemporaryWorkspace, IWorkspaceContextService, IWorkspaceFoldersChangeEvent, IWorkspaceIdentifier, WorkbenchState, WORKSPACE_EXTENSION } from 'vs/platform/workspace/common/workspace';
import { ILogService } from 'vs/platform/log/common/log';
import { Disposable, DisposableStore } from 'vs/base/common/lifecycle';
import { getWorkspaceIdentifier } from 'vs/workbench/services/workspaces/browser/workspaces';
import { IFileService, FileOperationError, FileOperationResult } from 'vs/platform/files/common/files';
import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService';
import { joinPath } from 'vs/base/common/resources';
import { VSBuffer } from 'vs/base/common/buffer';
import { IUriIdentityService } from 'vs/platform/uriIdentity/common/uriIdentity';
import { IWorkspaceBackupInfo, IFolderBackupInfo } from 'vs/platform/backup/common/backup';
import { Schemas } from 'vs/base/common/network';
export class BrowserWorkspacesService extends Disposable implements IWorkspacesService {
static readonly RECENTLY_OPENED_KEY = 'recently.opened';
declare readonly _serviceBrand: undefined;
private readonly _onRecentlyOpenedChange = this._register(new Emitter<void>());
readonly onDidChangeRecentlyOpened = this._onRecentlyOpenedChange.event;
constructor(
@IStorageService private readonly storageService: IStorageService,
@IWorkspaceContextService private readonly contextService: IWorkspaceContextService,
@ILogService private readonly logService: ILogService,
@IFileService private readonly fileService: IFileService,
@IWorkbenchEnvironmentService private readonly environmentService: IWorkbenchEnvironmentService,
@IUriIdentityService private readonly uriIdentityService: IUriIdentityService,
) {
super();
// Opening a workspace should push it as most
// recently used to the workspaces history
this.addWorkspaceToRecentlyOpened();
this.registerListeners();
}
private registerListeners(): void {
// Storage
this._register(this.storageService.onDidChangeValue(StorageScope.APPLICATION, BrowserWorkspacesService.RECENTLY_OPENED_KEY, this._register(new DisposableStore()))(() => this._onRecentlyOpenedChange.fire()));
// Workspace
this._register(this.contextService.onDidChangeWorkspaceFolders(e => this.onDidChangeWorkspaceFolders(e)));
}
private onDidChangeWorkspaceFolders(e: IWorkspaceFoldersChangeEvent): void {
if (!isTemporaryWorkspace(this.contextService.getWorkspace())) {
return;
}
// When in a temporary workspace, make sure to track folder changes
// in the history so that these can later be restored.
for (const folder of e.added) {
this.addRecentlyOpened([{ folderUri: folder.uri }]);
}
}
private addWorkspaceToRecentlyOpened(): void {
const workspace = this.contextService.getWorkspace();
const remoteAuthority = this.environmentService.remoteAuthority;
switch (this.contextService.getWorkbenchState()) {
case WorkbenchState.FOLDER:
this.addRecentlyOpened([{ folderUri: workspace.folders[0].uri, remoteAuthority }]);
break;
case WorkbenchState.WORKSPACE:
this.addRecentlyOpened([{ workspace: { id: workspace.id, configPath: workspace.configuration! }, remoteAuthority }]);
break;
}
}
//#region Workspaces History
async getRecentlyOpened(): Promise<IRecentlyOpened> {
const recentlyOpenedRaw = this.storageService.get(BrowserWorkspacesService.RECENTLY_OPENED_KEY, StorageScope.APPLICATION);
if (recentlyOpenedRaw) {
const recentlyOpened = restoreRecentlyOpened(JSON.parse(recentlyOpenedRaw), this.logService);
recentlyOpened.workspaces = recentlyOpened.workspaces.filter(recent => {
// In web, unless we are in a temporary workspace, we cannot support
// to switch to local folders because this would require a window
// reload and local file access only works with explicit user gesture
// from the current session.
if (isRecentFolder(recent) && recent.folderUri.scheme === Schemas.file && !isTemporaryWorkspace(this.contextService.getWorkspace())) {
return false;
}
// Never offer temporary workspaces in the history
if (isRecentWorkspace(recent) && isTemporaryWorkspace(recent.workspace.configPath)) {
return false;
}
return true;
});
return recentlyOpened;
}
return { workspaces: [], files: [] };
}
async addRecentlyOpened(recents: IRecent[]): Promise<void> {
const recentlyOpened = await this.getRecentlyOpened();
for (const recent of recents) {
if (isRecentFile(recent)) {
this.doRemoveRecentlyOpened(recentlyOpened, [recent.fileUri]);
recentlyOpened.files.unshift(recent);
} else if (isRecentFolder(recent)) {
this.doRemoveRecentlyOpened(recentlyOpened, [recent.folderUri]);
recentlyOpened.workspaces.unshift(recent);
} else {
this.doRemoveRecentlyOpened(recentlyOpened, [recent.workspace.configPath]);
recentlyOpened.workspaces.unshift(recent);
}
}
return this.saveRecentlyOpened(recentlyOpened);
}
async removeRecentlyOpened(paths: URI[]): Promise<void> {
const recentlyOpened = await this.getRecentlyOpened();
this.doRemoveRecentlyOpened(recentlyOpened, paths);
return this.saveRecentlyOpened(recentlyOpened);
}
private doRemoveRecentlyOpened(recentlyOpened: IRecentlyOpened, paths: URI[]): void {
recentlyOpened.files = recentlyOpened.files.filter(file => {
return !paths.some(path => path.toString() === file.fileUri.toString());
});
recentlyOpened.workspaces = recentlyOpened.workspaces.filter(workspace => {
return !paths.some(path => path.toString() === (isRecentFolder(workspace) ? workspace.folderUri.toString() : workspace.workspace.configPath.toString()));
});
}
private async saveRecentlyOpened(data: IRecentlyOpened): Promise<void> {
return this.storageService.store(BrowserWorkspacesService.RECENTLY_OPENED_KEY, JSON.stringify(toStoreData(data)), StorageScope.APPLICATION, StorageTarget.USER);
}
async clearRecentlyOpened(): Promise<void> {
this.storageService.remove(BrowserWorkspacesService.RECENTLY_OPENED_KEY, StorageScope.APPLICATION);
}
//#endregion
//#region Workspace Management
async enterWorkspace(workspaceUri: URI): Promise<IEnterWorkspaceResult | undefined> {
return { workspace: await this.getWorkspaceIdentifier(workspaceUri) };
}
async createUntitledWorkspace(folders?: IWorkspaceFolderCreationData[], remoteAuthority?: string): Promise<IWorkspaceIdentifier> {
const randomId = (Date.now() + Math.round(Math.random() * 1000)).toString();
const newUntitledWorkspacePath = joinPath(this.environmentService.untitledWorkspacesHome, `Untitled-${randomId}.${WORKSPACE_EXTENSION}`);
// Build array of workspace folders to store
const storedWorkspaceFolder: IStoredWorkspaceFolder[] = [];
if (folders) {
for (const folder of folders) {
storedWorkspaceFolder.push(getStoredWorkspaceFolder(folder.uri, true, folder.name, this.environmentService.untitledWorkspacesHome, this.uriIdentityService.extUri));
}
}
// Store at untitled workspaces location
const storedWorkspace: IStoredWorkspace = { folders: storedWorkspaceFolder, remoteAuthority };
await this.fileService.writeFile(newUntitledWorkspacePath, VSBuffer.fromString(JSON.stringify(storedWorkspace, null, '\t')));
return this.getWorkspaceIdentifier(newUntitledWorkspacePath);
}
async deleteUntitledWorkspace(workspace: IWorkspaceIdentifier): Promise<void> {
try {
await this.fileService.del(workspace.configPath);
} catch (error) {
if ((<FileOperationError>error).fileOperationResult !== FileOperationResult.FILE_NOT_FOUND) {
throw error; // re-throw any other error than file not found which is OK
}
}
}
async getWorkspaceIdentifier(workspaceUri: URI): Promise<IWorkspaceIdentifier> {
return getWorkspaceIdentifier(workspaceUri);
}
//#endregion
//#region Dirty Workspaces
async getDirtyWorkspaces(): Promise<Array<IWorkspaceBackupInfo | IFolderBackupInfo>> {
return []; // Currently not supported in web
}
//#endregion
}
registerSingleton(IWorkspacesService, BrowserWorkspacesService, InstantiationType.Delayed);
| src/vs/workbench/services/workspaces/browser/workspacesService.ts | 0 | https://github.com/microsoft/vscode/commit/48a9149e6ad2cbc0f7ebfdb2ce6143627c077d1e | [
0.00017671767272986472,
0.00017267126531805843,
0.00016186636639758945,
0.00017385103274136782,
0.0000032120115065481514
] |
{
"id": 6,
"code_window": [
"\n",
"\t\tawait p;\n",
"\n",
"\t\tconst session = inlineChatSessionService.getSession(editor, editor.getModel()!.uri);\n",
"\t\tassert.ok(session);\n",
"\t\tassert.deepStrictEqual(session.wholeRange.value, new Range(1, 1, 1, 11));\n",
"\n",
"\t\teditor.setSelection(new Range(2, 1, 2, 1));\n",
"\t\teditor.trigger('test', 'type', { text: 'a' });\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tassert.deepStrictEqual(session.wholeRange.value, new Range(1, 1, 1, 6));\n"
],
"file_path": "src/vs/workbench/contrib/inlineChat/test/browser/inlineChatController.test.ts",
"type": "replace",
"edit_start_line_idx": 254
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { URI } from 'vs/base/common/uri';
import { IUriIdentityService } from 'vs/platform/uriIdentity/common/uriIdentity';
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
import { ITerminalLinkDetector, ITerminalLinkResolver, ITerminalSimpleLink, TerminalBuiltinLinkType } from 'vs/workbench/contrib/terminalContrib/links/browser/links';
import { convertLinkRangeToBuffer, getXtermLineContent } from 'vs/workbench/contrib/terminalContrib/links/browser/terminalLinkHelpers';
import type { IBufferLine, Terminal } from '@xterm/xterm';
import { ITerminalProcessManager } from 'vs/workbench/contrib/terminal/common/terminal';
import { ITerminalBackend, ITerminalLogService } from 'vs/platform/terminal/common/terminal';
const enum Constants {
/**
* The max line length to try extract word links from.
*/
MaxLineLength = 2000,
/**
* The maximum length of a link to resolve against the file system. This limit is put in place
* to avoid sending excessive data when remote connections are in place.
*/
MaxResolvedLinkLength = 1024,
}
const lineNumberPrefixMatchers = [
// Ripgrep:
// /some/file
// 16:searchresult
// 16: searchresult
// Eslint:
// /some/file
// 16:5 error ...
/^ *(?<link>(?<line>\d+):(?<col>\d+)?)/
];
const gitDiffMatchers = [
// --- a/some/file
// +++ b/some/file
// @@ -8,11 +8,11 @@ file content...
/^(?<link>@@ .+ \+(?<toFileLine>\d+),(?<toFileCount>\d+) @@)/
];
export class TerminalMultiLineLinkDetector implements ITerminalLinkDetector {
static id = 'multiline';
// This was chosen as a reasonable maximum line length given the tradeoff between performance
// and how likely it is to encounter such a large line length. Some useful reference points:
// - Window old max length: 260 ($MAX_PATH)
// - Linux max length: 4096 ($PATH_MAX)
readonly maxLinkLength = 500;
constructor(
readonly xterm: Terminal,
private readonly _processManager: Pick<ITerminalProcessManager, 'initialCwd' | 'os' | 'remoteAuthority' | 'userHome'> & { backend?: Pick<ITerminalBackend, 'getWslPath'> },
private readonly _linkResolver: ITerminalLinkResolver,
@ITerminalLogService private readonly _logService: ITerminalLogService,
@IUriIdentityService private readonly _uriIdentityService: IUriIdentityService,
@IWorkspaceContextService private readonly _workspaceContextService: IWorkspaceContextService
) {
}
async detect(lines: IBufferLine[], startLine: number, endLine: number): Promise<ITerminalSimpleLink[]> {
const links: ITerminalSimpleLink[] = [];
// Get the text representation of the wrapped line
const text = getXtermLineContent(this.xterm.buffer.active, startLine, endLine, this.xterm.cols);
if (text === '' || text.length > Constants.MaxLineLength) {
return [];
}
this._logService.trace('terminalMultiLineLinkDetector#detect text', text);
// Match against the fallback matchers which are mainly designed to catch paths with spaces
// that aren't possible using the regular mechanism.
for (const matcher of lineNumberPrefixMatchers) {
const match = text.match(matcher);
const group = match?.groups;
if (!group) {
continue;
}
const link = group?.link;
const line = group?.line;
const col = group?.col;
if (!link || line === undefined) {
continue;
}
// Don't try resolve any links of excessive length
if (link.length > Constants.MaxResolvedLinkLength) {
continue;
}
this._logService.trace('terminalMultiLineLinkDetector#detect candidate', link);
// Scan up looking for the first line that could be a path
let possiblePath: string | undefined;
for (let index = startLine - 1; index >= 0; index--) {
// Ignore lines that aren't at the beginning of a wrapped line
if (this.xterm.buffer.active.getLine(index)!.isWrapped) {
continue;
}
const text = getXtermLineContent(this.xterm.buffer.active, index, index, this.xterm.cols);
if (!text.match(/^\s*\d/)) {
possiblePath = text;
break;
}
}
if (!possiblePath) {
continue;
}
// Check if the first non-matching line is an absolute or relative link
const linkStat = await this._linkResolver.resolveLink(this._processManager, possiblePath);
if (linkStat) {
let type: TerminalBuiltinLinkType;
if (linkStat.isDirectory) {
if (this._isDirectoryInsideWorkspace(linkStat.uri)) {
type = TerminalBuiltinLinkType.LocalFolderInWorkspace;
} else {
type = TerminalBuiltinLinkType.LocalFolderOutsideWorkspace;
}
} else {
type = TerminalBuiltinLinkType.LocalFile;
}
// Convert the entire line's text string index into a wrapped buffer range
const bufferRange = convertLinkRangeToBuffer(lines, this.xterm.cols, {
startColumn: 1,
startLineNumber: 1,
endColumn: 1 + text.length,
endLineNumber: 1
}, startLine);
const simpleLink: ITerminalSimpleLink = {
text: link,
uri: linkStat.uri,
selection: {
startLineNumber: parseInt(line),
startColumn: col ? parseInt(col) : 1
},
disableTrimColon: true,
bufferRange: bufferRange,
type
};
this._logService.trace('terminalMultiLineLinkDetector#detect verified link', simpleLink);
links.push(simpleLink);
// Break on the first match
break;
}
}
if (links.length === 0) {
for (const matcher of gitDiffMatchers) {
const match = text.match(matcher);
const group = match?.groups;
if (!group) {
continue;
}
const link = group?.link;
const toFileLine = group?.toFileLine;
const toFileCount = group?.toFileCount;
if (!link || toFileLine === undefined) {
continue;
}
// Don't try resolve any links of excessive length
if (link.length > Constants.MaxResolvedLinkLength) {
continue;
}
this._logService.trace('terminalMultiLineLinkDetector#detect candidate', link);
// Scan up looking for the first line that could be a path
let possiblePath: string | undefined;
for (let index = startLine - 1; index >= 0; index--) {
// Ignore lines that aren't at the beginning of a wrapped line
if (this.xterm.buffer.active.getLine(index)!.isWrapped) {
continue;
}
const text = getXtermLineContent(this.xterm.buffer.active, index, index, this.xterm.cols);
const match = text.match(/\+\+\+ b\/(?<path>.+)/);
if (match) {
possiblePath = match.groups?.path;
break;
}
}
if (!possiblePath) {
continue;
}
// Check if the first non-matching line is an absolute or relative link
const linkStat = await this._linkResolver.resolveLink(this._processManager, possiblePath);
if (linkStat) {
let type: TerminalBuiltinLinkType;
if (linkStat.isDirectory) {
if (this._isDirectoryInsideWorkspace(linkStat.uri)) {
type = TerminalBuiltinLinkType.LocalFolderInWorkspace;
} else {
type = TerminalBuiltinLinkType.LocalFolderOutsideWorkspace;
}
} else {
type = TerminalBuiltinLinkType.LocalFile;
}
// Convert the link to the buffer range
const bufferRange = convertLinkRangeToBuffer(lines, this.xterm.cols, {
startColumn: 1,
startLineNumber: 1,
endColumn: 1 + link.length,
endLineNumber: 1
}, startLine);
const simpleLink: ITerminalSimpleLink = {
text: link,
uri: linkStat.uri,
selection: {
startLineNumber: parseInt(toFileLine),
startColumn: 1,
endLineNumber: parseInt(toFileLine) + parseInt(toFileCount)
},
bufferRange: bufferRange,
type
};
this._logService.trace('terminalMultiLineLinkDetector#detect verified link', simpleLink);
links.push(simpleLink);
// Break on the first match
break;
}
}
}
return links;
}
private _isDirectoryInsideWorkspace(uri: URI) {
const folders = this._workspaceContextService.getWorkspace().folders;
for (let i = 0; i < folders.length; i++) {
if (this._uriIdentityService.extUri.isEqualOrParent(uri, folders[i].uri)) {
return true;
}
}
return false;
}
}
| src/vs/workbench/contrib/terminalContrib/links/browser/terminalMultiLineLinkDetector.ts | 0 | https://github.com/microsoft/vscode/commit/48a9149e6ad2cbc0f7ebfdb2ce6143627c077d1e | [
0.00017504283459857106,
0.00017035265045706183,
0.00016112798766698688,
0.00017101010598707944,
0.000003264144424974802
] |
{
"id": 6,
"code_window": [
"\n",
"\t\tawait p;\n",
"\n",
"\t\tconst session = inlineChatSessionService.getSession(editor, editor.getModel()!.uri);\n",
"\t\tassert.ok(session);\n",
"\t\tassert.deepStrictEqual(session.wholeRange.value, new Range(1, 1, 1, 11));\n",
"\n",
"\t\teditor.setSelection(new Range(2, 1, 2, 1));\n",
"\t\teditor.trigger('test', 'type', { text: 'a' });\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tassert.deepStrictEqual(session.wholeRange.value, new Range(1, 1, 1, 6));\n"
],
"file_path": "src/vs/workbench/contrib/inlineChat/test/browser/inlineChatController.test.ts",
"type": "replace",
"edit_start_line_idx": 254
} | {
"name": "vscode-test-resolver",
"description": "Test resolver for VS Code",
"version": "0.0.1",
"publisher": "vscode",
"license": "MIT",
"enabledApiProposals": [
"resolvers",
"tunnels"
],
"private": true,
"engines": {
"vscode": "^1.25.0"
},
"icon": "media/icon.png",
"extensionKind": [
"ui"
],
"scripts": {
"compile": "node ./node_modules/vscode/bin/compile -watch -p ./",
"vscode:prepublish": "node ../../node_modules/gulp/bin/gulp.js --gulpfile ../../build/gulpfile.extensions.js compile-extension:vscode-test-resolver"
},
"activationEvents": [
"onResolveRemoteAuthority:test",
"onCommand:vscode-testresolver.newWindow",
"onCommand:vscode-testresolver.currentWindow",
"onCommand:vscode-testresolver.newWindowWithError",
"onCommand:vscode-testresolver.showLog",
"onCommand:vscode-testresolver.openTunnel",
"onCommand:vscode-testresolver.startRemoteServer",
"onCommand:vscode-testresolver.toggleConnectionPause"
],
"main": "./out/extension",
"browser": "./dist/browser/testResolverMain",
"devDependencies": {
"@types/node": "18.x"
},
"capabilities": {
"untrustedWorkspaces": {
"supported": true
},
"virtualWorkspaces": true
},
"contributes": {
"resourceLabelFormatters": [
{
"scheme": "vscode-remote",
"authority": "test+*",
"formatting": {
"label": "${path}",
"separator": "/",
"tildify": true,
"workspaceSuffix": "TestResolver",
"workspaceTooltip": "Remote running on the same machine"
}
}
],
"commands": [
{
"title": "New TestResolver Window",
"category": "Remote-TestResolver",
"command": "vscode-testresolver.newWindow"
},
{
"title": "Connect to TestResolver in Current Window",
"category": "Remote-TestResolver",
"command": "vscode-testresolver.currentWindow"
},
{
"title": "Connect to TestResolver in Current Window with Managed Connection",
"category": "Remote-TestResolver",
"command": "vscode-testresolver.currentWindowManaged"
},
{
"title": "Show TestResolver Log",
"category": "Remote-TestResolver",
"command": "vscode-testresolver.showLog"
},
{
"title": "Kill Remote Server and Trigger Handled Error",
"category": "Remote-TestResolver",
"command": "vscode-testresolver.killServerAndTriggerHandledError"
},
{
"title": "Open Tunnel...",
"category": "Remote-TestResolver",
"command": "vscode-testresolver.openTunnel"
},
{
"title": "Open a Remote Port...",
"category": "Remote-TestResolver",
"command": "vscode-testresolver.startRemoteServer"
},
{
"title": "Pause Connection (Test Reconnect)",
"category": "Remote-TestResolver",
"command": "vscode-testresolver.toggleConnectionPause"
},
{
"title": "Slowdown Connection (Test Slow Down Indicator)",
"category": "Remote-TestResolver",
"command": "vscode-testresolver.toggleConnectionSlowdown"
}
],
"menus": {
"commandPalette": [
{
"command": "vscode-testresolver.openTunnel",
"when": "remoteName == test"
},
{
"command": "vscode-testresolver.startRemoteServer",
"when": "remoteName == test"
},
{
"command": "vscode-testresolver.toggleConnectionPause",
"when": "remoteName == test"
}
],
"statusBar/remoteIndicator": [
{
"command": "vscode-testresolver.newWindow",
"when": "!remoteName && !virtualWorkspace",
"group": "remote_90_test_1_local@2"
},
{
"command": "vscode-testresolver.showLog",
"when": "remoteName == test",
"group": "remote_90_test_1_open@3"
},
{
"command": "vscode-testresolver.newWindow",
"when": "remoteName == test",
"group": "remote_90_test_1_open@1"
},
{
"command": "vscode-testresolver.openTunnel",
"when": "remoteName == test",
"group": "remote_90_test_2_more@4"
},
{
"command": "vscode-testresolver.startRemoteServer",
"when": "remoteName == test",
"group": "remote_90_test_2_more@5"
},
{
"command": "vscode-testresolver.toggleConnectionPause",
"when": "remoteName == test",
"group": "remote_90_test_2_more@6"
}
]
},
"configuration": {
"properties": {
"testresolver.startupDelay": {
"description": "If set, the resolver will delay for the given amount of seconds. Use ths setting for testing a slow resolver",
"type": "number",
"default": 0
},
"testresolver.startupError": {
"description": "If set, the resolver will fail. Use ths setting for testing the failure of a resolver.",
"type": "boolean",
"default": false
},
"testresolver.supportPublicPorts": {
"description": "If set, the test resolver tunnel factory will support mock public ports. Forwarded ports will not actually be public. Requires reload.",
"type": "boolean",
"default": false
}
}
}
},
"repository": {
"type": "git",
"url": "https://github.com/microsoft/vscode.git"
}
}
| extensions/vscode-test-resolver/package.json | 0 | https://github.com/microsoft/vscode/commit/48a9149e6ad2cbc0f7ebfdb2ce6143627c077d1e | [
0.00017657062562648207,
0.00017435145855415612,
0.00017034911434166133,
0.00017452388419769704,
0.0000014809970707574394
] |
{
"id": 7,
"code_window": [
"\n",
"\t\tawait p;\n",
"\n",
"\t\tconst session = inlineChatSessionService.getSession(editor, editor.getModel()!.uri);\n",
"\t\tassert.ok(session);\n",
"\t\tassert.deepStrictEqual(session.wholeRange.value, new Range(3, 1, 3, 12));\n",
"\n",
"\t\tctrl.acceptInput();\n",
"\n",
"\t\tawait ctrl.waitFor([State.MAKE_REQUEST, State.APPLY_RESPONSE, State.SHOW_RESPONSE, State.WAIT_FOR_INPUT]);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tassert.deepStrictEqual(session.wholeRange.value, new Range(3, 1, 3, 3));\n"
],
"file_path": "src/vs/workbench/contrib/inlineChat/test/browser/inlineChatController.test.ts",
"type": "replace",
"edit_start_line_idx": 296
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { URI } from 'vs/base/common/uri';
import { Emitter, Event } from 'vs/base/common/event';
import { ResourceEdit, ResourceFileEdit, ResourceTextEdit } from 'vs/editor/browser/services/bulkEditService';
import { IWorkspaceTextEdit, TextEdit, WorkspaceEdit } from 'vs/editor/common/languages';
import { IModelDecorationOptions, IModelDeltaDecoration, ITextModel } from 'vs/editor/common/model';
import { EditMode, IInlineChatSessionProvider, IInlineChatSession, IInlineChatBulkEditResponse, IInlineChatEditResponse, IInlineChatResponse, IInlineChatService, InlineChatResponseType, InlineChatResponseTypes } from 'vs/workbench/contrib/inlineChat/common/inlineChat';
import { IRange, Range } from 'vs/editor/common/core/range';
import { IActiveCodeEditor, ICodeEditor } from 'vs/editor/browser/editorBrowser';
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { IModelService } from 'vs/editor/common/services/model';
import { ITextModelService } from 'vs/editor/common/services/resolverService';
import { DisposableStore, IDisposable, toDisposable } from 'vs/base/common/lifecycle';
import { ModelDecorationOptions, createTextBufferFactoryFromSnapshot } from 'vs/editor/common/model/textModel';
import { ILogService } from 'vs/platform/log/common/log';
import { CancellationToken } from 'vs/base/common/cancellation';
import { Iterable } from 'vs/base/common/iterator';
import { toErrorMessage } from 'vs/base/common/errorMessage';
import { isCancellationError } from 'vs/base/common/errors';
import { EditOperation, ISingleEditOperation } from 'vs/editor/common/core/editOperation';
import { raceCancellation } from 'vs/base/common/async';
import { DetailedLineRangeMapping, LineRangeMapping } from 'vs/editor/common/diff/rangeMapping';
import { IMarkdownString } from 'vs/base/common/htmlContent';
import { IUntitledTextEditorModel } from 'vs/workbench/services/untitled/common/untitledTextEditorModel';
import { ITextFileService } from 'vs/workbench/services/textfile/common/textfiles';
import { ILanguageService } from 'vs/editor/common/languages/language';
import { ResourceMap } from 'vs/base/common/map';
import { Schemas } from 'vs/base/common/network';
import { isEqual } from 'vs/base/common/resources';
export type Recording = {
when: Date;
session: IInlineChatSession;
exchanges: { prompt: string; res: IInlineChatResponse }[];
};
type TelemetryData = {
extension: string;
rounds: string;
undos: string;
edits: boolean;
finishedByEdit: boolean;
startTime: string;
endTime: string;
editMode: string;
};
type TelemetryDataClassification = {
owner: 'jrieken';
comment: 'Data about an interaction editor session';
extension: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'The extension providing the data' };
rounds: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'Number of request that were made' };
undos: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; isMeasurement: true; comment: 'Requests that have been undone' };
edits: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; isMeasurement: true; comment: 'Did edits happen while the session was active' };
finishedByEdit: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; isMeasurement: true; comment: 'Did edits cause the session to terminate' };
startTime: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'When the session started' };
endTime: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'When the session ended' };
editMode: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'What edit mode was choosen: live, livePreview, preview' };
};
export enum ExpansionState {
EXPANDED = 'expanded',
CROPPED = 'cropped',
NOT_CROPPED = 'not_cropped'
}
class SessionWholeRange {
private static readonly _options: IModelDecorationOptions = ModelDecorationOptions.register({ description: 'inlineChat/session/wholeRange' });
private readonly _onDidChange = new Emitter<this>();
readonly onDidChange: Event<this> = this._onDidChange.event;
private _decorationIds: string[] = [];
constructor(private readonly _textModel: ITextModel, wholeRange: IRange) {
this._decorationIds = _textModel.deltaDecorations([], [{ range: wholeRange, options: SessionWholeRange._options }]);
}
dispose() {
this._onDidChange.dispose();
if (!this._textModel.isDisposed()) {
this._textModel.deltaDecorations(this._decorationIds, []);
}
}
trackEdits(edits: ISingleEditOperation[]): void {
const newDeco: IModelDeltaDecoration[] = [];
for (const edit of edits) {
newDeco.push({ range: edit.range, options: SessionWholeRange._options });
}
this._decorationIds.push(...this._textModel.deltaDecorations([], newDeco));
this._onDidChange.fire(this);
}
fixup(changes: readonly DetailedLineRangeMapping[]): void {
const newDeco: IModelDeltaDecoration[] = [];
for (const { modified } of changes) {
const modifiedRange = modified.isEmpty
? new Range(modified.startLineNumber, 1, modified.startLineNumber, this._textModel.getLineLength(modified.startLineNumber))
: new Range(modified.startLineNumber, 1, modified.endLineNumberExclusive - 1, this._textModel.getLineLength(modified.endLineNumberExclusive - 1));
newDeco.push({ range: modifiedRange, options: SessionWholeRange._options });
}
const [first, ...rest] = this._decorationIds; // first is the original whole range
const newIds = this._textModel.deltaDecorations(rest, newDeco);
this._decorationIds = [first].concat(newIds);
this._onDidChange.fire(this);
}
get value(): Range {
let result: Range | undefined;
for (const id of this._decorationIds) {
const range = this._textModel.getDecorationRange(id);
if (range) {
if (!result) {
result = range;
} else {
result = Range.plusRange(result, range);
}
}
}
return result!;
}
}
export class Session {
private _lastInput: SessionPrompt | undefined;
private _lastExpansionState: ExpansionState | undefined;
private _isUnstashed: boolean = false;
private readonly _exchange: SessionExchange[] = [];
private readonly _startTime = new Date();
private readonly _teldata: Partial<TelemetryData>;
readonly textModelNAltVersion: number;
private _textModelNSnapshotAltVersion: number | undefined;
constructor(
readonly editMode: EditMode,
readonly editor: ICodeEditor,
readonly textModel0: ITextModel,
readonly textModelN: ITextModel,
readonly provider: IInlineChatSessionProvider,
readonly session: IInlineChatSession,
readonly wholeRange: SessionWholeRange
) {
this.textModelNAltVersion = textModelN.getAlternativeVersionId();
this._teldata = {
extension: provider.debugName,
startTime: this._startTime.toISOString(),
edits: false,
finishedByEdit: false,
rounds: '',
undos: '',
editMode
};
}
addInput(input: SessionPrompt): void {
this._lastInput = input;
}
get lastInput() {
return this._lastInput;
}
get isUnstashed(): boolean {
return this._isUnstashed;
}
markUnstashed() {
this._isUnstashed = true;
}
get lastExpansionState(): ExpansionState | undefined {
return this._lastExpansionState;
}
set lastExpansionState(state: ExpansionState) {
this._lastExpansionState = state;
}
get textModelNSnapshotAltVersion(): number | undefined {
return this._textModelNSnapshotAltVersion;
}
createSnapshot(): void {
this._textModelNSnapshotAltVersion = this.textModelN.getAlternativeVersionId();
}
addExchange(exchange: SessionExchange): void {
this._isUnstashed = false;
const newLen = this._exchange.push(exchange);
this._teldata.rounds += `${newLen}|`;
}
get exchanges(): Iterable<SessionExchange> {
return this._exchange;
}
get lastExchange(): SessionExchange | undefined {
return this._exchange[this._exchange.length - 1];
}
get hasChangedText(): boolean {
return !this.textModel0.equalsTextBuffer(this.textModelN.getTextBuffer());
}
asChangedText(changes: readonly LineRangeMapping[]): string | undefined {
if (changes.length === 0) {
return undefined;
}
let startLine = Number.MAX_VALUE;
let endLine = Number.MIN_VALUE;
for (const change of changes) {
startLine = Math.min(startLine, change.modified.startLineNumber);
endLine = Math.max(endLine, change.modified.endLineNumberExclusive);
}
return this.textModelN.getValueInRange(new Range(startLine, 1, endLine, Number.MAX_VALUE));
}
recordExternalEditOccurred(didFinish: boolean) {
this._teldata.edits = true;
this._teldata.finishedByEdit = didFinish;
}
asTelemetryData(): TelemetryData {
return <TelemetryData>{
...this._teldata,
endTime: new Date().toISOString(),
};
}
asRecording(): Recording {
const result: Recording = {
session: this.session,
when: this._startTime,
exchanges: []
};
for (const exchange of this._exchange) {
const response = exchange.response;
if (response instanceof ReplyResponse) {
result.exchanges.push({ prompt: exchange.prompt.value, res: response.raw });
}
}
return result;
}
}
export class SessionPrompt {
private _attempt: number = 0;
constructor(
readonly value: string,
) { }
get attempt() {
return this._attempt;
}
retry() {
const result = new SessionPrompt(this.value);
result._attempt = this._attempt + 1;
return result;
}
}
export class SessionExchange {
constructor(
readonly prompt: SessionPrompt,
readonly response: ReplyResponse | EmptyResponse | ErrorResponse
) { }
}
export class EmptyResponse {
}
export class ErrorResponse {
readonly message: string;
readonly isCancellation: boolean;
constructor(
readonly error: any
) {
this.message = toErrorMessage(error, false);
this.isCancellation = isCancellationError(error);
}
}
export class ReplyResponse {
readonly allLocalEdits: TextEdit[][] = [];
readonly untitledTextModel: IUntitledTextEditorModel | undefined;
readonly workspaceEdit: WorkspaceEdit | undefined;
readonly responseType: InlineChatResponseTypes;
constructor(
readonly raw: IInlineChatBulkEditResponse | IInlineChatEditResponse,
readonly mdContent: IMarkdownString,
localUri: URI,
readonly modelAltVersionId: number,
progressEdits: TextEdit[][],
readonly requestId: string,
@ITextFileService private readonly _textFileService: ITextFileService,
@ILanguageService private readonly _languageService: ILanguageService,
) {
const editsMap = new ResourceMap<TextEdit[][]>();
editsMap.set(localUri, [...progressEdits]);
if (raw.type === InlineChatResponseType.EditorEdit) {
//
editsMap.get(localUri)!.push(raw.edits);
} else if (raw.type === InlineChatResponseType.BulkEdit) {
//
const edits = ResourceEdit.convert(raw.edits);
for (const edit of edits) {
if (edit instanceof ResourceFileEdit) {
if (edit.newResource && !edit.oldResource) {
editsMap.set(edit.newResource, []);
if (edit.options.contents) {
console.warn('CONTENT not supported');
}
}
} else if (edit instanceof ResourceTextEdit) {
//
const array = editsMap.get(edit.resource);
if (array) {
array.push([edit.textEdit]);
} else {
editsMap.set(edit.resource, [[edit.textEdit]]);
}
}
}
}
let needsWorkspaceEdit = false;
for (const [uri, edits] of editsMap) {
const flatEdits = edits.flat();
if (flatEdits.length === 0) {
editsMap.delete(uri);
continue;
}
const isLocalUri = isEqual(uri, localUri);
needsWorkspaceEdit = needsWorkspaceEdit || (uri.scheme !== Schemas.untitled && !isLocalUri);
if (uri.scheme === Schemas.untitled && !isLocalUri && !this.untitledTextModel) { //TODO@jrieken the first untitled model WINS
const langSelection = this._languageService.createByFilepathOrFirstLine(uri, undefined);
const untitledTextModel = this._textFileService.untitled.create({
associatedResource: uri,
languageId: langSelection.languageId
});
this.untitledTextModel = untitledTextModel;
untitledTextModel.resolve().then(async () => {
const model = untitledTextModel.textEditorModel!;
model.applyEdits(flatEdits.map(edit => EditOperation.replace(Range.lift(edit.range), edit.text)));
});
}
}
this.allLocalEdits = editsMap.get(localUri) ?? [];
if (needsWorkspaceEdit) {
const workspaceEdits: IWorkspaceTextEdit[] = [];
for (const [uri, edits] of editsMap) {
for (const edit of edits.flat()) {
workspaceEdits.push({ resource: uri, textEdit: edit, versionId: undefined });
}
}
this.workspaceEdit = { edits: workspaceEdits };
}
const hasEdits = editsMap.size > 0;
const hasMessage = mdContent.value.length > 0;
if (hasEdits && hasMessage) {
this.responseType = InlineChatResponseTypes.Mixed;
} else if (hasEdits) {
this.responseType = InlineChatResponseTypes.OnlyEdits;
} else if (hasMessage) {
this.responseType = InlineChatResponseTypes.OnlyMessages;
} else {
this.responseType = InlineChatResponseTypes.Empty;
}
}
}
export interface ISessionKeyComputer {
getComparisonKey(editor: ICodeEditor, uri: URI): string;
}
export const IInlineChatSessionService = createDecorator<IInlineChatSessionService>('IInlineChatSessionService');
export interface IInlineChatSessionService {
_serviceBrand: undefined;
onWillStartSession: Event<IActiveCodeEditor>;
onDidEndSession: Event<ICodeEditor>;
createSession(editor: IActiveCodeEditor, options: { editMode: EditMode; wholeRange?: IRange }, token: CancellationToken): Promise<Session | undefined>;
getSession(editor: ICodeEditor, uri: URI): Session | undefined;
releaseSession(session: Session): void;
registerSessionKeyComputer(scheme: string, value: ISessionKeyComputer): IDisposable;
//
recordings(): readonly Recording[];
dispose(): void;
}
type SessionData = {
session: Session;
store: IDisposable;
};
export class InlineChatSessionService implements IInlineChatSessionService {
declare _serviceBrand: undefined;
private readonly _onWillStartSession = new Emitter<IActiveCodeEditor>();
readonly onWillStartSession: Event<IActiveCodeEditor> = this._onWillStartSession.event;
private readonly _onDidEndSession = new Emitter<ICodeEditor>();
readonly onDidEndSession: Event<ICodeEditor> = this._onDidEndSession.event;
private readonly _sessions = new Map<string, SessionData>();
private readonly _keyComputers = new Map<string, ISessionKeyComputer>();
private _recordings: Recording[] = [];
constructor(
@IInlineChatService private readonly _inlineChatService: IInlineChatService,
@ITelemetryService private readonly _telemetryService: ITelemetryService,
@IModelService private readonly _modelService: IModelService,
@ITextModelService private readonly _textModelService: ITextModelService,
@ILogService private readonly _logService: ILogService,
) { }
dispose() {
this._onWillStartSession.dispose();
this._onDidEndSession.dispose();
this._sessions.forEach(x => x.store.dispose());
this._sessions.clear();
}
async createSession(editor: IActiveCodeEditor, options: { editMode: EditMode; wholeRange?: Range }, token: CancellationToken): Promise<Session | undefined> {
const provider = Iterable.first(this._inlineChatService.getAllProvider());
if (!provider) {
this._logService.trace('[IE] NO provider found');
return undefined;
}
this._onWillStartSession.fire(editor);
const textModel = editor.getModel();
const selection = editor.getSelection();
let raw: IInlineChatSession | undefined | null;
try {
raw = await raceCancellation(
Promise.resolve(provider.prepareInlineChatSession(textModel, selection, token)),
token
);
} catch (error) {
this._logService.error('[IE] FAILED to prepare session', provider.debugName);
this._logService.error(error);
return undefined;
}
if (!raw) {
this._logService.trace('[IE] NO session', provider.debugName);
return undefined;
}
this._logService.trace('[IE] NEW session', provider.debugName);
this._logService.trace(`[IE] creating NEW session for ${editor.getId()}, ${provider.debugName}`);
const store = new DisposableStore();
// create: keep a reference to prevent disposal of the "actual" model
const refTextModelN = await this._textModelService.createModelReference(textModel.uri);
store.add(refTextModelN);
// create: keep a snapshot of the "actual" model
const textModel0 = this._modelService.createModel(
createTextBufferFactoryFromSnapshot(textModel.createSnapshot()),
{ languageId: textModel.getLanguageId(), onDidChange: Event.None },
undefined, true
);
store.add(textModel0);
let wholeRange = options.wholeRange;
if (!wholeRange) {
wholeRange = raw.wholeRange ? Range.lift(raw.wholeRange) : editor.getSelection();
}
// expand to whole lines
wholeRange = new Range(wholeRange.startLineNumber, 1, wholeRange.endLineNumber, textModel.getLineMaxColumn(wholeRange.endLineNumber));
// install managed-marker for the decoration range
const wholeRangeMgr = new SessionWholeRange(textModel, wholeRange);
store.add(wholeRangeMgr);
const session = new Session(options.editMode, editor, textModel0, textModel, provider, raw, wholeRangeMgr);
// store: key -> session
const key = this._key(editor, textModel.uri);
if (this._sessions.has(key)) {
store.dispose();
throw new Error(`Session already stored for ${key}`);
}
this._sessions.set(key, { session, store });
return session;
}
releaseSession(session: Session): void {
const { editor } = session;
// cleanup
for (const [key, value] of this._sessions) {
if (value.session === session) {
value.store.dispose();
this._sessions.delete(key);
this._logService.trace(`[IE] did RELEASED session for ${editor.getId()}, ${session.provider.debugName}`);
break;
}
}
// keep recording
const newLen = this._recordings.unshift(session.asRecording());
if (newLen > 5) {
this._recordings.pop();
}
// send telemetry
this._telemetryService.publicLog2<TelemetryData, TelemetryDataClassification>('interactiveEditor/session', session.asTelemetryData());
this._onDidEndSession.fire(editor);
}
getSession(editor: ICodeEditor, uri: URI): Session | undefined {
const key = this._key(editor, uri);
return this._sessions.get(key)?.session;
}
private _key(editor: ICodeEditor, uri: URI): string {
const item = this._keyComputers.get(uri.scheme);
return item
? item.getComparisonKey(editor, uri)
: `${editor.getId()}@${uri.toString()}`;
}
registerSessionKeyComputer(scheme: string, value: ISessionKeyComputer): IDisposable {
this._keyComputers.set(scheme, value);
return toDisposable(() => this._keyComputers.delete(scheme));
}
// --- debug
recordings(): readonly Recording[] {
return this._recordings;
}
}
| src/vs/workbench/contrib/inlineChat/browser/inlineChatSession.ts | 1 | https://github.com/microsoft/vscode/commit/48a9149e6ad2cbc0f7ebfdb2ce6143627c077d1e | [
0.013342460617423058,
0.0008464400307275355,
0.0001627888559596613,
0.000173752021510154,
0.0019381545716896653
] |
{
"id": 7,
"code_window": [
"\n",
"\t\tawait p;\n",
"\n",
"\t\tconst session = inlineChatSessionService.getSession(editor, editor.getModel()!.uri);\n",
"\t\tassert.ok(session);\n",
"\t\tassert.deepStrictEqual(session.wholeRange.value, new Range(3, 1, 3, 12));\n",
"\n",
"\t\tctrl.acceptInput();\n",
"\n",
"\t\tawait ctrl.waitFor([State.MAKE_REQUEST, State.APPLY_RESPONSE, State.SHOW_RESPONSE, State.WAIT_FOR_INPUT]);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tassert.deepStrictEqual(session.wholeRange.value, new Range(3, 1, 3, 3));\n"
],
"file_path": "src/vs/workbench/contrib/inlineChat/test/browser/inlineChatController.test.ts",
"type": "replace",
"edit_start_line_idx": 296
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
declare module 'vscode' {
/**
* Represents a session of a currently logged in user.
*/
export interface AuthenticationSession {
/**
* An optional ID token that may be included in the session.
*/
readonly idToken?: string;
}
}
| src/vscode-dts/vscode.proposed.idToken.d.ts | 0 | https://github.com/microsoft/vscode/commit/48a9149e6ad2cbc0f7ebfdb2ce6143627c077d1e | [
0.00016952128498815,
0.00016675706137903035,
0.0001639928377699107,
0.00016675706137903035,
0.0000027642236091196537
] |
{
"id": 7,
"code_window": [
"\n",
"\t\tawait p;\n",
"\n",
"\t\tconst session = inlineChatSessionService.getSession(editor, editor.getModel()!.uri);\n",
"\t\tassert.ok(session);\n",
"\t\tassert.deepStrictEqual(session.wholeRange.value, new Range(3, 1, 3, 12));\n",
"\n",
"\t\tctrl.acceptInput();\n",
"\n",
"\t\tawait ctrl.waitFor([State.MAKE_REQUEST, State.APPLY_RESPONSE, State.SHOW_RESPONSE, State.WAIT_FOR_INPUT]);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tassert.deepStrictEqual(session.wholeRange.value, new Range(3, 1, 3, 3));\n"
],
"file_path": "src/vs/workbench/contrib/inlineChat/test/browser/inlineChatController.test.ts",
"type": "replace",
"edit_start_line_idx": 296
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { ClientSecretCredential } from '@azure/identity';
import { CosmosClient } from '@azure/cosmos';
import { retry } from './retry';
if (process.argv.length !== 3) {
console.error('Usage: node createBuild.js VERSION');
process.exit(-1);
}
function getEnv(name: string): string {
const result = process.env[name];
if (typeof result === 'undefined') {
throw new Error('Missing env: ' + name);
}
return result;
}
async function main(): Promise<void> {
const [, , _version] = process.argv;
const quality = getEnv('VSCODE_QUALITY');
const commit = getEnv('BUILD_SOURCEVERSION');
const queuedBy = getEnv('BUILD_QUEUEDBY');
const sourceBranch = getEnv('BUILD_SOURCEBRANCH');
const version = _version + (quality === 'stable' ? '' : `-${quality}`);
console.log('Creating build...');
console.log('Quality:', quality);
console.log('Version:', version);
console.log('Commit:', commit);
const build = {
id: commit,
timestamp: (new Date()).getTime(),
version,
isReleased: false,
private: process.env['VSCODE_PRIVATE_BUILD']?.toLowerCase() === 'true',
sourceBranch,
queuedBy,
assets: [],
updates: {}
};
const aadCredentials = new ClientSecretCredential(process.env['AZURE_TENANT_ID']!, process.env['AZURE_CLIENT_ID']!, process.env['AZURE_CLIENT_SECRET']!);
const client = new CosmosClient({ endpoint: process.env['AZURE_DOCUMENTDB_ENDPOINT']!, aadCredentials });
const scripts = client.database('builds').container(quality).scripts;
await retry(() => scripts.storedProcedure('createBuild').execute('', [{ ...build, _partitionKey: '' }]));
}
main().then(() => {
console.log('Build successfully created');
process.exit(0);
}, err => {
console.error(err);
process.exit(1);
});
| build/azure-pipelines/common/createBuild.ts | 0 | https://github.com/microsoft/vscode/commit/48a9149e6ad2cbc0f7ebfdb2ce6143627c077d1e | [
0.00017633139214012772,
0.0001708725467324257,
0.0001627677702344954,
0.00017345481319352984,
0.000004763310244015884
] |
{
"id": 7,
"code_window": [
"\n",
"\t\tawait p;\n",
"\n",
"\t\tconst session = inlineChatSessionService.getSession(editor, editor.getModel()!.uri);\n",
"\t\tassert.ok(session);\n",
"\t\tassert.deepStrictEqual(session.wholeRange.value, new Range(3, 1, 3, 12));\n",
"\n",
"\t\tctrl.acceptInput();\n",
"\n",
"\t\tawait ctrl.waitFor([State.MAKE_REQUEST, State.APPLY_RESPONSE, State.SHOW_RESPONSE, State.WAIT_FOR_INPUT]);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tassert.deepStrictEqual(session.wholeRange.value, new Range(3, 1, 3, 3));\n"
],
"file_path": "src/vs/workbench/contrib/inlineChat/test/browser/inlineChatController.test.ts",
"type": "replace",
"edit_start_line_idx": 296
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
.monaco-workbench .notifications-list-container .notification-list-item .notification-list-item-toolbar-container .action-item,
.monaco-workbench > .notifications-center > .notifications-center-header > .notifications-center-header-toolbar .action-item {
margin-right: 4px;
}
.monaco-workbench .notifications-list-container .notification-list-item .notification-list-item-toolbar-container .action-item:first-child,
.monaco-workbench > .notifications-center > .notifications-center-header > .notifications-center-header-toolbar .action-item:first-child {
margin-left: 4px;
}
| src/vs/workbench/browser/parts/notifications/media/notificationsActions.css | 0 | https://github.com/microsoft/vscode/commit/48a9149e6ad2cbc0f7ebfdb2ce6143627c077d1e | [
0.0001740499137667939,
0.0001732756063574925,
0.0001725012989481911,
0.0001732756063574925,
7.743074093014002e-7
] |
{
"id": 8,
"code_window": [
"\n",
"\t\tctrl.acceptInput();\n",
"\n",
"\t\tawait ctrl.waitFor([State.MAKE_REQUEST, State.APPLY_RESPONSE, State.SHOW_RESPONSE, State.WAIT_FOR_INPUT]);\n",
"\n",
"\t\tassert.deepStrictEqual(session.wholeRange.value, new Range(4, 1, 4, 12));\n",
"\n",
"\t\tawait ctrl.cancelSession();\n",
"\t\tawait r;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tassert.deepStrictEqual(session.wholeRange.value, new Range(4, 1, 4, 3));\n"
],
"file_path": "src/vs/workbench/contrib/inlineChat/test/browser/inlineChatController.test.ts",
"type": "replace",
"edit_start_line_idx": 302
} | /*---------------------------------------------------------------------------------------------
* 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.996157705783844,
0.028171397745609283,
0.00016324430180247873,
0.0006481516757048666,
0.1591586470603943
] |
{
"id": 8,
"code_window": [
"\n",
"\t\tctrl.acceptInput();\n",
"\n",
"\t\tawait ctrl.waitFor([State.MAKE_REQUEST, State.APPLY_RESPONSE, State.SHOW_RESPONSE, State.WAIT_FOR_INPUT]);\n",
"\n",
"\t\tassert.deepStrictEqual(session.wholeRange.value, new Range(4, 1, 4, 12));\n",
"\n",
"\t\tawait ctrl.cancelSession();\n",
"\t\tawait r;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tassert.deepStrictEqual(session.wholeRange.value, new Range(4, 1, 4, 3));\n"
],
"file_path": "src/vs/workbench/contrib/inlineChat/test/browser/inlineChatController.test.ts",
"type": "replace",
"edit_start_line_idx": 302
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { KeyCode, KeyCodeUtils, IMMUTABLE_CODE_TO_KEY_CODE, ScanCode } from 'vs/base/common/keyCodes';
import { SingleModifierChord, Chord, KeyCodeChord, Keybinding } from 'vs/base/common/keybindings';
import { OperatingSystem } from 'vs/base/common/platform';
import { BaseResolvedKeybinding } from 'vs/platform/keybinding/common/baseResolvedKeybinding';
import { toEmptyArrayIfContainsNull } from 'vs/platform/keybinding/common/resolvedKeybindingItem';
/**
* Do not instantiate. Use KeybindingService to get a ResolvedKeybinding seeded with information about the current kb layout.
*/
export class USLayoutResolvedKeybinding extends BaseResolvedKeybinding<KeyCodeChord> {
constructor(chords: KeyCodeChord[], os: OperatingSystem) {
super(os, chords);
}
private _keyCodeToUILabel(keyCode: KeyCode): string {
if (this._os === OperatingSystem.Macintosh) {
switch (keyCode) {
case KeyCode.LeftArrow:
return '←';
case KeyCode.UpArrow:
return '↑';
case KeyCode.RightArrow:
return '→';
case KeyCode.DownArrow:
return '↓';
}
}
return KeyCodeUtils.toString(keyCode);
}
protected _getLabel(chord: KeyCodeChord): string | null {
if (chord.isDuplicateModifierCase()) {
return '';
}
return this._keyCodeToUILabel(chord.keyCode);
}
protected _getAriaLabel(chord: KeyCodeChord): string | null {
if (chord.isDuplicateModifierCase()) {
return '';
}
return KeyCodeUtils.toString(chord.keyCode);
}
protected _getElectronAccelerator(chord: KeyCodeChord): string | null {
return KeyCodeUtils.toElectronAccelerator(chord.keyCode);
}
protected _getUserSettingsLabel(chord: KeyCodeChord): string | null {
if (chord.isDuplicateModifierCase()) {
return '';
}
const result = KeyCodeUtils.toUserSettingsUS(chord.keyCode);
return (result ? result.toLowerCase() : result);
}
protected _isWYSIWYG(): boolean {
return true;
}
protected _getChordDispatch(chord: KeyCodeChord): string | null {
return USLayoutResolvedKeybinding.getDispatchStr(chord);
}
public static getDispatchStr(chord: KeyCodeChord): string | null {
if (chord.isModifierKey()) {
return null;
}
let result = '';
if (chord.ctrlKey) {
result += 'ctrl+';
}
if (chord.shiftKey) {
result += 'shift+';
}
if (chord.altKey) {
result += 'alt+';
}
if (chord.metaKey) {
result += 'meta+';
}
result += KeyCodeUtils.toString(chord.keyCode);
return result;
}
protected _getSingleModifierChordDispatch(keybinding: KeyCodeChord): SingleModifierChord | null {
if (keybinding.keyCode === KeyCode.Ctrl && !keybinding.shiftKey && !keybinding.altKey && !keybinding.metaKey) {
return 'ctrl';
}
if (keybinding.keyCode === KeyCode.Shift && !keybinding.ctrlKey && !keybinding.altKey && !keybinding.metaKey) {
return 'shift';
}
if (keybinding.keyCode === KeyCode.Alt && !keybinding.ctrlKey && !keybinding.shiftKey && !keybinding.metaKey) {
return 'alt';
}
if (keybinding.keyCode === KeyCode.Meta && !keybinding.ctrlKey && !keybinding.shiftKey && !keybinding.altKey) {
return 'meta';
}
return null;
}
/**
* *NOTE*: Check return value for `KeyCode.Unknown`.
*/
private static _scanCodeToKeyCode(scanCode: ScanCode): KeyCode {
const immutableKeyCode = IMMUTABLE_CODE_TO_KEY_CODE[scanCode];
if (immutableKeyCode !== KeyCode.DependsOnKbLayout) {
return immutableKeyCode;
}
switch (scanCode) {
case ScanCode.KeyA: return KeyCode.KeyA;
case ScanCode.KeyB: return KeyCode.KeyB;
case ScanCode.KeyC: return KeyCode.KeyC;
case ScanCode.KeyD: return KeyCode.KeyD;
case ScanCode.KeyE: return KeyCode.KeyE;
case ScanCode.KeyF: return KeyCode.KeyF;
case ScanCode.KeyG: return KeyCode.KeyG;
case ScanCode.KeyH: return KeyCode.KeyH;
case ScanCode.KeyI: return KeyCode.KeyI;
case ScanCode.KeyJ: return KeyCode.KeyJ;
case ScanCode.KeyK: return KeyCode.KeyK;
case ScanCode.KeyL: return KeyCode.KeyL;
case ScanCode.KeyM: return KeyCode.KeyM;
case ScanCode.KeyN: return KeyCode.KeyN;
case ScanCode.KeyO: return KeyCode.KeyO;
case ScanCode.KeyP: return KeyCode.KeyP;
case ScanCode.KeyQ: return KeyCode.KeyQ;
case ScanCode.KeyR: return KeyCode.KeyR;
case ScanCode.KeyS: return KeyCode.KeyS;
case ScanCode.KeyT: return KeyCode.KeyT;
case ScanCode.KeyU: return KeyCode.KeyU;
case ScanCode.KeyV: return KeyCode.KeyV;
case ScanCode.KeyW: return KeyCode.KeyW;
case ScanCode.KeyX: return KeyCode.KeyX;
case ScanCode.KeyY: return KeyCode.KeyY;
case ScanCode.KeyZ: return KeyCode.KeyZ;
case ScanCode.Digit1: return KeyCode.Digit1;
case ScanCode.Digit2: return KeyCode.Digit2;
case ScanCode.Digit3: return KeyCode.Digit3;
case ScanCode.Digit4: return KeyCode.Digit4;
case ScanCode.Digit5: return KeyCode.Digit5;
case ScanCode.Digit6: return KeyCode.Digit6;
case ScanCode.Digit7: return KeyCode.Digit7;
case ScanCode.Digit8: return KeyCode.Digit8;
case ScanCode.Digit9: return KeyCode.Digit9;
case ScanCode.Digit0: return KeyCode.Digit0;
case ScanCode.Minus: return KeyCode.Minus;
case ScanCode.Equal: return KeyCode.Equal;
case ScanCode.BracketLeft: return KeyCode.BracketLeft;
case ScanCode.BracketRight: return KeyCode.BracketRight;
case ScanCode.Backslash: return KeyCode.Backslash;
case ScanCode.IntlHash: return KeyCode.Unknown; // missing
case ScanCode.Semicolon: return KeyCode.Semicolon;
case ScanCode.Quote: return KeyCode.Quote;
case ScanCode.Backquote: return KeyCode.Backquote;
case ScanCode.Comma: return KeyCode.Comma;
case ScanCode.Period: return KeyCode.Period;
case ScanCode.Slash: return KeyCode.Slash;
case ScanCode.IntlBackslash: return KeyCode.IntlBackslash;
}
return KeyCode.Unknown;
}
private static _toKeyCodeChord(chord: Chord | null): KeyCodeChord | null {
if (!chord) {
return null;
}
if (chord instanceof KeyCodeChord) {
return chord;
}
const keyCode = this._scanCodeToKeyCode(chord.scanCode);
if (keyCode === KeyCode.Unknown) {
return null;
}
return new KeyCodeChord(chord.ctrlKey, chord.shiftKey, chord.altKey, chord.metaKey, keyCode);
}
public static resolveKeybinding(keybinding: Keybinding, os: OperatingSystem): USLayoutResolvedKeybinding[] {
const chords: KeyCodeChord[] = toEmptyArrayIfContainsNull(keybinding.chords.map(chord => this._toKeyCodeChord(chord)));
if (chords.length > 0) {
return [new USLayoutResolvedKeybinding(chords, os)];
}
return [];
}
}
| src/vs/platform/keybinding/common/usLayoutResolvedKeybinding.ts | 0 | https://github.com/microsoft/vscode/commit/48a9149e6ad2cbc0f7ebfdb2ce6143627c077d1e | [
0.0014021045062690973,
0.0002474799402989447,
0.00016677533858455718,
0.00017478315567132086,
0.0002688996319193393
] |
{
"id": 8,
"code_window": [
"\n",
"\t\tctrl.acceptInput();\n",
"\n",
"\t\tawait ctrl.waitFor([State.MAKE_REQUEST, State.APPLY_RESPONSE, State.SHOW_RESPONSE, State.WAIT_FOR_INPUT]);\n",
"\n",
"\t\tassert.deepStrictEqual(session.wholeRange.value, new Range(4, 1, 4, 12));\n",
"\n",
"\t\tawait ctrl.cancelSession();\n",
"\t\tawait r;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tassert.deepStrictEqual(session.wholeRange.value, new Range(4, 1, 4, 3));\n"
],
"file_path": "src/vs/workbench/contrib/inlineChat/test/browser/inlineChatController.test.ts",
"type": "replace",
"edit_start_line_idx": 302
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { ITextAreaInputHost, TextAreaInput, TextAreaWrapper } from 'vs/editor/browser/controller/textAreaInput';
import { ISimpleModel, PagedScreenReaderStrategy, TextAreaState } from 'vs/editor/browser/controller/textAreaState';
import { Position } from 'vs/editor/common/core/position';
import { IRange, Range } from 'vs/editor/common/core/range';
import { EndOfLinePreference } from 'vs/editor/common/model';
import * as dom from 'vs/base/browser/dom';
import * as browser from 'vs/base/browser/browser';
import * as platform from 'vs/base/common/platform';
import { mainWindow } from 'vs/base/browser/window';
import { TestAccessibilityService } from 'vs/platform/accessibility/test/common/testAccessibilityService';
import { NullLogService } from 'vs/platform/log/common/log';
// To run this test, open imeTester.html
class SingleLineTestModel implements ISimpleModel {
private _line: string;
constructor(line: string) {
this._line = line;
}
_setText(text: string) {
this._line = text;
}
getLineMaxColumn(lineNumber: number): number {
return this._line.length + 1;
}
getValueInRange(range: IRange, eol: EndOfLinePreference): string {
return this._line.substring(range.startColumn - 1, range.endColumn - 1);
}
getValueLengthInRange(range: Range, eol: EndOfLinePreference): number {
return this.getValueInRange(range, eol).length;
}
modifyPosition(position: Position, offset: number): Position {
const column = Math.min(this.getLineMaxColumn(position.lineNumber), Math.max(1, position.column + offset));
return new Position(position.lineNumber, column);
}
getModelLineContent(lineNumber: number): string {
return this._line;
}
getLineCount(): number {
return 1;
}
}
class TestView {
private readonly _model: SingleLineTestModel;
constructor(model: SingleLineTestModel) {
this._model = model;
}
public paint(output: HTMLElement) {
dom.clearNode(output);
for (let i = 1; i <= this._model.getLineCount(); i++) {
const textNode = document.createTextNode(this._model.getModelLineContent(i));
output.appendChild(textNode);
const br = document.createElement('br');
output.appendChild(br);
}
}
}
function doCreateTest(description: string, inputStr: string, expectedStr: string): HTMLElement {
let cursorOffset: number = 0;
let cursorLength: number = 0;
const container = document.createElement('div');
container.className = 'container';
const title = document.createElement('div');
title.className = 'title';
const inputStrStrong = document.createElement('strong');
inputStrStrong.innerText = inputStr;
title.innerText = description + '. Type ';
title.appendChild(inputStrStrong);
container.appendChild(title);
const startBtn = document.createElement('button');
startBtn.innerText = 'Start';
container.appendChild(startBtn);
const input = document.createElement('textarea');
input.setAttribute('rows', '10');
input.setAttribute('cols', '40');
container.appendChild(input);
const model = new SingleLineTestModel('some text');
const textAreaInputHost: ITextAreaInputHost = {
getDataToCopy: () => {
return {
isFromEmptySelection: false,
multicursorText: null,
text: '',
html: undefined,
mode: null
};
},
getScreenReaderContent: (): TextAreaState => {
const selection = new Range(1, 1 + cursorOffset, 1, 1 + cursorOffset + cursorLength);
return PagedScreenReaderStrategy.fromEditorSelection(model, selection, 10, true);
},
deduceModelPosition: (viewAnchorPosition: Position, deltaOffset: number, lineFeedCnt: number): Position => {
return null!;
}
};
const handler = new TextAreaInput(textAreaInputHost, new TextAreaWrapper(input), platform.OS, {
isAndroid: browser.isAndroid,
isFirefox: browser.isFirefox,
isChrome: browser.isChrome,
isSafari: browser.isSafari,
}, new TestAccessibilityService(), new NullLogService());
const output = document.createElement('pre');
output.className = 'output';
container.appendChild(output);
const check = document.createElement('pre');
check.className = 'check';
container.appendChild(check);
const br = document.createElement('br');
br.style.clear = 'both';
container.appendChild(br);
const view = new TestView(model);
const updatePosition = (off: number, len: number) => {
cursorOffset = off;
cursorLength = len;
handler.writeNativeTextAreaContent('selection changed');
handler.focusTextArea();
};
const updateModelAndPosition = (text: string, off: number, len: number) => {
model._setText(text);
updatePosition(off, len);
view.paint(output);
const expected = 'some ' + expectedStr + ' text';
if (text === expected) {
check.innerText = '[GOOD]';
check.className = 'check good';
} else {
check.innerText = '[BAD]';
check.className = 'check bad';
}
check.appendChild(document.createTextNode(expected));
};
handler.onType((e) => {
console.log('type text: ' + e.text + ', replaceCharCnt: ' + e.replacePrevCharCnt);
const text = model.getModelLineContent(1);
const preText = text.substring(0, cursorOffset - e.replacePrevCharCnt);
const postText = text.substring(cursorOffset + cursorLength);
const midText = e.text;
updateModelAndPosition(preText + midText + postText, (preText + midText).length, 0);
});
view.paint(output);
startBtn.onclick = function () {
updateModelAndPosition('some text', 5, 0);
input.focus();
};
return container;
}
const TESTS = [
{ description: 'Japanese IME 1', in: 'sennsei [Enter]', out: 'せんせい' },
{ description: 'Japanese IME 2', in: 'konnichiha [Enter]', out: 'こんいちは' },
{ description: 'Japanese IME 3', in: 'mikann [Enter]', out: 'みかん' },
{ description: 'Korean IME 1', in: 'gksrmf [Space]', out: '한글 ' },
{ description: 'Chinese IME 1', in: '.,', out: '。,' },
{ description: 'Chinese IME 2', in: 'ni [Space] hao [Space]', out: '你好' },
{ description: 'Chinese IME 3', in: 'hazni [Space]', out: '哈祝你' },
{ description: 'Mac dead key 1', in: '`.', out: '`.' },
{ description: 'Mac hold key 1', in: 'e long press and 1', out: 'é' }
];
TESTS.forEach((t) => {
mainWindow.document.body.appendChild(doCreateTest(t.description, t.in, t.out));
});
| src/vs/editor/test/browser/controller/imeTester.ts | 0 | https://github.com/microsoft/vscode/commit/48a9149e6ad2cbc0f7ebfdb2ce6143627c077d1e | [
0.00017843574460130185,
0.00017384905368089676,
0.00016895953740458935,
0.00017378822667524219,
0.0000024936950921983225
] |
{
"id": 8,
"code_window": [
"\n",
"\t\tctrl.acceptInput();\n",
"\n",
"\t\tawait ctrl.waitFor([State.MAKE_REQUEST, State.APPLY_RESPONSE, State.SHOW_RESPONSE, State.WAIT_FOR_INPUT]);\n",
"\n",
"\t\tassert.deepStrictEqual(session.wholeRange.value, new Range(4, 1, 4, 12));\n",
"\n",
"\t\tawait ctrl.cancelSession();\n",
"\t\tawait r;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tassert.deepStrictEqual(session.wholeRange.value, new Range(4, 1, 4, 3));\n"
],
"file_path": "src/vs/workbench/contrib/inlineChat/test/browser/inlineChatController.test.ts",
"type": "replace",
"edit_start_line_idx": 302
} | {
parts: [
{
range: {
start: 0,
endExclusive: 5
},
editorRange: {
startLineNumber: 1,
startColumn: 1,
endLineNumber: 2,
endColumn: 1
},
text: " \n",
kind: "text"
},
{
range: {
start: 5,
endExclusive: 11
},
editorRange: {
startLineNumber: 2,
startColumn: 1,
endLineNumber: 2,
endColumn: 7
},
agent: {
id: "agent",
metadata: { description: "" },
provideSlashCommands: [Function provideSlashCommands]
},
kind: "agent"
},
{
range: {
start: 11,
endExclusive: 12
},
editorRange: {
startLineNumber: 2,
startColumn: 7,
endLineNumber: 3,
endColumn: 1
},
text: "\n",
kind: "text"
},
{
range: {
start: 12,
endExclusive: 23
},
editorRange: {
startLineNumber: 3,
startColumn: 1,
endLineNumber: 3,
endColumn: 12
},
command: {
name: "subCommand",
description: ""
},
kind: "subcommand"
},
{
range: {
start: 23,
endExclusive: 30
},
editorRange: {
startLineNumber: 3,
startColumn: 12,
endLineNumber: 3,
endColumn: 19
},
text: " Thanks",
kind: "text"
}
],
text: " \n@agent\n/subCommand Thanks"
} | src/vs/workbench/contrib/chat/test/common/__snapshots__/ChatRequestParser_agent_and_subcommand_after_newline.0.snap | 0 | https://github.com/microsoft/vscode/commit/48a9149e6ad2cbc0f7ebfdb2ce6143627c077d1e | [
0.00017427509010303766,
0.000171804815181531,
0.0001676244573900476,
0.00017197428678628057,
0.000002100138544847141
] |
{
"id": 0,
"code_window": [
"\n",
"function processAttrs (el) {\n",
" const list = el.attrsList\n",
" let i, l, name, rawName, value, arg, modifiers, isProp\n",
" for (i = 0, l = list.length; i < l; i++) {\n",
" name = rawName = list[i].name\n",
" value = list[i].value\n",
" if (dirRE.test(name)) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" let i, l, name, rawName, value, modifiers, isProp\n"
],
"file_path": "src/compiler/parser/index.js",
"type": "replace",
"edit_start_line_idx": 429
} | /* @flow */
import { decode } from 'he'
import { parseHTML } from './html-parser'
import { parseText } from './text-parser'
import { parseFilters } from './filter-parser'
import { cached, no, camelize } from 'shared/util'
import { isIE, isServerRendering } from 'core/util/env'
import {
addProp,
addAttr,
baseWarn,
addHandler,
addDirective,
getBindingAttr,
getAndRemoveAttr,
pluckModuleFunction
} from '../helpers'
export const onRE = /^@|^v-on:/
export const dirRE = /^v-|^@|^:/
export const forAliasRE = /(.*?)\s+(?:in|of)\s+(.*)/
export const forIteratorRE = /\((\{[^}]*\}|[^,]*),([^,]*)(?:,([^,]*))?\)/
const argRE = /:(.*)$/
const bindRE = /^:|^v-bind:/
const modifierRE = /\.[^.]+/g
const decodeHTMLCached = cached(decode)
// configurable state
let warn
let delimiters
let transforms
let preTransforms
let postTransforms
let platformIsPreTag
let platformMustUseProp
let platformGetTagNamespace
/**
* Convert HTML string to AST.
*/
export function parse (
template: string,
options: CompilerOptions
): ASTElement | void {
warn = options.warn || baseWarn
platformGetTagNamespace = options.getTagNamespace || no
platformMustUseProp = options.mustUseProp || no
platformIsPreTag = options.isPreTag || no
preTransforms = pluckModuleFunction(options.modules, 'preTransformNode')
transforms = pluckModuleFunction(options.modules, 'transformNode')
postTransforms = pluckModuleFunction(options.modules, 'postTransformNode')
delimiters = options.delimiters
const stack = []
const preserveWhitespace = options.preserveWhitespace !== false
let root
let currentParent
let inVPre = false
let inPre = false
let warned = false
function endPre (element) {
// check pre state
if (element.pre) {
inVPre = false
}
if (platformIsPreTag(element.tag)) {
inPre = false
}
}
parseHTML(template, {
warn,
expectHTML: options.expectHTML,
isUnaryTag: options.isUnaryTag,
shouldDecodeNewlines: options.shouldDecodeNewlines,
start (tag, attrs, unary) {
// check namespace.
// inherit parent ns if there is one
const ns = (currentParent && currentParent.ns) || platformGetTagNamespace(tag)
// handle IE svg bug
/* istanbul ignore if */
if (isIE && ns === 'svg') {
attrs = guardIESVGBug(attrs)
}
const element: ASTElement = {
type: 1,
tag,
attrsList: attrs,
attrsMap: makeAttrsMap(attrs),
parent: currentParent,
children: []
}
if (ns) {
element.ns = ns
}
if (isForbiddenTag(element) && !isServerRendering()) {
element.forbidden = true
process.env.NODE_ENV !== 'production' && warn(
'Templates should only be responsible for mapping the state to the ' +
'UI. Avoid placing tags with side-effects in your templates, such as ' +
`<${tag}>` + ', as they will not be parsed.'
)
}
// apply pre-transforms
for (let i = 0; i < preTransforms.length; i++) {
preTransforms[i](element, options)
}
if (!inVPre) {
processPre(element)
if (element.pre) {
inVPre = true
}
}
if (platformIsPreTag(element.tag)) {
inPre = true
}
if (inVPre) {
processRawAttrs(element)
} else {
processFor(element)
processIf(element)
processOnce(element)
processKey(element)
// determine whether this is a plain element after
// removing structural attributes
element.plain = !element.key && !attrs.length
processRef(element)
processSlot(element)
processComponent(element)
for (let i = 0; i < transforms.length; i++) {
transforms[i](element, options)
}
processAttrs(element)
}
function checkRootConstraints (el) {
if (process.env.NODE_ENV !== 'production' && !warned) {
if (el.tag === 'slot' || el.tag === 'template') {
warned = true
warn(
`Cannot use <${el.tag}> as component root element because it may ` +
'contain multiple nodes.'
)
}
if (el.attrsMap.hasOwnProperty('v-for')) {
warned = true
warn(
'Cannot use v-for on stateful component root element because ' +
'it renders multiple elements.'
)
}
}
}
// tree management
if (!root) {
root = element
checkRootConstraints(root)
} else if (!stack.length) {
// allow root elements with v-if, v-else-if and v-else
if (root.if && (element.elseif || element.else)) {
checkRootConstraints(element)
addIfCondition(root, {
exp: element.elseif,
block: element
})
} else if (process.env.NODE_ENV !== 'production' && !warned) {
warned = true
warn(
`Component template should contain exactly one root element. ` +
`If you are using v-if on multiple elements, ` +
`use v-else-if to chain them instead.`
)
}
}
if (currentParent && !element.forbidden) {
if (element.elseif || element.else) {
processIfConditions(element, currentParent)
} else if (element.slotScope) { // scoped slot
currentParent.plain = false
const name = element.slotTarget || '"default"'
;(currentParent.scopedSlots || (currentParent.scopedSlots = {}))[name] = element
} else {
currentParent.children.push(element)
element.parent = currentParent
}
}
if (!unary) {
currentParent = element
stack.push(element)
} else {
endPre(element)
}
// apply post-transforms
for (let i = 0; i < postTransforms.length; i++) {
postTransforms[i](element, options)
}
},
end () {
// remove trailing whitespace
const element = stack[stack.length - 1]
const lastNode = element.children[element.children.length - 1]
if (lastNode && lastNode.type === 3 && lastNode.text === ' ' && !inPre) {
element.children.pop()
}
// pop stack
stack.length -= 1
currentParent = stack[stack.length - 1]
endPre(element)
},
chars (text: string) {
if (!currentParent) {
if (process.env.NODE_ENV !== 'production' && !warned && text === template) {
warned = true
warn(
'Component template requires a root element, rather than just text.'
)
}
return
}
// IE textarea placeholder bug
/* istanbul ignore if */
if (isIE &&
currentParent.tag === 'textarea' &&
currentParent.attrsMap.placeholder === text) {
return
}
const children = currentParent.children
text = inPre || text.trim()
? decodeHTMLCached(text)
// only preserve whitespace if its not right after a starting tag
: preserveWhitespace && children.length ? ' ' : ''
if (text) {
let expression
if (!inVPre && text !== ' ' && (expression = parseText(text, delimiters))) {
children.push({
type: 2,
expression,
text
})
} else if (text !== ' ' || !children.length || children[children.length - 1].text !== ' ') {
children.push({
type: 3,
text
})
}
}
}
})
return root
}
function processPre (el) {
if (getAndRemoveAttr(el, 'v-pre') != null) {
el.pre = true
}
}
function processRawAttrs (el) {
const l = el.attrsList.length
if (l) {
const attrs = el.attrs = new Array(l)
for (let i = 0; i < l; i++) {
attrs[i] = {
name: el.attrsList[i].name,
value: JSON.stringify(el.attrsList[i].value)
}
}
} else if (!el.pre) {
// non root node in pre blocks with no attributes
el.plain = true
}
}
function processKey (el) {
const exp = getBindingAttr(el, 'key')
if (exp) {
if (process.env.NODE_ENV !== 'production' && el.tag === 'template') {
warn(`<template> cannot be keyed. Place the key on real elements instead.`)
}
el.key = exp
}
}
function processRef (el) {
const ref = getBindingAttr(el, 'ref')
if (ref) {
el.ref = ref
el.refInFor = checkInFor(el)
}
}
function processFor (el) {
let exp
if ((exp = getAndRemoveAttr(el, 'v-for'))) {
const inMatch = exp.match(forAliasRE)
if (!inMatch) {
process.env.NODE_ENV !== 'production' && warn(
`Invalid v-for expression: ${exp}`
)
return
}
el.for = inMatch[2].trim()
const alias = inMatch[1].trim()
const iteratorMatch = alias.match(forIteratorRE)
if (iteratorMatch) {
el.alias = iteratorMatch[1].trim()
el.iterator1 = iteratorMatch[2].trim()
if (iteratorMatch[3]) {
el.iterator2 = iteratorMatch[3].trim()
}
} else {
el.alias = alias
}
}
}
function processIf (el) {
const exp = getAndRemoveAttr(el, 'v-if')
if (exp) {
el.if = exp
addIfCondition(el, {
exp: exp,
block: el
})
} else {
if (getAndRemoveAttr(el, 'v-else') != null) {
el.else = true
}
const elseif = getAndRemoveAttr(el, 'v-else-if')
if (elseif) {
el.elseif = elseif
}
}
}
function processIfConditions (el, parent) {
const prev = findPrevElement(parent.children)
if (prev && prev.if) {
addIfCondition(prev, {
exp: el.elseif,
block: el
})
} else if (process.env.NODE_ENV !== 'production') {
warn(
`v-${el.elseif ? ('else-if="' + el.elseif + '"') : 'else'} ` +
`used on element <${el.tag}> without corresponding v-if.`
)
}
}
function findPrevElement (children: Array<any>): ASTElement | void {
let i = children.length
while (i--) {
if (children[i].type === 1) {
return children[i]
} else {
if (process.env.NODE_ENV !== 'production' && children[i].text !== ' ') {
warn(
`text "${children[i].text.trim()}" between v-if and v-else(-if) ` +
`will be ignored.`
)
}
children.pop()
}
}
}
function addIfCondition (el, condition) {
if (!el.ifConditions) {
el.ifConditions = []
}
el.ifConditions.push(condition)
}
function processOnce (el) {
const once = getAndRemoveAttr(el, 'v-once')
if (once != null) {
el.once = true
}
}
function processSlot (el) {
if (el.tag === 'slot') {
el.slotName = getBindingAttr(el, 'name')
if (process.env.NODE_ENV !== 'production' && el.key) {
warn(
`\`key\` does not work on <slot> because slots are abstract outlets ` +
`and can possibly expand into multiple elements. ` +
`Use the key on a wrapping element instead.`
)
}
} else {
const slotTarget = getBindingAttr(el, 'slot')
if (slotTarget) {
el.slotTarget = slotTarget === '""' ? '"default"' : slotTarget
}
if (el.tag === 'template') {
el.slotScope = getAndRemoveAttr(el, 'scope')
}
}
}
function processComponent (el) {
let binding
if ((binding = getBindingAttr(el, 'is'))) {
el.component = binding
}
if (getAndRemoveAttr(el, 'inline-template') != null) {
el.inlineTemplate = true
}
}
function processAttrs (el) {
const list = el.attrsList
let i, l, name, rawName, value, arg, modifiers, isProp
for (i = 0, l = list.length; i < l; i++) {
name = rawName = list[i].name
value = list[i].value
if (dirRE.test(name)) {
// mark element as dynamic
el.hasBindings = true
// modifiers
modifiers = parseModifiers(name)
if (modifiers) {
name = name.replace(modifierRE, '')
}
if (bindRE.test(name)) { // v-bind
name = name.replace(bindRE, '')
value = parseFilters(value)
isProp = false
if (modifiers) {
if (modifiers.prop) {
isProp = true
name = camelize(name)
if (name === 'innerHtml') name = 'innerHTML'
}
if (modifiers.camel) {
name = camelize(name)
}
}
if (isProp || platformMustUseProp(el.tag, el.attrsMap.type, name)) {
addProp(el, name, value)
} else {
addAttr(el, name, value)
}
} else if (onRE.test(name)) { // v-on
name = name.replace(onRE, '')
addHandler(el, name, value, modifiers)
} else { // normal directives
name = name.replace(dirRE, '')
// parse arg
const argMatch = name.match(argRE)
if (argMatch && (arg = argMatch[1])) {
name = name.slice(0, -(arg.length + 1))
}
addDirective(el, name, rawName, value, arg, modifiers)
if (process.env.NODE_ENV !== 'production' && name === 'model') {
checkForAliasModel(el, value)
}
}
} else {
// literal attribute
if (process.env.NODE_ENV !== 'production') {
const expression = parseText(value, delimiters)
if (expression) {
warn(
`${name}="${value}": ` +
'Interpolation inside attributes has been removed. ' +
'Use v-bind or the colon shorthand instead. For example, ' +
'instead of <div id="{{ val }}">, use <div :id="val">.'
)
}
}
addAttr(el, name, JSON.stringify(value))
}
}
}
function checkInFor (el: ASTElement): boolean {
let parent = el
while (parent) {
if (parent.for !== undefined) {
return true
}
parent = parent.parent
}
return false
}
function parseModifiers (name: string): Object | void {
const match = name.match(modifierRE)
if (match) {
const ret = {}
match.forEach(m => { ret[m.slice(1)] = true })
return ret
}
}
function makeAttrsMap (attrs: Array<Object>): Object {
const map = {}
for (let i = 0, l = attrs.length; i < l; i++) {
if (process.env.NODE_ENV !== 'production' && map[attrs[i].name] && !isIE) {
warn('duplicate attribute: ' + attrs[i].name)
}
map[attrs[i].name] = attrs[i].value
}
return map
}
function isForbiddenTag (el): boolean {
return (
el.tag === 'style' ||
(el.tag === 'script' && (
!el.attrsMap.type ||
el.attrsMap.type === 'text/javascript'
))
)
}
const ieNSBug = /^xmlns:NS\d+/
const ieNSPrefix = /^NS\d+:/
/* istanbul ignore next */
function guardIESVGBug (attrs) {
const res = []
for (let i = 0; i < attrs.length; i++) {
const attr = attrs[i]
if (!ieNSBug.test(attr.name)) {
attr.name = attr.name.replace(ieNSPrefix, '')
res.push(attr)
}
}
return res
}
function checkForAliasModel (el, value) {
let _el = el
while (_el) {
if (_el.for && _el.alias === value) {
warn(
`<${el.tag} v-model="${value}">: ` +
`You are binding v-model directly to a v-for iteration alias. ` +
`This will not be able to modify the v-for source array because ` +
`writing to the alias is like modifying a function local variable. ` +
`Consider using an array of objects and use v-model on an object property instead.`
)
}
_el = _el.parent
}
}
| src/compiler/parser/index.js | 1 | https://github.com/vuejs/vue/commit/e7dfcc334d6f6513d2ed1cddfa28a08796e07df7 | [
0.9984752535820007,
0.2556471526622772,
0.00016350240912288427,
0.0005088731413707137,
0.4258776307106018
] |
{
"id": 0,
"code_window": [
"\n",
"function processAttrs (el) {\n",
" const list = el.attrsList\n",
" let i, l, name, rawName, value, arg, modifiers, isProp\n",
" for (i = 0, l = list.length; i < l; i++) {\n",
" name = rawName = list[i].name\n",
" value = list[i].value\n",
" if (dirRE.test(name)) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" let i, l, name, rawName, value, modifiers, isProp\n"
],
"file_path": "src/compiler/parser/index.js",
"type": "replace",
"edit_start_line_idx": 429
} | import Vue from 'vue'
describe('Options functional', () => {
it('should work', done => {
const vm = new Vue({
data: { test: 'foo' },
template: '<div><wrap :msg="test">bar</wrap></div>',
components: {
wrap: {
functional: true,
props: ['msg'],
render (h, { props, children }) {
return h('div', null, [props.msg, ' '].concat(children))
}
}
}
}).$mount()
expect(vm.$el.innerHTML).toBe('<div>foo bar</div>')
vm.test = 'qux'
waitForUpdate(() => {
expect(vm.$el.innerHTML).toBe('<div>qux bar</div>')
}).then(done)
})
it('should support returning more than one root node', () => {
const vm = new Vue({
template: `<div><test></test></div>`,
components: {
test: {
functional: true,
render (h) {
return [h('span', 'foo'), h('span', 'bar')]
}
}
}
}).$mount()
expect(vm.$el.innerHTML).toBe('<span>foo</span><span>bar</span>')
})
it('should support slots', () => {
const vm = new Vue({
data: { test: 'foo' },
template: '<div><wrap><div slot="a">foo</div><div slot="b">bar</div></wrap></div>',
components: {
wrap: {
functional: true,
props: ['msg'],
render (h, { slots }) {
slots = slots()
return h('div', null, [slots.b, slots.a])
}
}
}
}).$mount()
expect(vm.$el.innerHTML).toBe('<div><div>bar</div><div>foo</div></div>')
})
it('should let vnode raw data pass through', done => {
const onValid = jasmine.createSpy('valid')
const vm = new Vue({
data: { msg: 'hello' },
template: `<div>
<validate field="field1" @valid="onValid">
<input type="text" v-model="msg">
</validate>
</div>`,
components: {
validate: {
functional: true,
props: ['field'],
render (h, { props, children, data: { on }}) {
props.child = children[0]
return h('validate-control', { props, on })
}
},
'validate-control': {
props: ['field', 'child'],
render () {
return this.child
},
mounted () {
this.$el.addEventListener('input', this.onInput)
},
destroyed () {
this.$el.removeEventListener('input', this.onInput)
},
methods: {
onInput (e) {
const value = e.target.value
if (this.validate(value)) {
this.$emit('valid', this)
}
},
// something validation logic here
validate (val) {
return val.length > 0
}
}
}
},
methods: { onValid }
}).$mount()
document.body.appendChild(vm.$el)
const input = vm.$el.querySelector('input')
expect(onValid).not.toHaveBeenCalled()
waitForUpdate(() => {
input.value = 'foo'
triggerEvent(input, 'input')
}).then(() => {
expect(onValid).toHaveBeenCalled()
}).then(() => {
document.body.removeChild(vm.$el)
vm.$destroy()
}).then(done)
})
})
| test/unit/features/options/functional.spec.js | 0 | https://github.com/vuejs/vue/commit/e7dfcc334d6f6513d2ed1cddfa28a08796e07df7 | [
0.00028466799994930625,
0.00018151075346395373,
0.00016729488561395556,
0.00017199074500240386,
0.00003126277442788705
] |
{
"id": 0,
"code_window": [
"\n",
"function processAttrs (el) {\n",
" const list = el.attrsList\n",
" let i, l, name, rawName, value, arg, modifiers, isProp\n",
" for (i = 0, l = list.length; i < l; i++) {\n",
" name = rawName = list[i].name\n",
" value = list[i].value\n",
" if (dirRE.test(name)) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" let i, l, name, rawName, value, modifiers, isProp\n"
],
"file_path": "src/compiler/parser/index.js",
"type": "replace",
"edit_start_line_idx": 429
} | /* globals renderer */
// renderer is injected by weex factory wrapper
export const namespaceMap = {}
export function createElement (tagName) {
return new renderer.Element(tagName)
}
export function createElementNS (namespace, tagName) {
return new renderer.Element(namespace + ':' + tagName)
}
export function createTextNode (text) {
return new renderer.TextNode(text)
}
export function createComment (text) {
return new renderer.Comment(text)
}
export function insertBefore (node, target, before) {
if (target.nodeType === 3) {
if (node.type === 'text') {
node.setAttr('value', target.text)
target.parentNode = node
} else {
const text = createElement('text')
text.setAttr('value', target.text)
node.insertBefore(text, before)
}
return
}
node.insertBefore(target, before)
}
export function removeChild (node, child) {
if (child.nodeType === 3) {
node.setAttr('value', '')
return
}
node.removeChild(child)
}
export function appendChild (node, child) {
if (child.nodeType === 3) {
if (node.type === 'text') {
node.setAttr('value', child.text)
child.parentNode = node
} else {
const text = createElement('text')
text.setAttr('value', child.text)
node.appendChild(text)
}
return
}
node.appendChild(child)
}
export function parentNode (node) {
return node.parentNode
}
export function nextSibling (node) {
return node.nextSibling
}
export function tagName (node) {
return node.type
}
export function setTextContent (node, text) {
node.parentNode.setAttr('value', text)
}
export function setAttribute (node, key, val) {
node.setAttr(key, val)
}
| src/platforms/weex/runtime/node-ops.js | 0 | https://github.com/vuejs/vue/commit/e7dfcc334d6f6513d2ed1cddfa28a08796e07df7 | [
0.00017290805408265442,
0.00017084306455217302,
0.00016953550220932811,
0.00017079419922083616,
0.0000011486271205285448
] |
{
"id": 0,
"code_window": [
"\n",
"function processAttrs (el) {\n",
" const list = el.attrsList\n",
" let i, l, name, rawName, value, arg, modifiers, isProp\n",
" for (i = 0, l = list.length; i < l; i++) {\n",
" name = rawName = list[i].name\n",
" value = list[i].value\n",
" if (dirRE.test(name)) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" let i, l, name, rawName, value, modifiers, isProp\n"
],
"file_path": "src/compiler/parser/index.js",
"type": "replace",
"edit_start_line_idx": 429
} | import Vue from 'vue'
describe('Directive v-bind', () => {
it('normal attr', done => {
const vm = new Vue({
template: '<div><span :test="foo">hello</span></div>',
data: { foo: 'ok' }
}).$mount()
expect(vm.$el.firstChild.getAttribute('test')).toBe('ok')
vm.foo = 'again'
waitForUpdate(() => {
expect(vm.$el.firstChild.getAttribute('test')).toBe('again')
vm.foo = null
}).then(() => {
expect(vm.$el.firstChild.hasAttribute('test')).toBe(false)
vm.foo = false
}).then(() => {
expect(vm.$el.firstChild.hasAttribute('test')).toBe(false)
vm.foo = true
}).then(() => {
expect(vm.$el.firstChild.getAttribute('test')).toBe('true')
vm.foo = 0
}).then(() => {
expect(vm.$el.firstChild.getAttribute('test')).toBe('0')
}).then(done)
})
it('should set property for input value', done => {
const vm = new Vue({
template: `
<div>
<input type="text" :value="foo">
<input type="checkbox" :checked="bar">
</div>
`,
data: {
foo: 'ok',
bar: false
}
}).$mount()
expect(vm.$el.firstChild.value).toBe('ok')
expect(vm.$el.lastChild.checked).toBe(false)
vm.bar = true
waitForUpdate(() => {
expect(vm.$el.lastChild.checked).toBe(true)
}).then(done)
})
it('xlink', done => {
const vm = new Vue({
template: '<svg><a :xlink:special="foo"></a></svg>',
data: {
foo: 'ok'
}
}).$mount()
const xlinkNS = 'http://www.w3.org/1999/xlink'
expect(vm.$el.firstChild.getAttributeNS(xlinkNS, 'special')).toBe('ok')
vm.foo = 'again'
waitForUpdate(() => {
expect(vm.$el.firstChild.getAttributeNS(xlinkNS, 'special')).toBe('again')
vm.foo = null
}).then(() => {
expect(vm.$el.firstChild.hasAttributeNS(xlinkNS, 'special')).toBe(false)
vm.foo = true
}).then(() => {
expect(vm.$el.firstChild.getAttributeNS(xlinkNS, 'special')).toBe('true')
}).then(done)
})
it('enumerated attr', done => {
const vm = new Vue({
template: '<div><span :draggable="foo">hello</span></div>',
data: { foo: true }
}).$mount()
expect(vm.$el.firstChild.getAttribute('draggable')).toBe('true')
vm.foo = 'again'
waitForUpdate(() => {
expect(vm.$el.firstChild.getAttribute('draggable')).toBe('true')
vm.foo = null
}).then(() => {
expect(vm.$el.firstChild.getAttribute('draggable')).toBe('false')
vm.foo = ''
}).then(() => {
expect(vm.$el.firstChild.getAttribute('draggable')).toBe('true')
vm.foo = false
}).then(() => {
expect(vm.$el.firstChild.getAttribute('draggable')).toBe('false')
vm.foo = 'false'
}).then(() => {
expect(vm.$el.firstChild.getAttribute('draggable')).toBe('false')
}).then(done)
})
it('boolean attr', done => {
const vm = new Vue({
template: '<div><span :disabled="foo">hello</span></div>',
data: { foo: true }
}).$mount()
expect(vm.$el.firstChild.getAttribute('disabled')).toBe('disabled')
vm.foo = 'again'
waitForUpdate(() => {
expect(vm.$el.firstChild.getAttribute('disabled')).toBe('disabled')
vm.foo = null
}).then(() => {
expect(vm.$el.firstChild.hasAttribute('disabled')).toBe(false)
vm.foo = ''
}).then(() => {
expect(vm.$el.firstChild.hasAttribute('disabled')).toBe(true)
}).then(done)
})
it('.prop modifier', () => {
const vm = new Vue({
template: '<div><span v-bind:text-content.prop="foo"></span><span :inner-html.prop="bar"></span></div>',
data: {
foo: 'hello',
bar: '<span>qux</span>'
}
}).$mount()
expect(vm.$el.children[0].textContent).toBe('hello')
expect(vm.$el.children[1].innerHTML).toBe('<span>qux</span>')
})
it('.prop modifier with normal attribute binding', () => {
const vm = new Vue({
template: '<input :some.prop="some" :id="id">',
data: {
some: 'hello',
id: false
}
}).$mount()
expect(vm.$el.some).toBe('hello')
expect(vm.$el.getAttribute('id')).toBe(null)
})
it('.camel modifier', () => {
const vm = new Vue({
template: '<svg :view-box.camel="viewBox"></svg>',
data: {
viewBox: '0 0 1 1'
}
}).$mount()
expect(vm.$el.getAttribute('viewBox')).toBe('0 0 1 1')
})
it('bind object', done => {
const vm = new Vue({
template: '<input v-bind="test">',
data: {
test: {
id: 'test',
class: 'ok',
value: 'hello'
}
}
}).$mount()
expect(vm.$el.getAttribute('id')).toBe('test')
expect(vm.$el.getAttribute('class')).toBe('ok')
expect(vm.$el.value).toBe('hello')
vm.test.id = 'hi'
vm.test.value = 'bye'
waitForUpdate(() => {
expect(vm.$el.getAttribute('id')).toBe('hi')
expect(vm.$el.getAttribute('class')).toBe('ok')
expect(vm.$el.value).toBe('bye')
}).then(done)
})
it('bind object with class/style', done => {
const vm = new Vue({
template: '<input class="a" style="color:red" v-bind="test">',
data: {
test: {
id: 'test',
class: ['b', 'c'],
style: { fontSize: '12px' }
}
}
}).$mount()
expect(vm.$el.id).toBe('test')
expect(vm.$el.className).toBe('a b c')
expect(vm.$el.style.color).toBe('red')
expect(vm.$el.style.fontSize).toBe('12px')
vm.test.id = 'hi'
vm.test.class = ['d']
vm.test.style = { fontSize: '14px' }
waitForUpdate(() => {
expect(vm.$el.id).toBe('hi')
expect(vm.$el.className).toBe('a d')
expect(vm.$el.style.color).toBe('red')
expect(vm.$el.style.fontSize).toBe('14px')
}).then(done)
})
it('bind object as prop', done => {
const vm = new Vue({
template: '<input v-bind.prop="test">',
data: {
test: {
id: 'test',
className: 'ok',
value: 'hello'
}
}
}).$mount()
expect(vm.$el.id).toBe('test')
expect(vm.$el.className).toBe('ok')
expect(vm.$el.value).toBe('hello')
vm.test.id = 'hi'
vm.test.className = 'okay'
vm.test.value = 'bye'
waitForUpdate(() => {
expect(vm.$el.id).toBe('hi')
expect(vm.$el.className).toBe('okay')
expect(vm.$el.value).toBe('bye')
}).then(done)
})
it('bind array', done => {
const vm = new Vue({
template: '<input v-bind="test">',
data: {
test: [
{ id: 'test', class: 'ok' },
{ value: 'hello' }
]
}
}).$mount()
expect(vm.$el.getAttribute('id')).toBe('test')
expect(vm.$el.getAttribute('class')).toBe('ok')
expect(vm.$el.value).toBe('hello')
vm.test[0].id = 'hi'
vm.test[1].value = 'bye'
waitForUpdate(() => {
expect(vm.$el.getAttribute('id')).toBe('hi')
expect(vm.$el.getAttribute('class')).toBe('ok')
expect(vm.$el.value).toBe('bye')
}).then(done)
})
it('warn expect object', () => {
new Vue({
template: '<input v-bind="test">',
data: {
test: 1
}
}).$mount()
expect('v-bind without argument expects an Object or Array value').toHaveBeenWarned()
})
it('set value for option element', () => {
const vm = new Vue({
template: '<select><option :value="val">val</option></select>',
data: {
val: 'val'
}
}).$mount()
// check value attribute
expect(vm.$el.options[0].getAttribute('value')).toBe('val')
})
// a vdom patch edge case where the user has several un-keyed elements of the
// same tag next to each other, and toggling them.
it('properly update for toggling un-keyed children', done => {
const vm = new Vue({
template: `
<div>
<div v-if="ok" id="a" data-test="1"></div>
<div v-if="!ok" id="b"></div>
</div>
`,
data: {
ok: true
}
}).$mount()
expect(vm.$el.children[0].id).toBe('a')
expect(vm.$el.children[0].getAttribute('data-test')).toBe('1')
vm.ok = false
waitForUpdate(() => {
expect(vm.$el.children[0].id).toBe('b')
expect(vm.$el.children[0].getAttribute('data-test')).toBe(null)
}).then(done)
})
})
| test/unit/features/directives/bind.spec.js | 0 | https://github.com/vuejs/vue/commit/e7dfcc334d6f6513d2ed1cddfa28a08796e07df7 | [
0.00017757726891431957,
0.00017311547708231956,
0.0001664560113567859,
0.0001737261045491323,
0.000003644719981821254
] |
{
"id": 1,
"code_window": [
" name = name.replace(dirRE, '')\n",
" // parse arg\n",
" const argMatch = name.match(argRE)\n",
" if (argMatch && (arg = argMatch[1])) {\n",
" name = name.slice(0, -(arg.length + 1))\n",
" }\n",
" addDirective(el, name, rawName, value, arg, modifiers)\n",
" if (process.env.NODE_ENV !== 'production' && name === 'model') {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const arg = argMatch && argMatch[1]\n",
" if (arg) {\n"
],
"file_path": "src/compiler/parser/index.js",
"type": "replace",
"edit_start_line_idx": 467
} | /* @flow */
import { decode } from 'he'
import { parseHTML } from './html-parser'
import { parseText } from './text-parser'
import { parseFilters } from './filter-parser'
import { cached, no, camelize } from 'shared/util'
import { isIE, isServerRendering } from 'core/util/env'
import {
addProp,
addAttr,
baseWarn,
addHandler,
addDirective,
getBindingAttr,
getAndRemoveAttr,
pluckModuleFunction
} from '../helpers'
export const onRE = /^@|^v-on:/
export const dirRE = /^v-|^@|^:/
export const forAliasRE = /(.*?)\s+(?:in|of)\s+(.*)/
export const forIteratorRE = /\((\{[^}]*\}|[^,]*),([^,]*)(?:,([^,]*))?\)/
const argRE = /:(.*)$/
const bindRE = /^:|^v-bind:/
const modifierRE = /\.[^.]+/g
const decodeHTMLCached = cached(decode)
// configurable state
let warn
let delimiters
let transforms
let preTransforms
let postTransforms
let platformIsPreTag
let platformMustUseProp
let platformGetTagNamespace
/**
* Convert HTML string to AST.
*/
export function parse (
template: string,
options: CompilerOptions
): ASTElement | void {
warn = options.warn || baseWarn
platformGetTagNamespace = options.getTagNamespace || no
platformMustUseProp = options.mustUseProp || no
platformIsPreTag = options.isPreTag || no
preTransforms = pluckModuleFunction(options.modules, 'preTransformNode')
transforms = pluckModuleFunction(options.modules, 'transformNode')
postTransforms = pluckModuleFunction(options.modules, 'postTransformNode')
delimiters = options.delimiters
const stack = []
const preserveWhitespace = options.preserveWhitespace !== false
let root
let currentParent
let inVPre = false
let inPre = false
let warned = false
function endPre (element) {
// check pre state
if (element.pre) {
inVPre = false
}
if (platformIsPreTag(element.tag)) {
inPre = false
}
}
parseHTML(template, {
warn,
expectHTML: options.expectHTML,
isUnaryTag: options.isUnaryTag,
shouldDecodeNewlines: options.shouldDecodeNewlines,
start (tag, attrs, unary) {
// check namespace.
// inherit parent ns if there is one
const ns = (currentParent && currentParent.ns) || platformGetTagNamespace(tag)
// handle IE svg bug
/* istanbul ignore if */
if (isIE && ns === 'svg') {
attrs = guardIESVGBug(attrs)
}
const element: ASTElement = {
type: 1,
tag,
attrsList: attrs,
attrsMap: makeAttrsMap(attrs),
parent: currentParent,
children: []
}
if (ns) {
element.ns = ns
}
if (isForbiddenTag(element) && !isServerRendering()) {
element.forbidden = true
process.env.NODE_ENV !== 'production' && warn(
'Templates should only be responsible for mapping the state to the ' +
'UI. Avoid placing tags with side-effects in your templates, such as ' +
`<${tag}>` + ', as they will not be parsed.'
)
}
// apply pre-transforms
for (let i = 0; i < preTransforms.length; i++) {
preTransforms[i](element, options)
}
if (!inVPre) {
processPre(element)
if (element.pre) {
inVPre = true
}
}
if (platformIsPreTag(element.tag)) {
inPre = true
}
if (inVPre) {
processRawAttrs(element)
} else {
processFor(element)
processIf(element)
processOnce(element)
processKey(element)
// determine whether this is a plain element after
// removing structural attributes
element.plain = !element.key && !attrs.length
processRef(element)
processSlot(element)
processComponent(element)
for (let i = 0; i < transforms.length; i++) {
transforms[i](element, options)
}
processAttrs(element)
}
function checkRootConstraints (el) {
if (process.env.NODE_ENV !== 'production' && !warned) {
if (el.tag === 'slot' || el.tag === 'template') {
warned = true
warn(
`Cannot use <${el.tag}> as component root element because it may ` +
'contain multiple nodes.'
)
}
if (el.attrsMap.hasOwnProperty('v-for')) {
warned = true
warn(
'Cannot use v-for on stateful component root element because ' +
'it renders multiple elements.'
)
}
}
}
// tree management
if (!root) {
root = element
checkRootConstraints(root)
} else if (!stack.length) {
// allow root elements with v-if, v-else-if and v-else
if (root.if && (element.elseif || element.else)) {
checkRootConstraints(element)
addIfCondition(root, {
exp: element.elseif,
block: element
})
} else if (process.env.NODE_ENV !== 'production' && !warned) {
warned = true
warn(
`Component template should contain exactly one root element. ` +
`If you are using v-if on multiple elements, ` +
`use v-else-if to chain them instead.`
)
}
}
if (currentParent && !element.forbidden) {
if (element.elseif || element.else) {
processIfConditions(element, currentParent)
} else if (element.slotScope) { // scoped slot
currentParent.plain = false
const name = element.slotTarget || '"default"'
;(currentParent.scopedSlots || (currentParent.scopedSlots = {}))[name] = element
} else {
currentParent.children.push(element)
element.parent = currentParent
}
}
if (!unary) {
currentParent = element
stack.push(element)
} else {
endPre(element)
}
// apply post-transforms
for (let i = 0; i < postTransforms.length; i++) {
postTransforms[i](element, options)
}
},
end () {
// remove trailing whitespace
const element = stack[stack.length - 1]
const lastNode = element.children[element.children.length - 1]
if (lastNode && lastNode.type === 3 && lastNode.text === ' ' && !inPre) {
element.children.pop()
}
// pop stack
stack.length -= 1
currentParent = stack[stack.length - 1]
endPre(element)
},
chars (text: string) {
if (!currentParent) {
if (process.env.NODE_ENV !== 'production' && !warned && text === template) {
warned = true
warn(
'Component template requires a root element, rather than just text.'
)
}
return
}
// IE textarea placeholder bug
/* istanbul ignore if */
if (isIE &&
currentParent.tag === 'textarea' &&
currentParent.attrsMap.placeholder === text) {
return
}
const children = currentParent.children
text = inPre || text.trim()
? decodeHTMLCached(text)
// only preserve whitespace if its not right after a starting tag
: preserveWhitespace && children.length ? ' ' : ''
if (text) {
let expression
if (!inVPre && text !== ' ' && (expression = parseText(text, delimiters))) {
children.push({
type: 2,
expression,
text
})
} else if (text !== ' ' || !children.length || children[children.length - 1].text !== ' ') {
children.push({
type: 3,
text
})
}
}
}
})
return root
}
function processPre (el) {
if (getAndRemoveAttr(el, 'v-pre') != null) {
el.pre = true
}
}
function processRawAttrs (el) {
const l = el.attrsList.length
if (l) {
const attrs = el.attrs = new Array(l)
for (let i = 0; i < l; i++) {
attrs[i] = {
name: el.attrsList[i].name,
value: JSON.stringify(el.attrsList[i].value)
}
}
} else if (!el.pre) {
// non root node in pre blocks with no attributes
el.plain = true
}
}
function processKey (el) {
const exp = getBindingAttr(el, 'key')
if (exp) {
if (process.env.NODE_ENV !== 'production' && el.tag === 'template') {
warn(`<template> cannot be keyed. Place the key on real elements instead.`)
}
el.key = exp
}
}
function processRef (el) {
const ref = getBindingAttr(el, 'ref')
if (ref) {
el.ref = ref
el.refInFor = checkInFor(el)
}
}
function processFor (el) {
let exp
if ((exp = getAndRemoveAttr(el, 'v-for'))) {
const inMatch = exp.match(forAliasRE)
if (!inMatch) {
process.env.NODE_ENV !== 'production' && warn(
`Invalid v-for expression: ${exp}`
)
return
}
el.for = inMatch[2].trim()
const alias = inMatch[1].trim()
const iteratorMatch = alias.match(forIteratorRE)
if (iteratorMatch) {
el.alias = iteratorMatch[1].trim()
el.iterator1 = iteratorMatch[2].trim()
if (iteratorMatch[3]) {
el.iterator2 = iteratorMatch[3].trim()
}
} else {
el.alias = alias
}
}
}
function processIf (el) {
const exp = getAndRemoveAttr(el, 'v-if')
if (exp) {
el.if = exp
addIfCondition(el, {
exp: exp,
block: el
})
} else {
if (getAndRemoveAttr(el, 'v-else') != null) {
el.else = true
}
const elseif = getAndRemoveAttr(el, 'v-else-if')
if (elseif) {
el.elseif = elseif
}
}
}
function processIfConditions (el, parent) {
const prev = findPrevElement(parent.children)
if (prev && prev.if) {
addIfCondition(prev, {
exp: el.elseif,
block: el
})
} else if (process.env.NODE_ENV !== 'production') {
warn(
`v-${el.elseif ? ('else-if="' + el.elseif + '"') : 'else'} ` +
`used on element <${el.tag}> without corresponding v-if.`
)
}
}
function findPrevElement (children: Array<any>): ASTElement | void {
let i = children.length
while (i--) {
if (children[i].type === 1) {
return children[i]
} else {
if (process.env.NODE_ENV !== 'production' && children[i].text !== ' ') {
warn(
`text "${children[i].text.trim()}" between v-if and v-else(-if) ` +
`will be ignored.`
)
}
children.pop()
}
}
}
function addIfCondition (el, condition) {
if (!el.ifConditions) {
el.ifConditions = []
}
el.ifConditions.push(condition)
}
function processOnce (el) {
const once = getAndRemoveAttr(el, 'v-once')
if (once != null) {
el.once = true
}
}
function processSlot (el) {
if (el.tag === 'slot') {
el.slotName = getBindingAttr(el, 'name')
if (process.env.NODE_ENV !== 'production' && el.key) {
warn(
`\`key\` does not work on <slot> because slots are abstract outlets ` +
`and can possibly expand into multiple elements. ` +
`Use the key on a wrapping element instead.`
)
}
} else {
const slotTarget = getBindingAttr(el, 'slot')
if (slotTarget) {
el.slotTarget = slotTarget === '""' ? '"default"' : slotTarget
}
if (el.tag === 'template') {
el.slotScope = getAndRemoveAttr(el, 'scope')
}
}
}
function processComponent (el) {
let binding
if ((binding = getBindingAttr(el, 'is'))) {
el.component = binding
}
if (getAndRemoveAttr(el, 'inline-template') != null) {
el.inlineTemplate = true
}
}
function processAttrs (el) {
const list = el.attrsList
let i, l, name, rawName, value, arg, modifiers, isProp
for (i = 0, l = list.length; i < l; i++) {
name = rawName = list[i].name
value = list[i].value
if (dirRE.test(name)) {
// mark element as dynamic
el.hasBindings = true
// modifiers
modifiers = parseModifiers(name)
if (modifiers) {
name = name.replace(modifierRE, '')
}
if (bindRE.test(name)) { // v-bind
name = name.replace(bindRE, '')
value = parseFilters(value)
isProp = false
if (modifiers) {
if (modifiers.prop) {
isProp = true
name = camelize(name)
if (name === 'innerHtml') name = 'innerHTML'
}
if (modifiers.camel) {
name = camelize(name)
}
}
if (isProp || platformMustUseProp(el.tag, el.attrsMap.type, name)) {
addProp(el, name, value)
} else {
addAttr(el, name, value)
}
} else if (onRE.test(name)) { // v-on
name = name.replace(onRE, '')
addHandler(el, name, value, modifiers)
} else { // normal directives
name = name.replace(dirRE, '')
// parse arg
const argMatch = name.match(argRE)
if (argMatch && (arg = argMatch[1])) {
name = name.slice(0, -(arg.length + 1))
}
addDirective(el, name, rawName, value, arg, modifiers)
if (process.env.NODE_ENV !== 'production' && name === 'model') {
checkForAliasModel(el, value)
}
}
} else {
// literal attribute
if (process.env.NODE_ENV !== 'production') {
const expression = parseText(value, delimiters)
if (expression) {
warn(
`${name}="${value}": ` +
'Interpolation inside attributes has been removed. ' +
'Use v-bind or the colon shorthand instead. For example, ' +
'instead of <div id="{{ val }}">, use <div :id="val">.'
)
}
}
addAttr(el, name, JSON.stringify(value))
}
}
}
function checkInFor (el: ASTElement): boolean {
let parent = el
while (parent) {
if (parent.for !== undefined) {
return true
}
parent = parent.parent
}
return false
}
function parseModifiers (name: string): Object | void {
const match = name.match(modifierRE)
if (match) {
const ret = {}
match.forEach(m => { ret[m.slice(1)] = true })
return ret
}
}
function makeAttrsMap (attrs: Array<Object>): Object {
const map = {}
for (let i = 0, l = attrs.length; i < l; i++) {
if (process.env.NODE_ENV !== 'production' && map[attrs[i].name] && !isIE) {
warn('duplicate attribute: ' + attrs[i].name)
}
map[attrs[i].name] = attrs[i].value
}
return map
}
function isForbiddenTag (el): boolean {
return (
el.tag === 'style' ||
(el.tag === 'script' && (
!el.attrsMap.type ||
el.attrsMap.type === 'text/javascript'
))
)
}
const ieNSBug = /^xmlns:NS\d+/
const ieNSPrefix = /^NS\d+:/
/* istanbul ignore next */
function guardIESVGBug (attrs) {
const res = []
for (let i = 0; i < attrs.length; i++) {
const attr = attrs[i]
if (!ieNSBug.test(attr.name)) {
attr.name = attr.name.replace(ieNSPrefix, '')
res.push(attr)
}
}
return res
}
function checkForAliasModel (el, value) {
let _el = el
while (_el) {
if (_el.for && _el.alias === value) {
warn(
`<${el.tag} v-model="${value}">: ` +
`You are binding v-model directly to a v-for iteration alias. ` +
`This will not be able to modify the v-for source array because ` +
`writing to the alias is like modifying a function local variable. ` +
`Consider using an array of objects and use v-model on an object property instead.`
)
}
_el = _el.parent
}
}
| src/compiler/parser/index.js | 1 | https://github.com/vuejs/vue/commit/e7dfcc334d6f6513d2ed1cddfa28a08796e07df7 | [
0.9977458119392395,
0.04932218790054321,
0.00015983478806447238,
0.00017092181951738894,
0.2050291895866394
] |
{
"id": 1,
"code_window": [
" name = name.replace(dirRE, '')\n",
" // parse arg\n",
" const argMatch = name.match(argRE)\n",
" if (argMatch && (arg = argMatch[1])) {\n",
" name = name.slice(0, -(arg.length + 1))\n",
" }\n",
" addDirective(el, name, rawName, value, arg, modifiers)\n",
" if (process.env.NODE_ENV !== 'production' && name === 'model') {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const arg = argMatch && argMatch[1]\n",
" if (arg) {\n"
],
"file_path": "src/compiler/parser/index.js",
"type": "replace",
"edit_start_line_idx": 467
} | /* @flow */
const MAX_STACK_DEPTH = 1000
export function createWriteFunction (
write: (text: string, next: Function) => ?boolean,
onError: Function
): Function {
let stackDepth = 0
const cachedWrite = (text, next) => {
if (text && cachedWrite.caching) {
cachedWrite.cacheBuffer[cachedWrite.cacheBuffer.length - 1] += text
}
const waitForNext = write(text, next)
if (!waitForNext) {
if (stackDepth >= MAX_STACK_DEPTH) {
process.nextTick(() => {
try { next() } catch (e) {
onError(e)
}
})
} else {
stackDepth++
next()
stackDepth--
}
}
}
cachedWrite.caching = false
cachedWrite.cacheBuffer = []
return cachedWrite
}
| src/server/write.js | 0 | https://github.com/vuejs/vue/commit/e7dfcc334d6f6513d2ed1cddfa28a08796e07df7 | [
0.00017213063256349415,
0.00016990686708595604,
0.00016695655358489603,
0.00017027012654580176,
0.0000019846904706355417
] |
{
"id": 1,
"code_window": [
" name = name.replace(dirRE, '')\n",
" // parse arg\n",
" const argMatch = name.match(argRE)\n",
" if (argMatch && (arg = argMatch[1])) {\n",
" name = name.slice(0, -(arg.length + 1))\n",
" }\n",
" addDirective(el, name, rawName, value, arg, modifiers)\n",
" if (process.env.NODE_ENV !== 'production' && name === 'model') {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const arg = argMatch && argMatch[1]\n",
" if (arg) {\n"
],
"file_path": "src/compiler/parser/index.js",
"type": "replace",
"edit_start_line_idx": 467
} | /* @flow */
import { cached, extend, toObject } from 'shared/util'
export const parseStyleText = cached(function (cssText) {
const res = {}
const listDelimiter = /;(?![^(]*\))/g
const propertyDelimiter = /:(.+)/
cssText.split(listDelimiter).forEach(function (item) {
if (item) {
var tmp = item.split(propertyDelimiter)
tmp.length > 1 && (res[tmp[0].trim()] = tmp[1].trim())
}
})
return res
})
// merge static and dynamic style data on the same vnode
function normalizeStyleData (data: VNodeData): ?Object {
const style = normalizeStyleBinding(data.style)
// static style is pre-processed into an object during compilation
// and is always a fresh object, so it's safe to merge into it
return data.staticStyle
? extend(data.staticStyle, style)
: style
}
// normalize possible array / string values into Object
export function normalizeStyleBinding (bindingStyle: any): ?Object {
if (Array.isArray(bindingStyle)) {
return toObject(bindingStyle)
}
if (typeof bindingStyle === 'string') {
return parseStyleText(bindingStyle)
}
return bindingStyle
}
/**
* parent component style should be after child's
* so that parent component's style could override it
*/
export function getStyle (vnode: VNode, checkChild: boolean): Object {
const res = {}
let styleData
if (checkChild) {
let childNode = vnode
while (childNode.componentInstance) {
childNode = childNode.componentInstance._vnode
if (childNode.data && (styleData = normalizeStyleData(childNode.data))) {
extend(res, styleData)
}
}
}
if ((styleData = normalizeStyleData(vnode.data))) {
extend(res, styleData)
}
let parentNode = vnode
while ((parentNode = parentNode.parent)) {
if (parentNode.data && (styleData = normalizeStyleData(parentNode.data))) {
extend(res, styleData)
}
}
return res
}
| src/platforms/web/util/style.js | 0 | https://github.com/vuejs/vue/commit/e7dfcc334d6f6513d2ed1cddfa28a08796e07df7 | [
0.00017478766676504165,
0.0001699936401564628,
0.00016484524530824274,
0.0001698824344202876,
0.0000034507529562688433
] |
{
"id": 1,
"code_window": [
" name = name.replace(dirRE, '')\n",
" // parse arg\n",
" const argMatch = name.match(argRE)\n",
" if (argMatch && (arg = argMatch[1])) {\n",
" name = name.slice(0, -(arg.length + 1))\n",
" }\n",
" addDirective(el, name, rawName, value, arg, modifiers)\n",
" if (process.env.NODE_ENV !== 'production' && name === 'model') {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const arg = argMatch && argMatch[1]\n",
" if (arg) {\n"
],
"file_path": "src/compiler/parser/index.js",
"type": "replace",
"edit_start_line_idx": 467
} | /* @flow */
import { genStaticKeys } from 'shared/util'
import { createCompiler } from 'compiler/index'
import modules from './modules/index'
import directives from './directives/index'
import {
isUnaryTag,
mustUseProp,
isReservedTag,
getTagNamespace
} from '../util/index'
export const baseOptions: CompilerOptions = {
modules,
directives,
isUnaryTag,
mustUseProp,
isReservedTag,
getTagNamespace,
preserveWhitespace: false,
staticKeys: genStaticKeys(modules)
}
const { compile, compileToFunctions } = createCompiler(baseOptions)
export { compile, compileToFunctions }
| src/platforms/weex/compiler/index.js | 0 | https://github.com/vuejs/vue/commit/e7dfcc334d6f6513d2ed1cddfa28a08796e07df7 | [
0.00017274325364269316,
0.0001695756072876975,
0.00016716125537641346,
0.00016882232739590108,
0.000002340264018130256
] |
{
"id": 2,
"code_window": [
"describe('codegen', () => {\n",
" it('generate directive', () => {\n",
" assertCodegen(\n",
" '<p v-custom1:arg1.modifier=\"value1\" v-custom2></p>',\n",
" `with(this){return _c('p',{directives:[{name:\"custom1\",rawName:\"v-custom1:arg1.modifier\",value:(value1),expression:\"value1\",arg:\"arg1\",modifiers:{\"modifier\":true}},{name:\"custom2\",rawName:\"v-custom2\",arg:\"arg1\"}]})}`\n",
" )\n",
" })\n",
"\n",
" it('generate filters', () => {\n",
" assertCodegen(\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" `with(this){return _c('p',{directives:[{name:\"custom1\",rawName:\"v-custom1:arg1.modifier\",value:(value1),expression:\"value1\",arg:\"arg1\",modifiers:{\"modifier\":true}},{name:\"custom2\",rawName:\"v-custom2\"}]})}`\n"
],
"file_path": "test/unit/modules/compiler/codegen.spec.js",
"type": "replace",
"edit_start_line_idx": 35
} | import { parse } from 'compiler/parser/index'
import { optimize } from 'compiler/optimizer'
import { generate } from 'compiler/codegen'
import { isObject } from 'shared/util'
import { isReservedTag } from 'web/util/index'
import { baseOptions } from 'web/compiler/index'
function assertCodegen (template, generatedCode, ...args) {
let staticRenderFnCodes = []
let generateOptions = baseOptions
let proc = null
let len = args.length
while (len--) {
const arg = args[len]
if (Array.isArray(arg)) {
staticRenderFnCodes = arg
} else if (isObject(arg)) {
generateOptions = arg
} else if (typeof arg === 'function') {
proc = arg
}
}
const ast = parse(template, baseOptions)
optimize(ast, baseOptions)
proc && proc(ast)
const res = generate(ast, generateOptions)
expect(res.render).toBe(generatedCode)
expect(res.staticRenderFns).toEqual(staticRenderFnCodes)
}
/* eslint-disable quotes */
describe('codegen', () => {
it('generate directive', () => {
assertCodegen(
'<p v-custom1:arg1.modifier="value1" v-custom2></p>',
`with(this){return _c('p',{directives:[{name:"custom1",rawName:"v-custom1:arg1.modifier",value:(value1),expression:"value1",arg:"arg1",modifiers:{"modifier":true}},{name:"custom2",rawName:"v-custom2",arg:"arg1"}]})}`
)
})
it('generate filters', () => {
assertCodegen(
'<div :id="a | b | c">{{ d | e | f }}</div>',
`with(this){return _c('div',{attrs:{"id":_f("c")(_f("b")(a))}},[_v(_s(_f("f")(_f("e")(d))))])}`
)
})
it('generate v-for directive', () => {
assertCodegen(
'<div><li v-for="item in items" :key="item.uid"></li></div>',
`with(this){return _c('div',_l((items),function(item){return _c('li',{key:item.uid})}))}`
)
// iterator syntax
assertCodegen(
'<div><li v-for="(item, i) in items"></li></div>',
`with(this){return _c('div',_l((items),function(item,i){return _c('li')}))}`
)
assertCodegen(
'<div><li v-for="(item, key, index) in items"></li></div>',
`with(this){return _c('div',_l((items),function(item,key,index){return _c('li')}))}`
)
// destructuring
assertCodegen(
'<div><li v-for="{ a, b } in items"></li></div>',
`with(this){return _c('div',_l((items),function({ a, b }){return _c('li')}))}`
)
assertCodegen(
'<div><li v-for="({ a, b }, key, index) in items"></li></div>',
`with(this){return _c('div',_l((items),function({ a, b },key,index){return _c('li')}))}`
)
// v-for with extra element
assertCodegen(
'<div><p></p><li v-for="item in items"></li></div>',
`with(this){return _c('div',[_c('p'),_l((items),function(item){return _c('li')})],2)}`
)
})
it('generate v-if directive', () => {
assertCodegen(
'<p v-if="show">hello</p>',
`with(this){return (show)?_c('p',[_v("hello")]):_e()}`
)
})
it('generate v-else directive', () => {
assertCodegen(
'<div><p v-if="show">hello</p><p v-else>world</p></div>',
`with(this){return _c('div',[(show)?_c('p',[_v("hello")]):_c('p',[_v("world")])])}`
)
})
it('generate v-else-if directive', () => {
assertCodegen(
'<div><p v-if="show">hello</p><p v-else-if="hide">world</p></div>',
`with(this){return _c('div',[(show)?_c('p',[_v("hello")]):(hide)?_c('p',[_v("world")]):_e()])}`
)
})
it('generate v-else-if with v-else directive', () => {
assertCodegen(
'<div><p v-if="show">hello</p><p v-else-if="hide">world</p><p v-else>bye</p></div>',
`with(this){return _c('div',[(show)?_c('p',[_v("hello")]):(hide)?_c('p',[_v("world")]):_c('p',[_v("bye")])])}`
)
})
it('generate multi v-else-if with v-else directive', () => {
assertCodegen(
'<div><p v-if="show">hello</p><p v-else-if="hide">world</p><p v-else-if="3">elseif</p><p v-else>bye</p></div>',
`with(this){return _c('div',[(show)?_c('p',[_v("hello")]):(hide)?_c('p',[_v("world")]):(3)?_c('p',[_v("elseif")]):_c('p',[_v("bye")])])}`
)
})
it('generate ref', () => {
assertCodegen(
'<p ref="component1"></p>',
`with(this){return _c('p',{ref:"component1"})}`
)
})
it('generate ref on v-for', () => {
assertCodegen(
'<ul><li v-for="item in items" ref="component1"></li></ul>',
`with(this){return _c('ul',_l((items),function(item){return _c('li',{ref:"component1",refInFor:true})}))}`
)
})
it('generate v-bind directive', () => {
assertCodegen(
'<p v-bind="test"></p>',
`with(this){return _c('p',_b({},'p',test))}`
)
})
it('generate template tag', () => {
assertCodegen(
'<div><template><p>{{hello}}</p></template></div>',
`with(this){return _c('div',[[_c('p',[_v(_s(hello))])]],2)}`
)
})
it('generate single slot', () => {
assertCodegen(
'<div><slot></slot></div>',
`with(this){return _c('div',[_t("default")],2)}`
)
})
it('generate named slot', () => {
assertCodegen(
'<div><slot name="one"></slot></div>',
`with(this){return _c('div',[_t("one")],2)}`
)
})
it('generate slot fallback content', () => {
assertCodegen(
'<div><slot><div>hi</div></slot></div>',
`with(this){return _c('div',[_t("default",[_c('div',[_v("hi")])])],2)}`
)
})
it('generate slot target', () => {
assertCodegen(
'<p slot="one">hello world</p>',
`with(this){return _c('p',{slot:"one"},[_v("hello world")])}`
)
})
it('generate class binding', () => {
// static
assertCodegen(
'<p class="class1">hello world</p>',
`with(this){return _c('p',{staticClass:"class1"},[_v("hello world")])}`,
)
// dynamic
assertCodegen(
'<p :class="class1">hello world</p>',
`with(this){return _c('p',{class:class1},[_v("hello world")])}`
)
})
it('generate style binding', () => {
assertCodegen(
'<p :style="error">hello world</p>',
`with(this){return _c('p',{style:(error)},[_v("hello world")])}`
)
})
it('generate v-show directive', () => {
assertCodegen(
'<p v-show="shown">hello world</p>',
`with(this){return _c('p',{directives:[{name:"show",rawName:"v-show",value:(shown),expression:"shown"}]},[_v("hello world")])}`
)
})
it('generate DOM props with v-bind directive', () => {
// input + value
assertCodegen(
'<input :value="msg">',
`with(this){return _c('input',{domProps:{"value":msg}})}`
)
// non input
assertCodegen(
'<p :value="msg"/>',
`with(this){return _c('p',{attrs:{"value":msg}})}`
)
})
it('generate attrs with v-bind directive', () => {
assertCodegen(
'<input :name="field1">',
`with(this){return _c('input',{attrs:{"name":field1}})}`
)
})
it('generate static attrs', () => {
assertCodegen(
'<input name="field1">',
`with(this){return _c('input',{attrs:{"name":"field1"}})}`
)
})
it('generate events with v-on directive', () => {
assertCodegen(
'<input @input="onInput">',
`with(this){return _c('input',{on:{"input":onInput}})}`
)
})
it('generate events with keycode', () => {
assertCodegen(
'<input @input.enter="onInput">',
`with(this){return _c('input',{on:{"input":function($event){if(!('button' in $event)&&_k($event.keyCode,"enter",13))return null;onInput($event)}}})}`
)
// multiple keycodes (delete)
assertCodegen(
'<input @input.delete="onInput">',
`with(this){return _c('input',{on:{"input":function($event){if(!('button' in $event)&&_k($event.keyCode,"delete",[8,46]))return null;onInput($event)}}})}`
)
// multiple keycodes (chained)
assertCodegen(
'<input @keydown.enter.delete="onInput">',
`with(this){return _c('input',{on:{"keydown":function($event){if(!('button' in $event)&&_k($event.keyCode,"enter",13)&&_k($event.keyCode,"delete",[8,46]))return null;onInput($event)}}})}`
)
// number keycode
assertCodegen(
'<input @input.13="onInput">',
`with(this){return _c('input',{on:{"input":function($event){if(!('button' in $event)&&$event.keyCode!==13)return null;onInput($event)}}})}`
)
// custom keycode
assertCodegen(
'<input @input.custom="onInput">',
`with(this){return _c('input',{on:{"input":function($event){if(!('button' in $event)&&_k($event.keyCode,"custom"))return null;onInput($event)}}})}`
)
})
it('generate events with generic modifiers', () => {
assertCodegen(
'<input @input.stop="onInput">',
`with(this){return _c('input',{on:{"input":function($event){$event.stopPropagation();onInput($event)}}})}`
)
assertCodegen(
'<input @input.prevent="onInput">',
`with(this){return _c('input',{on:{"input":function($event){$event.preventDefault();onInput($event)}}})}`
)
assertCodegen(
'<input @input.self="onInput">',
`with(this){return _c('input',{on:{"input":function($event){if($event.target !== $event.currentTarget)return null;onInput($event)}}})}`
)
})
// Github Issues #5146
it('generate events with generic modifiers and keycode correct order', () => {
assertCodegen(
'<input @keydown.enter.prevent="onInput">',
`with(this){return _c('input',{on:{"keydown":function($event){if(!('button' in $event)&&_k($event.keyCode,"enter",13))return null;$event.preventDefault();onInput($event)}}})}`
)
assertCodegen(
'<input @keydown.enter.stop="onInput">',
`with(this){return _c('input',{on:{"keydown":function($event){if(!('button' in $event)&&_k($event.keyCode,"enter",13))return null;$event.stopPropagation();onInput($event)}}})}`
)
})
it('generate events with mouse event modifiers', () => {
assertCodegen(
'<input @click.ctrl="onClick">',
`with(this){return _c('input',{on:{"click":function($event){if(!$event.ctrlKey)return null;onClick($event)}}})}`
)
assertCodegen(
'<input @click.shift="onClick">',
`with(this){return _c('input',{on:{"click":function($event){if(!$event.shiftKey)return null;onClick($event)}}})}`
)
assertCodegen(
'<input @click.alt="onClick">',
`with(this){return _c('input',{on:{"click":function($event){if(!$event.altKey)return null;onClick($event)}}})}`
)
assertCodegen(
'<input @click.meta="onClick">',
`with(this){return _c('input',{on:{"click":function($event){if(!$event.metaKey)return null;onClick($event)}}})}`
)
})
it('generate events with multiple modifiers', () => {
assertCodegen(
'<input @input.stop.prevent.self="onInput">',
`with(this){return _c('input',{on:{"input":function($event){$event.stopPropagation();$event.preventDefault();if($event.target !== $event.currentTarget)return null;onInput($event)}}})}`
)
})
it('generate events with capture modifier', () => {
assertCodegen(
'<input @input.capture="onInput">',
`with(this){return _c('input',{on:{"!input":function($event){onInput($event)}}})}`
)
})
it('generate events with once modifier', () => {
assertCodegen(
'<input @input.once="onInput">',
`with(this){return _c('input',{on:{"~input":function($event){onInput($event)}}})}`
)
})
it('generate events with capture and once modifier', () => {
assertCodegen(
'<input @input.capture.once="onInput">',
`with(this){return _c('input',{on:{"~!input":function($event){onInput($event)}}})}`
)
})
it('generate events with once and capture modifier', () => {
assertCodegen(
'<input @input.once.capture="onInput">',
`with(this){return _c('input',{on:{"~!input":function($event){onInput($event)}}})}`
)
})
it('generate events with inline statement', () => {
assertCodegen(
'<input @input="current++">',
`with(this){return _c('input',{on:{"input":function($event){current++}}})}`
)
})
it('generate events with inline function expression', () => {
// normal function
assertCodegen(
'<input @input="function () { current++ }">',
`with(this){return _c('input',{on:{"input":function () { current++ }}})}`
)
// arrow with no args
assertCodegen(
'<input @input="()=>current++">',
`with(this){return _c('input',{on:{"input":()=>current++}})}`
)
// arrow with parens, single arg
assertCodegen(
'<input @input="(e) => current++">',
`with(this){return _c('input',{on:{"input":(e) => current++}})}`
)
// arrow with parens, multi args
assertCodegen(
'<input @input="(a, b, c) => current++">',
`with(this){return _c('input',{on:{"input":(a, b, c) => current++}})}`
)
// arrow with destructuring
assertCodegen(
'<input @input="({ a, b }) => current++">',
`with(this){return _c('input',{on:{"input":({ a, b }) => current++}})}`
)
// arrow single arg no parens
assertCodegen(
'<input @input="e=>current++">',
`with(this){return _c('input',{on:{"input":e=>current++}})}`
)
// with modifiers
assertCodegen(
`<input @keyup.enter="e=>current++">`,
`with(this){return _c('input',{on:{"keyup":function($event){if(!('button' in $event)&&_k($event.keyCode,"enter",13))return null;(e=>current++)($event)}}})}`
)
})
// #3893
it('should not treat handler with unexpected whitespace as inline statement', () => {
assertCodegen(
'<input @input=" onInput ">',
`with(this){return _c('input',{on:{"input": onInput }})}`
)
})
it('generate unhandled events', () => {
assertCodegen(
'<input @input="current++">',
`with(this){return _c('input',{on:{"input":function(){}}})}`,
ast => {
ast.events.input = undefined
}
)
})
it('generate multiple event handlers', () => {
assertCodegen(
'<input @input="current++" @input.stop="onInput">',
`with(this){return _c('input',{on:{"input":[function($event){current++},function($event){$event.stopPropagation();onInput($event)}]}})}`
)
})
it('generate component', () => {
assertCodegen(
'<my-component name="mycomponent1" :msg="msg" @notify="onNotify"><div>hi</div></my-component>',
`with(this){return _c('my-component',{attrs:{"name":"mycomponent1","msg":msg},on:{"notify":onNotify}},[_c('div',[_v("hi")])])}`
)
})
it('generate svg component with children', () => {
assertCodegen(
'<svg><my-comp><circle :r="10"></circle></my-comp></svg>',
`with(this){return _c('svg',[_c('my-comp',[_c('circle',{attrs:{"r":10}})])],1)}`
)
})
it('generate is attribute', () => {
assertCodegen(
'<div is="component1"></div>',
`with(this){return _c("component1",{tag:"div"})}`
)
assertCodegen(
'<div :is="component1"></div>',
`with(this){return _c(component1,{tag:"div"})}`
)
})
it('generate component with inline-template', () => {
// have "inline-template'"
assertCodegen(
'<my-component inline-template><p><span>hello world</span></p></my-component>',
`with(this){return _c('my-component',{inlineTemplate:{render:function(){with(this){return _m(0)}},staticRenderFns:[function(){with(this){return _c('p',[_c('span',[_v("hello world")])])}}]}})}`
)
// "have inline-template attrs, but not having exactly one child element
assertCodegen(
'<my-component inline-template><hr><hr></my-component>',
`with(this){return _c('my-component',{inlineTemplate:{render:function(){with(this){return _c('hr')}},staticRenderFns:[]}})}`
)
expect('Inline-template components must have exactly one child element.').toHaveBeenWarned()
})
it('generate static trees inside v-for', () => {
assertCodegen(
`<div><div v-for="i in 10"><p><span></span></p></div></div>`,
`with(this){return _c('div',_l((10),function(i){return _c('div',[_m(0,true)])}))}`,
[`with(this){return _c('p',[_c('span')])}`]
)
})
it('generate component with v-for', () => {
// normalize type: 2
assertCodegen(
'<div><child></child><template v-for="item in list">{{ item }}</template></div>',
`with(this){return _c('div',[_c('child'),_l((list),function(item){return [_v(_s(item))]})],2)}`
)
})
it('not specified ast type', () => {
const res = generate(null, baseOptions)
expect(res.render).toBe(`with(this){return _c("div")}`)
expect(res.staticRenderFns).toEqual([])
})
it('not specified directives option', () => {
assertCodegen(
'<p v-if="show">hello world</p>',
`with(this){return (show)?_c('p',[_v("hello world")]):_e()}`,
{ isReservedTag }
)
})
})
/* eslint-enable quotes */
| test/unit/modules/compiler/codegen.spec.js | 1 | https://github.com/vuejs/vue/commit/e7dfcc334d6f6513d2ed1cddfa28a08796e07df7 | [
0.7296591401100159,
0.015711430460214615,
0.00016468734247609973,
0.00017317209858447313,
0.104144386947155
] |
{
"id": 2,
"code_window": [
"describe('codegen', () => {\n",
" it('generate directive', () => {\n",
" assertCodegen(\n",
" '<p v-custom1:arg1.modifier=\"value1\" v-custom2></p>',\n",
" `with(this){return _c('p',{directives:[{name:\"custom1\",rawName:\"v-custom1:arg1.modifier\",value:(value1),expression:\"value1\",arg:\"arg1\",modifiers:{\"modifier\":true}},{name:\"custom2\",rawName:\"v-custom2\",arg:\"arg1\"}]})}`\n",
" )\n",
" })\n",
"\n",
" it('generate filters', () => {\n",
" assertCodegen(\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" `with(this){return _c('p',{directives:[{name:\"custom1\",rawName:\"v-custom1:arg1.modifier\",value:(value1),expression:\"value1\",arg:\"arg1\",modifiers:{\"modifier\":true}},{name:\"custom2\",rawName:\"v-custom2\"}]})}`\n"
],
"file_path": "test/unit/modules/compiler/codegen.spec.js",
"type": "replace",
"edit_start_line_idx": 35
} | /* @flow */
const MAX_STACK_DEPTH = 1000
export function createWriteFunction (
write: (text: string, next: Function) => ?boolean,
onError: Function
): Function {
let stackDepth = 0
const cachedWrite = (text, next) => {
if (text && cachedWrite.caching) {
cachedWrite.cacheBuffer[cachedWrite.cacheBuffer.length - 1] += text
}
const waitForNext = write(text, next)
if (!waitForNext) {
if (stackDepth >= MAX_STACK_DEPTH) {
process.nextTick(() => {
try { next() } catch (e) {
onError(e)
}
})
} else {
stackDepth++
next()
stackDepth--
}
}
}
cachedWrite.caching = false
cachedWrite.cacheBuffer = []
return cachedWrite
}
| src/server/write.js | 0 | https://github.com/vuejs/vue/commit/e7dfcc334d6f6513d2ed1cddfa28a08796e07df7 | [
0.00017438962822780013,
0.00017054502677638084,
0.00016772677190601826,
0.00017003185348585248,
0.000002530788151489105
] |
{
"id": 2,
"code_window": [
"describe('codegen', () => {\n",
" it('generate directive', () => {\n",
" assertCodegen(\n",
" '<p v-custom1:arg1.modifier=\"value1\" v-custom2></p>',\n",
" `with(this){return _c('p',{directives:[{name:\"custom1\",rawName:\"v-custom1:arg1.modifier\",value:(value1),expression:\"value1\",arg:\"arg1\",modifiers:{\"modifier\":true}},{name:\"custom2\",rawName:\"v-custom2\",arg:\"arg1\"}]})}`\n",
" )\n",
" })\n",
"\n",
" it('generate filters', () => {\n",
" assertCodegen(\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" `with(this){return _c('p',{directives:[{name:\"custom1\",rawName:\"v-custom1:arg1.modifier\",value:(value1),expression:\"value1\",arg:\"arg1\",modifiers:{\"modifier\":true}},{name:\"custom2\",rawName:\"v-custom2\"}]})}`\n"
],
"file_path": "test/unit/modules/compiler/codegen.spec.js",
"type": "replace",
"edit_start_line_idx": 35
} | import Vue from 'vue'
import { isIE9, isAndroid } from 'core/util/env'
describe('Directive v-model text', () => {
it('should update value both ways', done => {
const vm = new Vue({
data: {
test: 'b'
},
template: '<input v-model="test">'
}).$mount()
expect(vm.$el.value).toBe('b')
vm.test = 'a'
waitForUpdate(() => {
expect(vm.$el.value).toBe('a')
vm.$el.value = 'c'
triggerEvent(vm.$el, 'input')
expect(vm.test).toBe('c')
}).then(done)
})
it('.lazy modifier', () => {
const vm = new Vue({
data: {
test: 'b'
},
template: '<input v-model.lazy="test">'
}).$mount()
expect(vm.$el.value).toBe('b')
expect(vm.test).toBe('b')
vm.$el.value = 'c'
triggerEvent(vm.$el, 'input')
expect(vm.test).toBe('b')
triggerEvent(vm.$el, 'change')
expect(vm.test).toBe('c')
})
it('.number modifier', () => {
const vm = new Vue({
data: {
test: 1
},
template: '<input v-model.number="test">'
}).$mount()
expect(vm.test).toBe(1)
vm.$el.value = '2'
triggerEvent(vm.$el, 'input')
expect(vm.test).toBe(2)
// should let strings pass through
vm.$el.value = 'f'
triggerEvent(vm.$el, 'input')
expect(vm.test).toBe('f')
})
it('.trim modifier', () => {
const vm = new Vue({
data: {
test: 'hi'
},
template: '<input v-model.trim="test">'
}).$mount()
expect(vm.test).toBe('hi')
vm.$el.value = ' what '
triggerEvent(vm.$el, 'input')
expect(vm.test).toBe('what')
})
it('.number focus and typing', (done) => {
const vm = new Vue({
data: {
test: 0,
update: 0
},
template:
'<div>' +
'<input ref="input" v-model.number="test">{{ update }}' +
'<input ref="blur">' +
'</div>'
}).$mount()
document.body.appendChild(vm.$el)
vm.$refs.input.focus()
expect(vm.test).toBe(0)
vm.$refs.input.value = '1.0'
triggerEvent(vm.$refs.input, 'input')
expect(vm.test).toBe(1)
vm.update++
waitForUpdate(() => {
expect(vm.$refs.input.value).toBe('1.0')
vm.$refs.blur.focus()
vm.update++
}).then(() => {
expect(vm.$refs.input.value).toBe('1')
}).then(done)
})
it('.trim focus and typing', (done) => {
const vm = new Vue({
data: {
test: 'abc',
update: 0
},
template:
'<div>' +
'<input ref="input" v-model.trim="test" type="text">{{ update }}' +
'<input ref="blur"/>' +
'</div>'
}).$mount()
document.body.appendChild(vm.$el)
vm.$refs.input.focus()
vm.$refs.input.value = ' abc '
triggerEvent(vm.$refs.input, 'input')
expect(vm.test).toBe('abc')
vm.update++
waitForUpdate(() => {
expect(vm.$refs.input.value).toBe(' abc ')
vm.$refs.blur.focus()
vm.update++
}).then(() => {
expect(vm.$refs.input.value).toBe('abc')
}).then(done)
})
it('multiple inputs', (done) => {
const spy = jasmine.createSpy()
const vm = new Vue({
data: {
selections: [[1, 2, 3], [4, 5]],
inputList: [
{
name: 'questionA',
data: ['a', 'b', 'c']
},
{
name: 'questionB',
data: ['1', '2']
}
]
},
watch: {
selections: spy
},
template:
'<div>' +
'<div v-for="(inputGroup, idx) in inputList">' +
'<div>' +
'<span v-for="(item, index) in inputGroup.data">' +
'<input v-bind:name="item" type="text" v-model.number="selections[idx][index]" v-bind:id="idx+\'-\'+index"/>' +
'<label>{{item}}</label>' +
'</span>' +
'</div>' +
'</div>' +
'<span ref="rs">{{selections}}</span>' +
'</div>'
}).$mount()
var inputs = vm.$el.getElementsByTagName('input')
inputs[1].value = 'test'
triggerEvent(inputs[1], 'input')
waitForUpdate(() => {
expect(spy).toHaveBeenCalled()
expect(vm.selections).toEqual([[1, 'test', 3], [4, 5]])
}).then(done)
})
if (isIE9) {
it('IE9 selectionchange', done => {
const vm = new Vue({
data: {
test: 'foo'
},
template: '<input v-model="test">'
}).$mount()
const input = vm.$el
input.value = 'bar'
document.body.appendChild(input)
input.focus()
triggerEvent(input, 'selectionchange')
waitForUpdate(() => {
expect(vm.test).toBe('bar')
input.value = 'a'
triggerEvent(input, 'selectionchange')
expect(vm.test).toBe('a')
}).then(done)
})
}
if (!isAndroid) {
it('compositionevents', function (done) {
const vm = new Vue({
data: {
test: 'foo'
},
template: '<input v-model="test">'
}).$mount()
const input = vm.$el
triggerEvent(input, 'compositionstart')
input.value = 'baz'
// input before composition unlock should not call set
triggerEvent(input, 'input')
expect(vm.test).toBe('foo')
// after composition unlock it should work
triggerEvent(input, 'compositionend')
triggerEvent(input, 'input')
expect(vm.test).toBe('baz')
done()
})
}
it('warn invalid tag', () => {
new Vue({
data: {
test: 'foo'
},
template: '<div v-model="test"></div>'
}).$mount()
expect('<div v-model="test">: v-model is not supported on this element type').toHaveBeenWarned()
})
// #3468
it('should have higher priority than user v-on events', () => {
const spy = jasmine.createSpy()
const vm = new Vue({
data: {
a: 'a'
},
template: '<input v-model="a" @input="onInput">',
methods: {
onInput (e) {
spy(e.target.value)
}
}
}).$mount()
vm.$el.value = 'b'
triggerEvent(vm.$el, 'input')
expect(spy).toHaveBeenCalledWith('b')
})
it('warn binding to v-for alias', () => {
new Vue({
data: {
strings: ['hi']
},
template: `
<div>
<div v-for="str in strings">
<input v-model="str">
</div>
</div>
`
}).$mount()
expect('You are binding v-model directly to a v-for iteration alias').toHaveBeenWarned()
})
})
| test/unit/features/directives/model-text.spec.js | 0 | https://github.com/vuejs/vue/commit/e7dfcc334d6f6513d2ed1cddfa28a08796e07df7 | [
0.00023835960018914193,
0.00017490390746388584,
0.00016713097284082323,
0.0001727066410239786,
0.000012839371265727095
] |
{
"id": 2,
"code_window": [
"describe('codegen', () => {\n",
" it('generate directive', () => {\n",
" assertCodegen(\n",
" '<p v-custom1:arg1.modifier=\"value1\" v-custom2></p>',\n",
" `with(this){return _c('p',{directives:[{name:\"custom1\",rawName:\"v-custom1:arg1.modifier\",value:(value1),expression:\"value1\",arg:\"arg1\",modifiers:{\"modifier\":true}},{name:\"custom2\",rawName:\"v-custom2\",arg:\"arg1\"}]})}`\n",
" )\n",
" })\n",
"\n",
" it('generate filters', () => {\n",
" assertCodegen(\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" `with(this){return _c('p',{directives:[{name:\"custom1\",rawName:\"v-custom1:arg1.modifier\",value:(value1),expression:\"value1\",arg:\"arg1\",modifiers:{\"modifier\":true}},{name:\"custom2\",rawName:\"v-custom2\"}]})}`\n"
],
"file_path": "test/unit/modules/compiler/codegen.spec.js",
"type": "replace",
"edit_start_line_idx": 35
} | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Move Animations</title>
<style>
.container {
position: relative;
padding: 0;
}
.item {
width: 100%;
height: 30px;
background-color: #f3f3f3;
border: 1px solid #666;
box-sizing: border-box;
}
/* 1. declare transition */
.fade-move, .fade-enter-active, .fade-leave-active {
transition: all .5s cubic-bezier(.55,0,.1,1);
}
/* 2. declare enter from and leave to state */
.fade-enter, .fade-leave-to {
opacity: 0;
transform: scaleY(0.01) translate(30px, 0);
}
/* 3. ensure leaving items are taken out of layout flow so that moving
animations can be calculated correctly. */
.fade-leave-active {
position: absolute;
}
</style>
<script src="https://cdn.jsdelivr.net/lodash/4.3.0/lodash.min.js"></script>
<!-- Delete ".min" for console warnings in development -->
<script src="../../dist/vue.min.js"></script>
</head>
<body>
<div id="el">
<button @click="insert">insert at random index</button>
<button @click="reset">reset</button>
<button @click="shuffle">shuffle</button>
<transition-group tag="ul" name="fade" class="container">
<item v-for="item in items"
class="item"
:msg="item"
:key="item"
@rm="remove(item)">
</item>
</transition-group>
</div>
<script>
var items = [1, 2, 3, 4, 5]
var id = items.length + 1
var vm = new Vue({
el: '#el',
data: {
items: items
},
components: {
item: {
props: ['msg'],
template: `<div>{{ msg }} <button @click="$emit('rm')">x</button></div>`
}
},
methods: {
insert () {
var i = Math.round(Math.random() * this.items.length)
this.items.splice(i, 0, id++)
},
reset () {
this.items = [1, 2, 3, 4, 5]
},
shuffle () {
this.items = _.shuffle(this.items)
},
remove (item) {
var i = this.items.indexOf(item)
if (i > -1) {
this.items.splice(i, 1)
}
}
}
})
</script>
</body>
</html>
| examples/move-animations/index.html | 0 | https://github.com/vuejs/vue/commit/e7dfcc334d6f6513d2ed1cddfa28a08796e07df7 | [
0.00017537294479552656,
0.00017172441584989429,
0.00016798653814475983,
0.00017203022434841841,
0.00000216313833334425
] |
{
"id": 0,
"code_window": [
"import * as blocked from 'blocked';\n",
"\n",
"blocked((ms: number) => {\n",
" // todo: show warning\n",
"}, {\n",
" threshold: 10\n",
"});"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" threshold: 10,\n",
" interval: 10,\n"
],
"file_path": "types/blocked/blocked-tests.ts",
"type": "replace",
"edit_start_line_idx": 5
} | // Type definitions for blocked 1.2
// Project: https://github.com/visionmedia/node-blocked#readme
// Definitions by: Jonas Lochmann <https://github.com/l-jonas>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="node" />
/*~ Note that ES6 modules cannot directly export callable functions.
*~ This file should be imported using the CommonJS-style:
*~ import x = require('someLibrary');
*~
*~ Refer to the documentation to understand common
*~ workarounds for this limitation of ES6 modules.
*/
export = Blocked;
declare function Blocked(callback: (ms: number) => void, options?: Blocked.Options): NodeJS.Timer;
declare namespace Blocked {
interface Options {
threshold: number; // in milliseconds
}
}
| types/blocked/index.d.ts | 1 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/f1cf1c35fcc34501098164d5c76e0ccf41efeee9 | [
0.13147743046283722,
0.05009056627750397,
0.0020035612396895885,
0.016790708526968956,
0.0578649640083313
] |
{
"id": 0,
"code_window": [
"import * as blocked from 'blocked';\n",
"\n",
"blocked((ms: number) => {\n",
" // todo: show warning\n",
"}, {\n",
" threshold: 10\n",
"});"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" threshold: 10,\n",
" interval: 10,\n"
],
"file_path": "types/blocked/blocked-tests.ts",
"type": "replace",
"edit_start_line_idx": 5
} | // Type definitions for Marionette 3.3
// Project: https://github.com/marionettejs/, https://marionettejs.com
// Definitions by: Zeeshan Hamid <https://github.com/zhamid>,
// Natan Vivo <https://github.com/nvivo>,
// Sven Tschui <https://github.com/sventschui>,
// Volker Nauruhn <https://github.com/razorness>,
// Ard Timmerman <https://github.com/confususs>,
// J. Joe Koullas <https://github.com/jjoekoullas>
// Julian Gonggrijp <https://github.com/jgonggrijp>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.8
import * as Backbone from 'backbone';
import * as JQuery from 'jquery';
import * as Radio from 'backbone.radio';
import * as _ from 'underscore';
export as namespace Marionette;
// These mixins mirror Marionette source and ensure that Marionette classes that
// extend these mixins have the correct methods attached.
export interface CommonMixin {
normalizeMethods: any;
mergeOptions: any;
getOption: any;
bindEvents: any;
unbindEvents: any;
}
export interface RadioMixinOptions {
/**
* Defines the Radio channel that will be used for the requests and/or
* events.
*/
channelName?: string;
/**
* Defines an events hash with the events to be listened and its respective
* handlers.
*/
radioEvents?: any;
/**
* Defines an events hash with the requests to be replied and its respective
* handlers
*/
radioRequests?: any;
}
export interface RadioMixin {
getChannel: any;
bindEvents: any;
unbindEvents: any;
bindRequests: any;
unbindRequests: any;
}
export interface DomMixin {
createBuffer: any;
appendChildren: any;
beforeEl: any;
replaceEl: any;
detachContents: any;
setInnerContent: any;
detachEl: any;
removeEl: any;
findEls: any;
}
export interface ViewMixinOptions {
/**
* Behavior objects to assign to this View.
*/
behaviors?: Marionette.Behavior[];
/**
* Customize the event prefix for events that are forwarded through the
* collection view.
*/
childViewEventPrefix?: string | false;
/**
* Use the childViewEvents attribute to map child events to methods on the
* parent view.
*/
childViewEvents?: Marionette.EventsHash;
/**
* A childViewTriggers hash or method permits proxying of child view events
* without manually setting bindings. The values of the hash should be a
* string of the event to trigger on the parent.
*/
childViewTriggers?: Marionette.EventsHash;
/**
* Bind to events that occur on attached collections.
*/
collectionEvents?: Marionette.EventsHash;
/**
* Bind to events that occur on attached models.
*/
modelEvents?: Marionette.EventsHash;
/**
* The view triggers attribute binds DOM events to Marionette View events
* that can be responded to at the view or parent level.
*/
triggers?: Marionette.EventsHash;
/**
* Name parts of your template to be used
* throughout the view with the ui attribute.
*/
ui?: any;
}
export interface ViewMixin extends DomMixin, CommonMixin {
supportsRenderLifecycle: any;
supportsDestroyLifecycle: any;
isDestroyed: any;
isRendered: any;
isAttached: any;
delegateEvents: any;
getTriggers: any;
delegateEntityEvents: any;
undelegateEntityEvents: any;
destroy: any;
bindUIElements: any;
unbindUIElements: any;
childViewEventPrefix: any;
triggerMethod: any;
}
export interface RegionsMixin {
regionClass: any;
addRegion: any;
addRegions: any;
removeRegion: any;
removeRegions: any;
emptyRegions: any;
hasRegion: any;
getRegion: any;
getRegions: any;
showChildView: any;
detachChildView: any;
getChildView: any;
}
export class Container<TView> {
/**
* Find a view by it's cid.
*/
findByCid(cid: string): TView;
/**
* Find a view by model.
*/
findByModel(model: Backbone.Model): TView;
/**
* Find a view by model cid.
*/
findByModelCid(modelCid: string): TView;
/**
* Find by custom key.
*/
findByCustom(key: string): TView;
/**
* Find by numeric index (unstable).
*/
findByIndex(index: number): TView;
/**
* Find a view by it's cid.
*/
add(view: TView, customIndex?: number): void;
/**
* Find a view by it's cid.
*/
remove(view: TView): void;
/**
* @see _.forEach
*/
forEach(iterator: _.ListIterator<TView, void>, context?: any): Container<TView>;
/**
* @see _.each
*/
each(iterator: _.ListIterator<TView, void>, context?: any): Container<TView>;
/**
* @see _.map
*/
map<TResult>(iterator: _.ListIterator<TView, TResult>, context?: any): TResult[];
/**
* @see _.find
*/
find(iterator: _.ListIterator<TView, boolean>, context?: any): Container<TView> | undefined;
/**
* @see _.detect
*/
detect(iterator: _.ListIterator<TView, boolean>, context?: any): Container<TView> | undefined;
/**
* @see _.filter
*/
filter(iterator: _.ListIterator<TView, boolean>, context?: any): TView[];
/**
* @see _.select
*/
select(iterator: _.ListIterator<TView, boolean>, context?: any): TView[];
/**
* @see _.reject
*/
reject(iterator: _.ListIterator<TView, boolean>, context?: any): TView[];
/**
* @see _.every
*/
every(iterator: _.ListIterator<TView, boolean>, context?: any): boolean;
/**
* @see _.all
*/
all(iterator: _.ListIterator<TView, boolean>, context?: any): boolean;
/**
* @see _.some
*/
some(iterator: _.ListIterator<TView, boolean>, context?: any): boolean;
/**
* @see _.any
*/
any(iterator: _.ListIterator<TView, boolean>, context?: any): boolean;
/**
* @see _.include
*/
include(value: TView, fromIndex?: number): boolean;
/**
* @see _.contains
*/
contains(value: TView, fromIndex?: number): boolean;
/**
* @see _.invoke
*/
invoke(methodName: string, ...args: any[]): any;
/**
* @see _.toArray
*/
toArray(): TView[];
/**
* @see _.first
*/
first(): TView | undefined;
/**
* @see _.initial
*/
initial(n?: number): TView[];
/**
* @see _.rest
*/
rest(n?: number): TView[];
/**
* @see _.last
*/
last(n: number): TView[];
/**
* @see _.without
*/
without(...values: TView[]): TView[];
/**
* @see _.isEmpty
*/
isEmpty(): boolean;
/**
* @see _.pluck
*/
pluck(propertyName: string): any[];
/**
* @see _.reduce
*/
reduce<TResult>(iterator: _.MemoIterator<TView, TResult>, memo?: TResult, context?: any): TResult;
/**
* @see _.partition
*/
partition(iterator: _.ListIterator<TView, boolean>, context?: any): TView[][];
}
/**
* Alias of Backbones extend function.
*/
export function extend(properties: any, classProperties?: any): any;
/**
* Determines whether the passed-in node is a child of the document or not.
*/
export function isNodeAttached(el: HTMLElement): boolean;
/**
* A handy function to pluck certain options and attach them directly to an
* instance.
*/
export function mergeOptions(target: any, options: any, keys: any): void;
/**
* Retrieve an object's attribute either directly from the object, or
* from the object's this.options, with this.options taking precedence.
*/
export function getOption(target: any, optionName: string): any;
/**
* Trigger an event and a corresponding method on the target object.
* All arguments that are passed to the triggerMethod call are passed along
* to both the event and the method, with the exception of the event name not
* being passed to the corresponding method.
*/
export function triggerMethod(target: any, name: string, ...args: any[]): any;
/**
* Invoke triggerMethod on a specific context.
* This is useful when it's not clear that the object has triggerMethod defined.
*/
export function triggerMethodOn(ctx: any, name: string, ...args: any[]): any;
/**
* This method is used to bind a backbone "entity" (collection/model) to methods on a target object.
* @param target An object that must have a listenTo method from the EventBinder object.
* @param entity The entity (Backbone.Model or Backbone.Collection) to bind the events from.
* @param bindings a hash of { "event:name": "eventHandler" } configuration. Multiple handlers can be separated by a space. A function can be supplied instead of a string handler name.
*/
export function bindEvents(target: any, entity: any, bindings: any): void;
/**
* This method can be used to unbind callbacks from entities' (collection/model) events. It's the opposite of bindEvents
* @param target An object that must have a listenTo method from the EventBinder object.
* @param entity The entity (Backbone.Model or Backbone.Collection) to bind the events from.
* @param bindings a hash of { "event:name": "eventHandler" } configuration. Multiple handlers can be separated by a space. A function can be supplied instead of a string handler name.
*/
export function unbindEvents(target: any, entity: any, bindings: any): void;
/**
* This method is used to bind a radio requests to methods on a target
* object.
*/
export function bindRequests(target: any, channel: Radio.Channel, bindings: any): void;
/**
* This method is used to unbind a radio requests to methods on a target
* object.
*/
export function unbindRequests(target: any, channel: Radio.Channel, bindings: any): void;
/**
* Receives a hash of event names and functions and/or function names, and
* returns the same hash with the function names replaced with the function
* references themselves.
*/
export function normalizeMethods<T>(target: any, hash: any): T;
/**
* Allows you to run multiple instances of Marionette in the same
* application.
*/
export function noConflict(): void;
/**
* Overrides Backbone.EventsHash as JQueryEventObject is deprecated and
* doesn't allow you to set the event target
*/
export interface EventsHash extends Backbone.EventsHash {
[selector: string]: string | ((eventObject: JQuery.Event) => void);
}
export interface ObjectOptions extends RadioMixinOptions {
/**
* Initialize is called immediately after the Object has been instantiated,
* and is invoked with the same arguments that the constructor received.
*/
initialize?(options?: ObjectOptions): void;
[index: string]: any;
}
/**
* A base class which other classes can extend from. Object incorporates many
* backbone conventions and utilities like initialize and Backbone.Events.
*/
export class Object extends Backbone.EventsMixin implements CommonMixin, RadioMixin, Backbone.Events {
constructor(options?: ObjectOptions);
/**
* Faulty overgeneralization of Backbone.Events.on, for historical
* reasons.
*/
on(eventName: any, callback?: any, context?: any): any;
/**
* Receives a hash of event names and functions and/or function names,
* and returns the same hash with the function names replaced with the
* function references themselves.
*/
normalizeMethods<T>(hash: any): T;
/**
* A handy function to pluck certain options and attach them directly
* to an instance.
*/
mergeOptions(options: any, keys: any): void;
/**
* Retrieve an object's attribute either directly from the object, or from
* the object's this.options, with this.options taking precedence.
* @param optionName the name of the option to retrieve.
*/
getOption(optionName: string): any;
/**
* This method is used to bind a backbone "entity" (collection/model) to
* methods on a target object.
*/
bindEvents(entity: any, bindings: any): void;
/**
* This method can be used to unbind callbacks from entities'
* (collection/model) events.
*/
unbindEvents(entity: any, bindings: any): void;
/**
* Returns a Radio.Channel instance using 'channelName'
*/
getChannel(): Backbone.Radio.Channel;
/**
* This method is used to bind a radio requests to methods on a target
* object.
*/
bindRequests(channel: Radio.Channel, bindings: any): void;
/**
* This method is used to unbind a radio requests to methods on a target
* object.
*/
unbindRequests(channel: Radio.Channel, bindings: any): void;
/**
* Defines the Radio channel that will be used for the requests and/or events
*/
channelName: string;
/**
* Defines an events hash with the events to be listened and its respective handlers
*/
radioEvents: any;
/**
* Defines an events hash with the requests to be replied and its respective handlers
*/
radioRequests: any;
/**
* Check if this Oject has been destroyed.
*/
isDestroyed(): boolean;
/**
* Initialize is called immediately after the Object has been instantiated,
* and is invoked with the same arguments that the constructor received.
*/
initialize(options?: ObjectOptions): void;
/**
* Objects have a destroy method that unbind the events that are directly
* attached to the instance. Invoking the destroy method will trigger a
* "before:destroy" event and corresponding onBeforeDestroy method call.
* These calls will be passed any arguments destroy was invoked with.
* @param args any arguments to pass to the "before:destory" event and call to
* onBeforeDestroy.
*/
destroy(...args: any[]): void;
/**
* Trigger an event and a corresponding method on the target object.
* All arguments that are passed to the triggerMethod call are passed
* along to both the event and the method, with the exception of the
* event name not being passed to the corresponding method.
*/
triggerMethod(name: string, ...args: any[]): any;
}
/**
* The TemplateCache provides a cache for retrieving templates from script blocks
* in your HTML. This will improve the speed of subsequent calls to get a template.
*/
export class TemplateCache implements DomMixin {
/**
* Returns a new HTML DOM node instance. The resulting node can be
* passed into the other DOM functions.
*/
createBuffer(): DocumentFragment;
/**
* Takes the DOM node el and appends the rendered children to the end of
* the element's contents.
* @param el is a jQuery argument: https://api.jquery.com/jQuery/
* @param children is jQuery.append argument: http://api.jquery.com/append/
*/
appendChildren(el: any, children: any): void;
/**
* Add sibling to the DOM immediately before the DOM node el. The
* sibling will be at the same level as el.
* @param el is a jQuery argument: https://api.jquery.com/jQuery/
* @param sibling is jQuery.before argument: http://api.jquery.com/before/
*/
beforeEl(el: any, sibling: any): void;
/**
* Remove oldEl from the DOM and put newEl in its place.
*/
replaceEl(newEl: HTMLElement, oldEL: HTMLElement): void;
/**
* Remove the inner contents of el from the DOM while leaving el itself
* in the DOM.
* @param el is a jQuery argument: https://api.jquery.com/jQuery/
*/
detachContents(el: any): void;
/**
* Replace the contents of el with the HTML string of html. Unlike other
* DOM functions, this takes a literal string for its second argument.
* @param el is a jQuery argument: https://api.jquery.com/jQuery/
* @param html is a jQuery.html argument: https://api.jquery.com/html/
*/
setInnerContent(el: any, html: string): void;
/**
* Detach el from the DOM.
* @param el is a jQuery argument: https://api.jquery.com/jQuery/
*/
detachEl(el: any): void;
/**
* Remove el from the DOM.
* @param el is a jQuery argument: https://api.jquery.com/jQuery/
*/
removeEl(el: any): void;
/**
* Lookup the selector string within the DOM node for context. The
* optional context argument will come in as a DOM Node reference to run
* the selector search. If context hasn't been set, then findEls should
* search the entire document for the selector.
* @param selector is a jQuery argument: https://api.jquery.com/jQuery/
* @param context is a jQuery argument: https://api.jquery.com/jQuery/
*/
findEls(selector: any, context: any): void;
/**
* To use the TemplateCache, call the get method on TemplateCache
* directly. Internally, instances of the TemplateCache class will be
* created and stored but you do not have to manually create these
* instances yourself. get will return a compiled template function.
*/
static get(templateId: string, options?: any): any;
/**
* You can clear one or more, or all items from the cache using the clear
* method. Clearing a template from the cache will force it to re-load
* from the DOM the next time it is retrieved.
* @param the templateId used for loading / caching of the templates to clear. If none specified, all templates will be cleared from the cache.
*/
static clear(...templateId: string[]): void;
/**
* Initial method to load the template. (undocumented)
*/
load(options?: any): any;
/**
* The default template retrieval is to select the template contents from the
* DOM using jQuery. If you wish to change the way this works, you can
* override this method on the TemplateCache object.
* Note that the options argument seems to be unused in the source.
*/
loadTemplate(templateId: string, options?: any): any;
/**
* The default template compilation passes the results from loadTemplate to
* the compileTemplate function, which returns an underscore.js compiled
* template function. When overriding compileTemplate remember that it
* must return a function which takes an object of parameters and values
* and returns a formatted HTML string.
*/
compileTemplate(rawTemplate: any, options?: any): any;
}
export interface RegionConstructionOptions {
/**
* Specifies the element for the region to manage. This may be
* a selector string, a raw DOM node reference or a jQuery wrapped
* DOM node.
*/
el?: any;
/**
* Prevents error on missing element. (undocumented)
*/
allowMissingEl?: boolean;
/**
* Element to use as context when finding el via jQuery. Defaults to the
* the document. (undocumented)
*/
parentEl?: string;
/**
* Overwrite the parent el of the region with the rendered contents of
* the inner View.
*/
replaceElement?: string;
}
export interface RegionViewOptions {
/**
* DEPRECATED: If you replace the current view with a new view by calling show, by
* default it will automatically destroy the previous view. You can
* prevent this behavior by setting this option to true.
*/
preventDestroy?: boolean;
}
/**
* Regions provide consistent methods to manage, show and destroy views in
* your applications and layouts. They use a jQuery selector to show your
* views in the correct place.
*/
export class Region extends Object implements DomMixin {
/**
* Returns a new HTML DOM node instance. The resulting node can be
* passed into the other DOM functions.
*/
createBuffer(): DocumentFragment;
/**
* Takes the DOM node el and appends the rendered children to the end of
* the element's contents.
* @param el is a jQuery argument: https://api.jquery.com/jQuery/
* @param children is jQuery.append argument: http://api.jquery.com/append/
*/
appendChildren(el: any, children: any): void;
/**
* Add sibling to the DOM immediately before the DOM node el. The
* sibling will be at the same level as el.
* @param el is a jQuery argument: https://api.jquery.com/jQuery/
* @param sibling is jQuery.before argument: http://api.jquery.com/before/
*/
beforeEl(el: any, sibling: any): void;
/**
* Remove oldEl from the DOM and put newEl in its place.
*/
replaceEl(newEl: HTMLElement, oldEL: HTMLElement): void;
/**
* Remove the inner contents of el from the DOM while leaving el itself
* in the DOM.
* @param el is a jQuery argument: https://api.jquery.com/jQuery/
*/
detachContents(el: any): void;
/**
* Replace the contents of el with the HTML string of html. Unlike other
* DOM functions, this takes a literal string for its second argument.
* @param el is a jQuery argument: https://api.jquery.com/jQuery/
* @param html is a jQuery.html argument: https://api.jquery.com/html/
*/
setInnerContent(el: any, html: string): void;
/**
* Detach el from the DOM.
* @param el is a jQuery argument: https://api.jquery.com/jQuery/
*/
detachEl(el: any): void;
/**
* Remove el from the DOM.
* @param el is a jQuery argument: https://api.jquery.com/jQuery/
*/
removeEl(el: any): void;
/**
* Lookup the selector string within the DOM node for context. The
* optional context argument will come in as a DOM Node reference to run
* the selector search. If context hasn't been set, then findEls should
* search the entire document for the selector.
* @param selector is a jQuery argument: https://api.jquery.com/jQuery/
* @param context is a jQuery argument: https://api.jquery.com/jQuery/
*/
findEls(selector: any, context: any): void;
/**
* You can specify an el for the region to manage at the time the region
* is instantiated.
*/
constructor(options?: RegionConstructionOptions);
/**
* Defaults to 'mnr' (undocumented)
*/
cidPrefix: string;
/**
* Overwrite the parent el of the region with the rendered contents of
* the inner View.
*/
replaceElement: boolean;
/**
* Contains the element that this region should manage.
*/
el: any;
/**
* Renders and displays the specified view in this region.
* @param view the view to display.
*/
show(view: Backbone.View<Backbone.Model>, options?: RegionViewOptions): void;
/**
* Override this method to change how the region finds the DOM element
* that it manages. Return a jQuery selector object scoped to a provided
* parent el or the document if none exists. (undocumented)
*/
getEl(): any;
/**
* Check to see if the region’s el was replaced. (undocumented)
*/
isReplaced(): boolean;
/**
* Check to see if a view is being swapped by another.
*/
isSwappingView(): boolean;
/**
* Override this method to change how the new view is appended to the
* `$el` that the region is managing
*/
attachHtml(view: Backbone.View<Backbone.Model>): void;
/**
* Destroy the current view, clean up any event handlers and remove it
* from the DOM. When a region is emptied empty events are triggered.
*/
empty(options?: RegionViewOptions): any;
/**
* Destroys the view taking into consideration if is a View descendant
* or vanilla Backbone view.
*/
destroyView<TModel extends Backbone.Model>(view: Backbone.View<TModel>): Backbone.View<TModel>;
/**
* Override the region's removeView method to change how and when the
* view is destroyed / removed from the DOM.
*/
removeView(view: Backbone.View<Backbone.Model>): void;
/**
* Empties the Region without destroying the view, returns the detached
* view.
*/
detachView(): Backbone.View<Backbone.Model>;
/**
* Override this method to change how the region detaches current
* content.
*/
detachHtml(): void;
/**
* If you wish to check whether a region has a view, you can use the
* hasView function. This will return a boolean value depending whether
* or not the region is showing a view.
*/
hasView(): boolean;
/**
* A region can be reset at any time. This destroys any existing view
* being displayed, and deletes the cached el. The next time the region
* shows a view, the region's el is queried from the DOM.
*/
reset(): any;
/**
* @returns view that this region has.
*/
currentView: Backbone.View<Backbone.Model>;
}
/**
* Render a template with data by passing in the template selector and the
* data to render. This is the default renderer that is used by Marionette.
*/
export namespace Renderer {
/**
* This method returns a string containing the result of applying the
* template using the data object as the context.
* @param template The template to render. If this is a function this is
* treated as a pre-compiled template and does not try to compile it again. This
* allows any view that supports a template parameter to specify a pre-compiled
* template function as the template setting. The template function does not
* have to be any specific template engine. It only needs to be a function
* that returns valid HTML as a string from the data parameter passed to
* the function.
*/
function render(template: any, data: any): string;
}
export interface ViewOptions<TModel extends Backbone.Model> extends Backbone.ViewOptions<TModel>, ViewMixinOptions {
/**
* The events attribute binds DOM events to actions to perform on the
* view. It takes DOM event key and a mapping to the handler.
*/
events?: EventsHash;
/**
* If you've created a custom region class, you can use it to define
* your region.
*/
regionClass?: any;
/**
* Add regions to this View.
*/
regions?: any;
/**
* Set the template of this View.
*/
template?: any;
/**
* The templateContext attribute can be used to add extra information to
* your templates
*/
templateContext?: any;
}
/**
* A View is a view that represents an item to be displayed with a template.
* This is typically a Backbone.Model, Backbone.Collection, or nothing at
* all. Views are also used to build up your application hierarchy - you can
* easily nest multiple views through the regions attribute.
*/
export class View<TModel extends Backbone.Model> extends Backbone.View<TModel> implements ViewMixin, RegionsMixin {
constructor(options?: ViewOptions<TModel>);
events(): EventsHash;
/**
* Returns a new HTML DOM node instance. The resulting node can be
* passed into the other DOM functions.
*/
createBuffer(): DocumentFragment;
/**
* Takes the DOM node el and appends the rendered children to the end of
* the element's contents.
* @param el is a jQuery argument: https://api.jquery.com/jQuery/
* @param children is jQuery.append argument: http://api.jquery.com/append/
*/
appendChildren(el: any, children: any): void;
/**
* Add sibling to the DOM immediately before the DOM node el. The
* sibling will be at the same level as el.
* @param el is a jQuery argument: https://api.jquery.com/jQuery/
* @param sibling is jQuery.before argument: http://api.jquery.com/before/
*/
beforeEl(el: any, sibling: any): void;
/**
* Remove oldEl from the DOM and put newEl in its place.
*/
replaceEl(newEl: HTMLElement, oldEL: HTMLElement): void;
/**
* Remove the inner contents of el from the DOM while leaving el itself
* in the DOM.
* @param el is a jQuery argument: https://api.jquery.com/jQuery/
*/
detachContents(el: any): void;
/**
* Replace the contents of el with the HTML string of html. Unlike other
* DOM functions, this takes a literal string for its second argument.
* @param el is a jQuery argument: https://api.jquery.com/jQuery/
* @param html is a jQuery.html argument: https://api.jquery.com/html/
*/
setInnerContent(el: any, html: string): void;
/**
* Detach el from the DOM.
* @param el is a jQuery argument: https://api.jquery.com/jQuery/
*/
detachEl(el: any): void;
/**
* Remove el from the DOM.
* @param el is a jQuery argument: https://api.jquery.com/jQuery/
*/
removeEl(el: any): void;
/**
* Lookup the selector string within the DOM node for context. The
* optional context argument will come in as a DOM Node reference to run
* the selector search. If context hasn't been set, then findEls should
* search the entire document for the selector.
* @param selector is a jQuery argument: https://api.jquery.com/jQuery/
* @param context is a jQuery argument: https://api.jquery.com/jQuery/
*/
findEls(selector: any, context: any): void;
/**
* Receives a hash of event names and functions and/or function names,
* and returns the same hash with the function names replaced with the
* function references themselves.
*/
normalizeMethods<T>(hash: any): T;
/**
* A handy function to pluck certain options and attach them directly
* to an instance.
*/
mergeOptions(options: any, keys: any): void;
/**
* Retrieve an object's attribute either directly from the object, or from
* the object's this.options, with this.options taking precedence.
* @param optionName the name of the option to retrieve.
*/
getOption(optionName: string): any;
/**
* This method is used to bind a backbone "entity" (collection/model) to
* methods on a target object.
*/
bindEvents(entity: any, bindings: any): void;
/**
* This method can be used to unbind callbacks from entities'
* (collection/model) events.
*/
unbindEvents(entity: any, bindings: any): void;
/**
* Internal property. (undocumented)
*/
supportsRenderLifecycle: boolean;
/**
* Internal property. (undocumented)
*/
supportsDestroyLifecycle: boolean;
/**
* Check if this View has been destroyed.
*/
isDestroyed(): boolean;
/**
* Check if this View has been rendered.
*/
isRendered(): boolean;
/**
* Check if this View is attached to the DOM.
*/
isAttached(): boolean;
/**
* Overrides Backbone.View.delegateEvents. By default Marionette uses
* this to add handlers for events and triggers. (undocumented)
*/
delegateEvents(eventsArg: any): View<TModel>;
/**
* Get the triggers that are currently attached to this view.
* (undocumented)
*/
getTriggers(): EventsHash;
/**
* Delegate entity events. (undocumented)
*/
delegateEntityEvents(): View<TModel>;
/**
* Undelegate entity events. (undocumented)
*/
undelegateEntityEvents(): View<TModel>;
/**
* Manually destroy a view by calling the destroy method. The method
* unbinds the UI elements, removes the view and its children from the
* DOM and unbinds the listeners. It also triggers lifecycle events.
*/
destroy(...args: any[]): View<TModel>;
/**
* Bind UI elements to this view. By default this is called in the
* render method. (undocumented)
*/
bindUIElements(): any;
/**
* Bind UI elements from this view. (undocumented)
*/
unbindUIElements(): any;
/**
* Customize the event prefix for events that are forwarded through the
* collection view.
*/
childViewEventPrefix: string | false;
/**
* Trigger an event and a corresponding method on the target object.
* All arguments that are passed to the triggerMethod call are passed
* along to both the event and the method, with the exception of the
* event name not being passed to the corresponding method.
*/
triggerMethod(name: string, ...args: any[]): any;
/**
* Define the region class used for this View.
*/
regionClass: any;
/**
* Add a region to this View.
*/
addRegion(regionName: string, element: any): any;
/**
* Add multiple regions to this View.
*/
addRegions(regions: any): any;
/**
* Remove a region from this View.
*/
removeRegion(regionName: string): any;
/**
* Remove all regions from this View.
*/
removeRegions(): any;
/**
* Empty all regions from this View.
*/
emptyRegions(): any;
/**
* Check if this View has a particular region.
*/
hasRegion(regionName: string): any;
/**
* Return a region from this View.
*/
getRegion(regionName: string): Region;
/**
* Returns all regions from this View.
*/
getRegions(): any;
/**
* Show a view inside a region.
*/
showChildView(regionName: string, view: any, options?: RegionViewOptions): void;
/**
* Detach a view from a region.
*/
detachChildView<TModel extends Backbone.Model>(regionName: string): Backbone.View<TModel>;
/**
* Get the view from a region.
*/
getChildView<TModel extends Backbone.Model>(regionName: string): Backbone.View<TModel>;
/**
* The results of this method ared passed to this View's template. By
* default Marionette will attempt to pass either an attached model or
* collection which has been converted to JSON.
*/
serializeData(): any;
/**
* Method used by this.serializeData to serialize this View's model
* data.
*/
serializeModel(): any;
/**
* Method used by this.serializeData to serialize this View's collection
* data.
*/
serializeCollection(): any;
/**
* Rebind this View to a new element. Overriding Backbone.View’s
* setElement to handle if an element was previously defined.
* (undocumented)
*/
setElement(element: any): View<TModel>;
/**
* Renders the view. Given a template this method will build your HTML
* from that template, mixing in model information and any extra
* template context.
*/
render(): View<TModel>;
/**
* Used to determine which template to use. Override this method to add
* logic for using multiple templates.
*/
getTemplate(): any;
/**
* Mix in template context methods. Looks for a templateContext
* attribute, which can either be an object literal, or a function that
* returns an object literal. All methods and attributes from this
* object are copies to the object passed in. (undocumented)
*/
mixinTemplateContext(...args: any[]): any;
/**
* Used to attached the rendered template to this View's element.
*/
attachElContent(html: string): View<TModel>;
/**
* Used to set the renderer for this View. The rendere function is
* passed the template and the data and is expected to return an html
* string. By default this is set to use Renderer.
*/
setRenderer(renderer: (template: any, data: any) => string): void;
/**
* Event that is triggered before this View is rendered.
*/
onBeforeRender(view: View<TModel>): void;
/**
* Event that is triggered after this View is rendered.
*/
onRender(view: View<TModel>): void;
/**
* Event that is triggered before this View is added to the DOM.
*/
onBeforeAttach(view: View<TModel>): void;
/**
* Event that is triggered after this View's element has been added to
* the DOM.
*/
onAttach(view: View<TModel>): void;
/**
* Event that is triggered after this View's content has been added to
* the DOM. Is also triggered every time this.render() is called.
*/
onDomRefresh(view: View<TModel>): void;
/**
* Event that is triggered before this View is destroyed.
*/
onBeforeDestroy(view: View<TModel>, ...args: any[]): void;
/**
* Event that is triggered before this View's element is removed from
* the DOM.
*/
onBeforeDetach(view: View<TModel>): void;
/**
* Event that is triggered before this View's content is removed from
* the DOM.
*/
onDomRemove(view: View<TModel>): void;
/**
* Event that is triggered after this View's element has been removed
* from the DOM.
*/
onDetach(view: View<TModel>): void;
/**
* Event that is triggered after this View is destroyed.
*/
onDestroy(view: View<TModel>, ...args: any[]): void;
/**
* Event that is triggered before a Region is added.
*/
onBeforeAddRegion(regionName: string, region: Region): void;
/**
* Event that is triggered after a Region has been added.
*/
onAddRegion(regionName: string, region: Region): void;
/**
* Event that is triggered before a Region is removed.
*/
onBeforeRemoveRegion(regionName: string, region: Region): void;
/**
* Event that is triggered after a Region has been removed.
*/
onRemoveRegion(regionName: string, region: Region): void;
/**
* Behavior objects to assign to this View.
*/
behaviors: Behavior[] | { [index: string]: typeof Behavior; } | Array<{
behaviorClass: typeof Behavior;
[index: string]: any;
}>;
/**
* Bind to events that occur on attached models.
*/
modelEvents: EventsHash;
/**
* The view triggers attribute binds DOM events to Marionette View events
* that can be responded to at the view or parent level.
*/
triggers: EventsHash;
/**
* Name parts of your template to be used
* throughout the view with the ui attribute.
*/
ui: any;
/**
* Get handle on UI element defined in ui hash
*/
getUI(ui: string): JQuery;
}
export interface CollectionViewOptions<
TModel extends Backbone.Model,
TCollection extends Backbone.Collection<TModel> = Backbone.Collection<TModel>
> extends Backbone.ViewOptions<TModel>, ViewMixinOptions {
/**
* Specify a child view to use.
*/
childView?: ((model: TModel) => typeof Backbone.View) | typeof Backbone.View;
/**
* Define options to pass to the childView constructor.
*/
childViewOptions?: (() => ViewOptions<TModel>) | ViewOptions<TModel>;
/**
* The events attribute binds DOM events to actions to perform on the
* view. It takes DOM event key and a mapping to the handler.
*/
events?: EventsHash;
/**
* Prevent some of the underlying collection's models from being
* rendered as child views.
*/
filter?(child?: TModel, index?: number, collection?: TCollection): boolean;
/**
* Specify a view to use if the collection has no children.
*/
emptyView?: (() => typeof Backbone.View) | typeof Backbone.View;
/**
* Define options to pass to the emptyView constructor.
*/
emptyViewOptions?: (() => ViewOptions<TModel>) | ViewOptions<TModel>;
/**
* If true when you sort your collection there will be no re-rendering,
* only the DOM nodes will be reordered.
*/
reorderOnSort?: boolean;
/**
* If false the collection view will not maintain a sorted collection's
* order in the DOM.
*/
sort?: boolean;
/**
* Render your collection view's children with a different sort order
* than the underlying Backbone collection.
*/
viewComparator?: string | ((element: TModel) => number | string) | ((compare: TModel, to?: TModel) => number); // Mirrors Backbone.Collection.comparator
}
/**
* The CollectionView will loop through all of the models in the specified
* collection, render each of them using a specified childView, then append
* the results of the child view's el to the collection view's el. By
* default the CollectionView will maintain a sorted collection's order in the
* DOM. This behavior can be disabled by specifying {sort: false} on
* initialize.
*/
export class CollectionView<TModel extends Backbone.Model, TView extends View<TModel>, TCollection extends Backbone.Collection<TModel> = Backbone.Collection<TModel>> extends View<TModel> {
constructor(options?: CollectionViewOptions<TModel, TCollection>);
/**
* Specify a child view to use.
*/
childView: ((model: TModel) => { new(...args: any[]): TView }) | { new(...args: any[]): TView };
/**
* Define options to pass to the childView constructor.
*/
childViewOptions: ((model: TModel, index: number) => ViewOptions<TModel>) | ViewOptions<TModel>;
/**
* Prevent some of the underlying collection's models from being
* rendered as child views.
*/
filter: (child?: TModel, index?: number, collection?: TCollection) => boolean;
/**
* Modify the CollectionView's filter attribute, and renders the new
* ChildViews in a efficient way, instead of rendering the whole DOM
* structure again.
*/
setFilter: (filter: (child?: TModel, index?: number, collection?: TCollection) => boolean, options: { preventRender: boolean }) => void;
/**
* Remove a filter from the CollectionView.
*/
removeFilter: (options: { preventRender: boolean }) => void;
/**
* Specify a view to use if the collection has no children.
*/
emptyView: (() => { new(...args: any[]): Backbone.View<TModel> }) | { new(...args: any[]): Backbone.View<TModel> };
/**
* Define options to pass to the emptyView constructor.
*/
emptyViewOptions: ((model: TModel, index: number) => ViewOptions<TModel>) | ViewOptions<TModel>;
/**
* Method used to determine when emptyView is rendered.
*/
isEmpty(): boolean;
/**
* The render method of the collection view is responsible for rendering
* the entire collection. It loops through each of the children in the
* collection and renders them individually as an childView.
*/
render(): CollectionView<TModel, TView, TCollection>;
/**
* This method is used move the HTML from the element buffer into the
* collection view's el.
*/
attachHtml(collectionView: CollectionView<TModel, TView, TCollection>, childView: TView, index: number): void;
/**
* When overriding attachHtml it may be necessary to also override how
* the buffer is attached.
*/
attachBuffer(collectionView: CollectionView<TModel, TView, TCollection>, buffer: DocumentFragment): void;
/**
* Customize the event prefix for events that are forwarded through the
* collection view.
*/
childViewEventPrefix: string | false;
/**
* Use the childViewEvents attribute to map child events to methods on the
* parent view.
*/
childViewEvents: EventsHash;
/**
* A childViewTriggers hash or method permits proxying of child view events
* without manually setting bindings. The values of the hash should be a
* string of the event to trigger on the parent.
*/
childViewTriggers: EventsHash;
/**
* Bind to events that occur on attached collections.
*/
collectionEvents: EventsHash;
/**
* Bind to events that occur on attached models.
*/
modelEvents: EventsHash;
/**
* The view triggers attribute binds DOM events to Marionette View events
* that can be responded to at the view or parent level.
*/
triggers: EventsHash;
/**
* If true when you sort your collection there will be no re-rendering,
* only the DOM nodes will be reordered.
*/
reorderOnSort: boolean;
/**
* If reorderOnSort is set to true, this function will be used instead
* of re-rendering all children.
*/
reorder(): void;
/**
* By default the CollectionView will maintain the order of its
* collection in the DOM. However on occasions the view may need to
* re-render to make this possible, for example if you were to change
* the comparator on the collection. The CollectionView will re-render
* its children or reorder them depending on reorderOnSort.
*/
resortView(): void;
/**
* Render your collection view's children with a different sort order
* than the underlying Backbone collection.
*/
viewComparator: string | ((element: TModel) => number | string) | ((compare: TModel, to?: TModel) => number); // Mirrors Backbone.Collection.comparator
/**
* Override this method to determine which viewComparator to use.
*/
getViewComparator: () => (string | ((element: TModel) => number | string) | ((compare: TModel, to?: TModel) => number)); // Mirrors Backbone.Collection.comparator
/**
* Behavior objects to assign to this View.
*/
behaviors: Behavior[] | { [index: string]: typeof Behavior; } | Array<{
behaviorClass: typeof Behavior;
[index: string]: any;
}>;
/**
* Name parts of your template to be used throughout the view with the
* ui attribute.
*/
ui: any;
/**
* The CollectionView can store and manage its child views. This allows
* you to easily access the views within the collection view, iterate
* them, find them by a given indexer such as the view's model or
* collection, and more.
*/
children: Container<TView>;
/**
* The buildChildView is responsible for taking the ChildView class and
* instantiating it with the appropriate data.
*/
buildChildView(child: TModel, childViewClass: { new(...args: any[]): TView }, childViewOptions: ViewOptions<TModel>): void;
/**
* The addChildView method can be used to add a view that is independent
* of your Backbone.Collection.
*/
addChildView(childView: TView, index: number): void;
/**
* The removeChildView method is useful if you need to remove a view
* from the CollectionView without affecting the view's collection.
*/
removeChildView(childView: TView): void;
/**
* Called just prior to rendering the collection view.
*/
onBeforeRender(): void;
/**
* Triggered after the view has been rendered. You can implement this in
* your view to provide custom code for dealing with the view's el after
* it has been rendered.
*/
onRender(): void;
/**
* This callback function allows you to know when a child / child view
* instance is about to be added to the collection view. It provides
* access to the view instance for the child that was added.
*/
onBeforeAddChild(collectionView: CollectionView<TModel, TView, TCollection>, childView: TView): void;
/**
* This callback function allows you to know when a child / child view
* instance has been added to the collection view. It provides access to
* the view instance for the child that was added.
*/
onAddChild(collectionView: CollectionView<TModel, TView, TCollection>, childView: TView): void;
/**
* This callback function allows you to know when a childView instance is
* about to be removed from the collectionView. It provides access to the
* view instance for the child that was removed.
*/
onBeforeRemoveChild(collectionView: CollectionView<TModel, TView, TCollection>, childView: TView): void;
/**
* This callback function allows you to know when a child / childView
* instance has been deleted or removed from the collection.
*/
onRemoveChild(collectionView: CollectionView<TModel, TView, TCollection>, childView: TView): void;
/**
* Automatically destroys this Collection's children and cleans up
* listeners.
*/
destroy(...args: any[]): CollectionView<TModel, TView, TCollection>;
}
export interface AppRoutes {
[index: string]: string;
}
export interface AppRouterOptions {
/**
* Define the app routes and the method names on the controller that
* will be called when accessing the routes.
*/
appRoutes?: AppRoutes;
/**
* Define the app routes and the method names on the router that will be
* called when accessing the routes.
*/
routes?: AppRoutes;
/**
* An object that contains the methods specified in appRoutes.
*/
controller?: any;
}
/**
* The Marionette AppRouter is typically used to set up your app when the
* user loads a specific endpoint directly.
*/
export class AppRouter extends Backbone.Router {
constructor(options?: AppRouterOptions);
/**
* Add an app route at runtime.
*/
appRoute(route: string, methodName: string): void;
/**
* Specify a controller with the multiple routes at runtime. This will
* preserve the existing controller as well.
*/
processAppRoutes(controller: any, appRoutes: AppRoutes): void;
/**
* An object that contains the methods specified in appRoutes.
*/
controller: any;
/**
* Fires whenever the user navigates to a new route in your application
* that matches a route.
*/
onRoute(name: string, path: string, args: any[]): void;
}
export interface ApplicationOptions extends ObjectOptions {
/**
* Root entry point for the View tree of your Application.
*/
region: string;
}
/**
* The Application is used to model your Marionette application under a
* single entry point. The application provides:
* - An obvious entry point to your app
* - A clear hook for global events e.g. the AppRouter
* - An interface to let you inject variables from the wider context into
* your app
*/
export class Application extends Object {
constructor(options?: ApplicationOptions);
/**
* Root entry point for the View tree of your Application.
*/
region: string;
/**
* Called immediately after the Application has been instantiated, and
* is invoked with the same arguments that the constructor received.
*/
initialize(options: ApplicationOptions): void;
/**
* Fired just before the application is started.
*/
onBeforeStart(options: ApplicationOptions): void;
/**
* Fired as part of the application startup.
*/
onStart(options: ApplicationOptions): void;
/**
* Once you have your application configured, you can kick everything
* off by calling this method.
*/
start(options?: any): void;
/**
* Return the attached region object for the Application.
*/
getRegion(): Region;
/**
* Display View in the region attached to the Application. This runs the
* View lifecycle.
*/
showView(view: View<any>): void;
/**
* Return the view currently being displayed in the Application's
* attached region. If the Application is not currently displaying a
* view, this method returns undefined.
*/
getView(): View<any>;
}
/**
* A Behavior provides a clean separation of concerns to your view logic,
* allowing you to share common user-facing operations between your views.
*/
export class Behavior extends Object {
constructor(options?: any);
options: any;
/**
* Behaviors can have their own ui hash, which will be mixed into the ui
* hash of its associated View instance. ui elements defined on either the
* Behavior or the View will be made available within events and triggers.
* They also are attached directly to the Behavior and can be accessed within
* Behavior methods as this.ui.
*/
ui: any;
/**
* Get handle on UI element defined in ui hash
*/
getUI(ui: string): JQuery;
/**
* Any triggers you define on the Behavior will be triggered in response to the appropriate event on the view.
*/
triggers: EventsHash;
/**
* modelEvents will respond to the view's model events.
*/
modelEvents: EventsHash;
/**
* collectionEvents will respond to the view's collection events.
*/
collectionEvents: EventsHash;
/**
* The behaviors key allows a behavior to group multiple behaviors
* together.
*/
behaviors: Behavior[] | { [index: string]: typeof Behavior; } | Array<{
behaviorClass: typeof Behavior;
[index: string]: any;
}>;
/**
* defaults can be a hash or function to define the default options for
* your behavior. The default options will be overridden depending on
* what you set as the options per behavior (this works just like a
* backbone.model).
*/
defaults: any;
/**
* el is a direct proxy of the view's el
*/
el: any;
/**
* $el is a direct proxy of the view's el cached as a jQuery selector.
*/
$el: JQuery;
/**
* The View that this behavior is attached to.
*/
view: View<any>;
/**
* $ is a direct proxy of the views $ lookup method.
*/
$(selector: any): JQuery;
}
/**
* DEPRECATED
*/
export namespace Behaviors {
/**
* This method defines where your behavior classes are stored. Override this to provide another lookup.
*/
function behaviorsLookup(): any;
/**
* This method has a default implementation that is simple to override. It
* is responsible for the lookup of single behavior from within the
* Behaviors.behaviorsLookup or elsewhere. Note that it should return the type of the
* class to instantiate, not an instance of that class.
*/
function getBehaviorClass(options: any, key: string): any;
}
| types/backbone.marionette/index.d.ts | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/f1cf1c35fcc34501098164d5c76e0ccf41efeee9 | [
0.0012093535624444485,
0.00018451893993187696,
0.0001650072226766497,
0.0001698065607342869,
0.00008887809235602617
] |
{
"id": 0,
"code_window": [
"import * as blocked from 'blocked';\n",
"\n",
"blocked((ms: number) => {\n",
" // todo: show warning\n",
"}, {\n",
" threshold: 10\n",
"});"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" threshold: 10,\n",
" interval: 10,\n"
],
"file_path": "types/blocked/blocked-tests.ts",
"type": "replace",
"edit_start_line_idx": 5
} | export default function deprecationWarning(oldname: any, newname: string, link?: string): void;
export function wrapper(Component: any, ...args: any[]): any;
export function _resetWarned(): void;
| types/react-bootstrap/lib/utils/deprecationWarning.d.ts | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/f1cf1c35fcc34501098164d5c76e0ccf41efeee9 | [
0.0002592185337562114,
0.0002592185337562114,
0.0002592185337562114,
0.0002592185337562114,
0
] |
{
"id": 0,
"code_window": [
"import * as blocked from 'blocked';\n",
"\n",
"blocked((ms: number) => {\n",
" // todo: show warning\n",
"}, {\n",
" threshold: 10\n",
"});"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" threshold: 10,\n",
" interval: 10,\n"
],
"file_path": "types/blocked/blocked-tests.ts",
"type": "replace",
"edit_start_line_idx": 5
} | {
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": false,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"gulp-istanbul-tests.ts"
]
} | types/gulp-istanbul/tsconfig.json | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/f1cf1c35fcc34501098164d5c76e0ccf41efeee9 | [
0.00017132713401224464,
0.00017059822857845575,
0.0001695835089776665,
0.00017088401364162564,
7.39962217721768e-7
] |
{
"id": 1,
"code_window": [
"// Type definitions for blocked 1.2\n",
"// Project: https://github.com/visionmedia/node-blocked#readme\n",
"// Definitions by: Jonas Lochmann <https://github.com/l-jonas>\n",
"// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped\n",
"\n",
"/// <reference types=\"node\" />\n"
],
"labels": [
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"// Type definitions for blocked 1.3\n"
],
"file_path": "types/blocked/index.d.ts",
"type": "replace",
"edit_start_line_idx": 0
} | // Type definitions for blocked 1.2
// Project: https://github.com/visionmedia/node-blocked#readme
// Definitions by: Jonas Lochmann <https://github.com/l-jonas>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="node" />
/*~ Note that ES6 modules cannot directly export callable functions.
*~ This file should be imported using the CommonJS-style:
*~ import x = require('someLibrary');
*~
*~ Refer to the documentation to understand common
*~ workarounds for this limitation of ES6 modules.
*/
export = Blocked;
declare function Blocked(callback: (ms: number) => void, options?: Blocked.Options): NodeJS.Timer;
declare namespace Blocked {
interface Options {
threshold: number; // in milliseconds
}
}
| types/blocked/index.d.ts | 1 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/f1cf1c35fcc34501098164d5c76e0ccf41efeee9 | [
0.05239972472190857,
0.018108638003468513,
0.0001678861299296841,
0.001758298953063786,
0.024256153032183647
] |
{
"id": 1,
"code_window": [
"// Type definitions for blocked 1.2\n",
"// Project: https://github.com/visionmedia/node-blocked#readme\n",
"// Definitions by: Jonas Lochmann <https://github.com/l-jonas>\n",
"// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped\n",
"\n",
"/// <reference types=\"node\" />\n"
],
"labels": [
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"// Type definitions for blocked 1.3\n"
],
"file_path": "types/blocked/index.d.ts",
"type": "replace",
"edit_start_line_idx": 0
} | import * as aws4 from "aws4";
let requestSigner = new aws4.RequestSigner({}, {});
requestSigner.matchHost("");
requestSigner.isSingleRegion();
requestSigner.createHost();
requestSigner.prepareRequest();
requestSigner.sign();
requestSigner.getDateTime();
requestSigner.getDate();
requestSigner.authHeader();
requestSigner.signature();
requestSigner.stringToSign();
requestSigner.canonicalString();
requestSigner.canonicalHeaders();
requestSigner.signedHeaders();
requestSigner.credentialString();
requestSigner.defaultCredentials();
requestSigner.parsePath();
requestSigner.formatPath();
aws4.sign({}, {});
| types/aws4/aws4-tests.ts | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/f1cf1c35fcc34501098164d5c76e0ccf41efeee9 | [
0.00017712844419293106,
0.00017335421580355614,
0.00017077910888474435,
0.00017215509433299303,
0.0000027272615170659265
] |
{
"id": 1,
"code_window": [
"// Type definitions for blocked 1.2\n",
"// Project: https://github.com/visionmedia/node-blocked#readme\n",
"// Definitions by: Jonas Lochmann <https://github.com/l-jonas>\n",
"// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped\n",
"\n",
"/// <reference types=\"node\" />\n"
],
"labels": [
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"// Type definitions for blocked 1.3\n"
],
"file_path": "types/blocked/index.d.ts",
"type": "replace",
"edit_start_line_idx": 0
} | /**
* Calculates the euclidian distance between two number's. Aliased as dist.
*/
declare function dist(a: number[], b: number[]): number;
export default dist;
| types/gl-vec3/dist.d.ts | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/f1cf1c35fcc34501098164d5c76e0ccf41efeee9 | [
0.00017416295304428786,
0.00017416295304428786,
0.00017416295304428786,
0.00017416295304428786,
0
] |
{
"id": 1,
"code_window": [
"// Type definitions for blocked 1.2\n",
"// Project: https://github.com/visionmedia/node-blocked#readme\n",
"// Definitions by: Jonas Lochmann <https://github.com/l-jonas>\n",
"// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped\n",
"\n",
"/// <reference types=\"node\" />\n"
],
"labels": [
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"// Type definitions for blocked 1.3\n"
],
"file_path": "types/blocked/index.d.ts",
"type": "replace",
"edit_start_line_idx": 0
} | {
"extends": "dtslint/dt.json",
"rules": {
"npm-naming": false
}
} | types/markdown-it-lazy-headers/tslint.json | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/f1cf1c35fcc34501098164d5c76e0ccf41efeee9 | [
0.00017297384329140186,
0.00017297384329140186,
0.00017297384329140186,
0.00017297384329140186,
0
] |
{
"id": 2,
"code_window": [
"declare function Blocked(callback: (ms: number) => void, options?: Blocked.Options): NodeJS.Timer;\n",
"\n",
"declare namespace Blocked {\n",
" interface Options {\n",
" threshold: number; // in milliseconds\n",
" }\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
" threshold?: number; // in milliseconds\n",
" interval?: number; // in milliseconds\n"
],
"file_path": "types/blocked/index.d.ts",
"type": "replace",
"edit_start_line_idx": 21
} | // Type definitions for blocked 1.2
// Project: https://github.com/visionmedia/node-blocked#readme
// Definitions by: Jonas Lochmann <https://github.com/l-jonas>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="node" />
/*~ Note that ES6 modules cannot directly export callable functions.
*~ This file should be imported using the CommonJS-style:
*~ import x = require('someLibrary');
*~
*~ Refer to the documentation to understand common
*~ workarounds for this limitation of ES6 modules.
*/
export = Blocked;
declare function Blocked(callback: (ms: number) => void, options?: Blocked.Options): NodeJS.Timer;
declare namespace Blocked {
interface Options {
threshold: number; // in milliseconds
}
}
| types/blocked/index.d.ts | 1 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/f1cf1c35fcc34501098164d5c76e0ccf41efeee9 | [
0.9929288029670715,
0.6529565453529358,
0.0009797809179872274,
0.9649611711502075,
0.4611585736274719
] |
{
"id": 2,
"code_window": [
"declare function Blocked(callback: (ms: number) => void, options?: Blocked.Options): NodeJS.Timer;\n",
"\n",
"declare namespace Blocked {\n",
" interface Options {\n",
" threshold: number; // in milliseconds\n",
" }\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
" threshold?: number; // in milliseconds\n",
" interval?: number; // in milliseconds\n"
],
"file_path": "types/blocked/index.d.ts",
"type": "replace",
"edit_start_line_idx": 21
} | {
"extends": "dtslint/dt.json",
"rules": {
"adjacent-overload-signatures": false,
"array-type": false,
"arrow-return-shorthand": false,
"ban-types": false,
"callable-types": false,
"comment-format": false,
"dt-header": false,
"npm-naming": false,
"eofline": false,
"export-just-namespace": false,
"import-spacing": false,
"interface-name": false,
"interface-over-type-literal": false,
"jsdoc-format": false,
"max-line-length": false,
"member-access": false,
"new-parens": false,
"no-any-union": false,
"no-boolean-literal-compare": false,
"no-conditional-assignment": false,
"no-consecutive-blank-lines": false,
"no-construct": false,
"no-declare-current-package": false,
"no-duplicate-imports": false,
"no-duplicate-variable": false,
"no-empty-interface": false,
"no-for-in-array": false,
"no-inferrable-types": false,
"no-internal-module": false,
"no-irregular-whitespace": false,
"no-mergeable-namespace": false,
"no-misused-new": false,
"no-namespace": false,
"no-object-literal-type-assertion": false,
"no-padding": false,
"no-redundant-jsdoc": false,
"no-redundant-jsdoc-2": false,
"no-redundant-undefined": false,
"no-reference-import": false,
"no-relative-import-in-test": false,
"no-self-import": false,
"no-single-declare-module": false,
"no-string-throw": false,
"no-unnecessary-callback-wrapper": false,
"no-unnecessary-class": false,
"no-unnecessary-generics": false,
"no-unnecessary-qualifier": false,
"no-unnecessary-type-assertion": false,
"no-useless-files": false,
"no-var-keyword": false,
"no-var-requires": false,
"no-void-expression": false,
"no-trailing-whitespace": false,
"object-literal-key-quotes": false,
"object-literal-shorthand": false,
"one-line": false,
"one-variable-per-declaration": false,
"only-arrow-functions": false,
"prefer-conditional-expression": false,
"prefer-const": false,
"prefer-declare-function": false,
"prefer-for-of": false,
"prefer-method-signature": false,
"prefer-template": false,
"radix": false,
"semicolon": false,
"space-before-function-paren": false,
"space-within-parens": false,
"strict-export-declare-modifiers": false,
"trim-file": false,
"triple-equals": false,
"typedef-whitespace": false,
"unified-signatures": false,
"void-return": false,
"whitespace": false
}
}
| types/gapi/tslint.json | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/f1cf1c35fcc34501098164d5c76e0ccf41efeee9 | [
0.0001743046595947817,
0.00016924981900956482,
0.00016694702208042145,
0.0001684957096586004,
0.000002389845121797407
] |
{
"id": 2,
"code_window": [
"declare function Blocked(callback: (ms: number) => void, options?: Blocked.Options): NodeJS.Timer;\n",
"\n",
"declare namespace Blocked {\n",
" interface Options {\n",
" threshold: number; // in milliseconds\n",
" }\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
" threshold?: number; // in milliseconds\n",
" interval?: number; // in milliseconds\n"
],
"file_path": "types/blocked/index.d.ts",
"type": "replace",
"edit_start_line_idx": 21
} | { "extends": "dtslint/dt.json" }
| types/project-name/tslint.json | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/f1cf1c35fcc34501098164d5c76e0ccf41efeee9 | [
0.00017123224097304046,
0.00017123224097304046,
0.00017123224097304046,
0.00017123224097304046,
0
] |
{
"id": 2,
"code_window": [
"declare function Blocked(callback: (ms: number) => void, options?: Blocked.Options): NodeJS.Timer;\n",
"\n",
"declare namespace Blocked {\n",
" interface Options {\n",
" threshold: number; // in milliseconds\n",
" }\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
" threshold?: number; // in milliseconds\n",
" interval?: number; // in milliseconds\n"
],
"file_path": "types/blocked/index.d.ts",
"type": "replace",
"edit_start_line_idx": 21
} | # TypeScript typings for Cloud Tool Results API v1beta3
Reads and publishes results from Firebase Test Lab.
For detailed description please check [documentation](https://firebase.google.com/docs/test-lab/).
## Installing
Install typings for Cloud Tool Results API:
```
npm install @types/gapi.client.toolresults@v1beta3 --save-dev
```
## Usage
You need to initialize Google API client in your code:
```typescript
gapi.load("client", () => {
// now we can use gapi.client
// ...
});
```
Then load api client wrapper:
```typescript
gapi.client.load('toolresults', 'v1beta3', () => {
// now we can use gapi.client.toolresults
// ...
});
```
Don't forget to authenticate your client before sending any request to resources:
```typescript
// declare client_id registered in Google Developers Console
var client_id = '',
scope = [
// View and manage your data across Google Cloud Platform services
'https://www.googleapis.com/auth/cloud-platform',
],
immediate = true;
// ...
gapi.auth.authorize({ client_id: client_id, scope: scope, immediate: immediate }, authResult => {
if (authResult && !authResult.error) {
/* handle succesfull authorization */
} else {
/* handle authorization error */
}
});
```
After that you can use Cloud Tool Results API resources:
```typescript
/*
Gets the Tool Results settings for a project.
May return any of the following canonical error codes:
- PERMISSION_DENIED - if the user is not authorized to read from project
*/
await gapi.client.projects.getSettings({ projectId: "projectId", });
/*
Creates resources for settings which have not yet been set.
Currently, this creates a single resource: a Google Cloud Storage bucket, to be used as the default bucket for this project. The bucket is created in an FTL-own storage project. Except for in rare cases, calling this method in parallel from multiple clients will only create a single bucket. In order to avoid unnecessary storage charges, the bucket is configured to automatically delete objects older than 90 days.
The bucket is created with the following permissions: - Owner access for owners of central storage project (FTL-owned) - Writer access for owners/editors of customer project - Reader access for viewers of customer project The default ACL on objects created in the bucket is: - Owner access for owners of central storage project - Reader access for owners/editors/viewers of customer project See Google Cloud Storage documentation for more details.
If there is already a default bucket set and the project can access the bucket, this call does nothing. However, if the project doesn't have the permission to access the bucket or the bucket is deleted, a new bucket will be created.
May return any canonical error codes, including the following:
- PERMISSION_DENIED - if the user is not authorized to write to project - Any error code raised by Google Cloud Storage
*/
await gapi.client.projects.initializeSettings({ projectId: "projectId", });
``` | types/gapi.client.toolresults/readme.md | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/f1cf1c35fcc34501098164d5c76e0ccf41efeee9 | [
0.0001716621918603778,
0.00016896177839953452,
0.00016270567721221596,
0.00017033639596775174,
0.0000029740815534751164
] |
{
"id": 0,
"code_window": [
"// import nodeCleanup = require('node-cleanup');\n",
"\n",
"export = install;\n",
"\n",
"declare function install(cleanupHandler?: ((exitCode: number | null, signal: string | null) => boolean | undefined),\n",
" stderrMessages?: { ctrl_C: string; uncaughtException: string }): void;\n",
"\n",
"declare namespace install {\n",
" function uninstall(): void;\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"declare function install(cleanupHandler?: ((exitCode: number | null, signal: string | null) => boolean | undefined | void),\n"
],
"file_path": "types/node-cleanup/index.d.ts",
"type": "replace",
"edit_start_line_idx": 11
} | import nodeCleanup = require('node-cleanup');
function cleanupHandler(exitCode: number | null, signal: string | null): boolean | undefined {
return true;
}
const stderrMessages = { ctrl_C: 'ctrl_c', uncaughtException: 'UncaughtException' };
nodeCleanup();
nodeCleanup(cleanupHandler);
nodeCleanup(cleanupHandler, undefined);
nodeCleanup(cleanupHandler, stderrMessages);
nodeCleanup(undefined, stderrMessages);
nodeCleanup.uninstall();
| types/node-cleanup/node-cleanup-tests.ts | 1 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/c2426c074c86b337e01714cb1b5b20cdf359509f | [
0.9979117512702942,
0.9906162619590759,
0.9833207726478577,
0.9906162619590759,
0.007295489311218262
] |
{
"id": 0,
"code_window": [
"// import nodeCleanup = require('node-cleanup');\n",
"\n",
"export = install;\n",
"\n",
"declare function install(cleanupHandler?: ((exitCode: number | null, signal: string | null) => boolean | undefined),\n",
" stderrMessages?: { ctrl_C: string; uncaughtException: string }): void;\n",
"\n",
"declare namespace install {\n",
" function uninstall(): void;\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"declare function install(cleanupHandler?: ((exitCode: number | null, signal: string | null) => boolean | undefined | void),\n"
],
"file_path": "types/node-cleanup/index.d.ts",
"type": "replace",
"edit_start_line_idx": 11
} | // Type definitions for @hapi/nes 11.0
// Project: https://github.com/hapijs/nes
// Definitions by: Ivo Stratev <https://github.com/NoHomey>
// Rodrigo Saboya <https://github.com/saboya>
// Silas Rech <https://github.com/lenovouser>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.8
declare class Client {
constructor(url: string, options?: Client.ClientOptions);
onError: (err: any) => void;
onConnect: () => void;
onDisconnect: (willReconnect: boolean, log: { code: number, explanation: string, reason: string, wasClean: boolean }) => void;
onUpdate: (message: any) => void;
connect(options: Client.ClientConnectOptions): Promise<any>;
connect(): Promise<any>;
disconnect(): Promise<any>;
id: any; // can be `null | number` but also the "socket" value from websocket message data.
request(options: string | Client.ClientRequestOptions): Promise<any>;
message(message: any): Promise<any>;
subscribe(path: string, handler: Client.Handler): Promise<any>;
unsubscribe(path: string, handler?: Client.Handler): Promise<any>;
subscriptions(): string[];
overrideReconnectionAuth(auth: any): void;
reauthenticate(auth: any): Promise<true>;
}
declare namespace Client {
interface Handler {
(message: any, flags: Client.ClientSubscribeFlags): void;
}
interface ClientOptions {
ws?: any;
timeout?: number | boolean;
}
interface ClientConnectOptions {
auth?: any;
delay?: number;
maxDelay?: number;
retries?: number;
timeout?: number;
}
interface ClientRequestOptions {
path: string;
method?: string;
headers?: Object;
payload?: any;
}
interface ClientSubscribeFlags {
revoked?: boolean;
}
}
export { Client };
| types/hapi__nes/lib/client.d.ts | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/c2426c074c86b337e01714cb1b5b20cdf359509f | [
0.0019334363751113415,
0.0006290634046308696,
0.00016741742729209363,
0.00042650772957131267,
0.0006063703331165016
] |
{
"id": 0,
"code_window": [
"// import nodeCleanup = require('node-cleanup');\n",
"\n",
"export = install;\n",
"\n",
"declare function install(cleanupHandler?: ((exitCode: number | null, signal: string | null) => boolean | undefined),\n",
" stderrMessages?: { ctrl_C: string; uncaughtException: string }): void;\n",
"\n",
"declare namespace install {\n",
" function uninstall(): void;\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"declare function install(cleanupHandler?: ((exitCode: number | null, signal: string | null) => boolean | undefined | void),\n"
],
"file_path": "types/node-cleanup/index.d.ts",
"type": "replace",
"edit_start_line_idx": 11
} | { "extends": "dtslint/dt.json" }
| types/react-instantsearch-native/tslint.json | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/c2426c074c86b337e01714cb1b5b20cdf359509f | [
0.00016485828382428735,
0.00016485828382428735,
0.00016485828382428735,
0.00016485828382428735,
0
] |
{
"id": 0,
"code_window": [
"// import nodeCleanup = require('node-cleanup');\n",
"\n",
"export = install;\n",
"\n",
"declare function install(cleanupHandler?: ((exitCode: number | null, signal: string | null) => boolean | undefined),\n",
" stderrMessages?: { ctrl_C: string; uncaughtException: string }): void;\n",
"\n",
"declare namespace install {\n",
" function uninstall(): void;\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"declare function install(cleanupHandler?: ((exitCode: number | null, signal: string | null) => boolean | undefined | void),\n"
],
"file_path": "types/node-cleanup/index.d.ts",
"type": "replace",
"edit_start_line_idx": 11
} | { "extends": "dtslint/dt.json" }
| types/react-animate-on-scroll/tslint.json | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/c2426c074c86b337e01714cb1b5b20cdf359509f | [
0.00016485828382428735,
0.00016485828382428735,
0.00016485828382428735,
0.00016485828382428735,
0
] |
{
"id": 1,
"code_window": [
"import nodeCleanup = require('node-cleanup');\n",
"\n",
"function cleanupHandler(exitCode: number | null, signal: string | null): boolean | undefined {\n",
" return true;\n",
"}\n",
"const stderrMessages = { ctrl_C: 'ctrl_c', uncaughtException: 'UncaughtException' };\n",
"\n",
"nodeCleanup();\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"function voidHandler(): void {\n",
" // do nothing\n",
"}\n"
],
"file_path": "types/node-cleanup/node-cleanup-tests.ts",
"type": "add",
"edit_start_line_idx": 5
} | import nodeCleanup = require('node-cleanup');
function cleanupHandler(exitCode: number | null, signal: string | null): boolean | undefined {
return true;
}
const stderrMessages = { ctrl_C: 'ctrl_c', uncaughtException: 'UncaughtException' };
nodeCleanup();
nodeCleanup(cleanupHandler);
nodeCleanup(cleanupHandler, undefined);
nodeCleanup(cleanupHandler, stderrMessages);
nodeCleanup(undefined, stderrMessages);
nodeCleanup.uninstall();
| types/node-cleanup/node-cleanup-tests.ts | 1 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/c2426c074c86b337e01714cb1b5b20cdf359509f | [
0.9992127418518066,
0.9987605810165405,
0.9983084201812744,
0.9987605810165405,
0.0004521608352661133
] |
{
"id": 1,
"code_window": [
"import nodeCleanup = require('node-cleanup');\n",
"\n",
"function cleanupHandler(exitCode: number | null, signal: string | null): boolean | undefined {\n",
" return true;\n",
"}\n",
"const stderrMessages = { ctrl_C: 'ctrl_c', uncaughtException: 'UncaughtException' };\n",
"\n",
"nodeCleanup();\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"function voidHandler(): void {\n",
" // do nothing\n",
"}\n"
],
"file_path": "types/node-cleanup/node-cleanup-tests.ts",
"type": "add",
"edit_start_line_idx": 5
} | {
"extends": "dtslint/dt.json",
"rules": {
"no-angle-bracket-type-assertion": false
}
}
| types/asynciterator/tslint.json | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/c2426c074c86b337e01714cb1b5b20cdf359509f | [
0.0001709105708869174,
0.0001709105708869174,
0.0001709105708869174,
0.0001709105708869174,
0
] |
{
"id": 1,
"code_window": [
"import nodeCleanup = require('node-cleanup');\n",
"\n",
"function cleanupHandler(exitCode: number | null, signal: string | null): boolean | undefined {\n",
" return true;\n",
"}\n",
"const stderrMessages = { ctrl_C: 'ctrl_c', uncaughtException: 'UncaughtException' };\n",
"\n",
"nodeCleanup();\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"function voidHandler(): void {\n",
" // do nothing\n",
"}\n"
],
"file_path": "types/node-cleanup/node-cleanup-tests.ts",
"type": "add",
"edit_start_line_idx": 5
} | {
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6",
"dom"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": false,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"pouchdb-adapter-memory-tests.ts"
]
} | types/pouchdb-adapter-memory/tsconfig.json | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/c2426c074c86b337e01714cb1b5b20cdf359509f | [
0.00017206631309818476,
0.00017099415708798915,
0.00017000315710902214,
0.000170913030160591,
8.442316357104573e-7
] |
{
"id": 1,
"code_window": [
"import nodeCleanup = require('node-cleanup');\n",
"\n",
"function cleanupHandler(exitCode: number | null, signal: string | null): boolean | undefined {\n",
" return true;\n",
"}\n",
"const stderrMessages = { ctrl_C: 'ctrl_c', uncaughtException: 'UncaughtException' };\n",
"\n",
"nodeCleanup();\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"function voidHandler(): void {\n",
" // do nothing\n",
"}\n"
],
"file_path": "types/node-cleanup/node-cleanup-tests.ts",
"type": "add",
"edit_start_line_idx": 5
} | import {
Feature, FeatureCollection, GeometryCollection, LineString,
MultiLineString, MultiPoint, MultiPolygon, Point, Polygon, GeoJsonGeometryTypes,
GeoJsonTypes, GeometryObject
} from "geojson";
let featureCollection: FeatureCollection = {
type: "FeatureCollection",
features: [
{
id: 1234,
type: "Feature",
geometry: {
type: "Point",
coordinates: [102.0, 0.5]
},
properties: {
prop0: "value0"
}
},
{
id: "stringid",
type: "Feature",
geometry: {
type: "LineString",
coordinates: [
[102.0, 0.0],
[103.0, 1.0],
[104.0, 0.0],
[105.0, 1.0]
]
},
properties: {
prop0: "value0",
prop1: 0.0
}
},
{
type: "Feature",
geometry: {
type: "Polygon",
coordinates: [
[[100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0]]
]
},
properties: {
prop0: "value0",
prop1: {
that: "this"
}
}
}
]
};
featureCollection.type; // $ExpectType "FeatureCollection"
featureCollection.features[0].type; // $ExpectType "Feature"
featureCollection.features[0].geometry; // $ExpectType Geometry
featureCollection.features[0].geometry.type; // $ExpectType "Point" | "MultiPoint" | "LineString" | "MultiLineString" | "Polygon" | "MultiPolygon" | "GeometryCollection"
declare let geometryTypes: GeoJsonGeometryTypes;
geometryTypes; // $ExpectType "Point" | "MultiPoint" | "LineString" | "MultiLineString" | "Polygon" | "MultiPolygon" | "GeometryCollection"
declare let geojsonTypes: GeoJsonTypes;
geojsonTypes; // $ExpectType "FeatureCollection" | "Feature" | "Point" | "MultiPoint" | "LineString" | "MultiLineString" | "Polygon" | "MultiPolygon" | "GeometryCollection"
const featureWithPolygon: Feature<Polygon> = {
type: "Feature",
bbox: [-180.0, -90.0, 180.0, 90.0],
geometry: {
type: "Polygon",
coordinates: [
[[-180.0, 10.0], [20.0, 90.0], [180.0, -5.0], [-30.0, -90.0]]
]
},
properties: null
};
featureWithPolygon.type; // $ExpectType "Feature"
featureWithPolygon.geometry; // $ExpectType Polygon
featureWithPolygon.geometry.type; // $ExpectType "Polygon"
featureWithPolygon.geometry.coordinates; // $ExpectType number[][][]
const point: Point = {
type: "Point",
coordinates: [100.0, 0.0]
};
// This type is commonly used in the turf package
const pointCoordinates: number[] = point.coordinates;
const lineString: LineString = {
type: "LineString",
coordinates: [[100.0, 0.0], [101.0, 1.0]]
};
const polygon: Polygon = {
type: "Polygon",
coordinates: [
[[100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0]]
]
};
const polygonWithHole: Polygon = {
type: "Polygon",
coordinates: [
[[100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0]],
[[100.2, 0.2], [100.8, 0.2], [100.8, 0.8], [100.2, 0.8], [100.2, 0.2]]
]
};
const multiPoint: MultiPoint = {
type: "MultiPoint",
coordinates: [[100.0, 0.0], [101.0, 1.0]]
};
const multiLineString: MultiLineString = {
type: "MultiLineString",
coordinates: [
[[100.0, 0.0], [101.0, 1.0]],
[[102.0, 2.0], [103.0, 3.0]]
]
};
const multiPolygon: MultiPolygon = {
type: "MultiPolygon",
coordinates: [
[[[102.0, 2.0], [103.0, 2.0], [103.0, 3.0], [102.0, 3.0], [102.0, 2.0]]],
[[[100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0]],
[[100.2, 0.2], [100.8, 0.2], [100.8, 0.8], [100.2, 0.8], [100.2, 0.2]]]
]
};
const geometryCollection: GeometryCollection = {
type: "GeometryCollection",
geometries: [
{
type: "Point",
coordinates: [100.0, 0.0]
},
{
type: "LineString",
coordinates: [[101.0, 0.0], [102.0, 1.0]]
}
]
};
let feature: Feature<GeometryObject> = {
type: "Feature",
geometry: lineString,
properties: null
};
feature.properties; // $ExpectType GeoJsonProperties
feature = {
type: "Feature",
geometry: polygon,
properties: null
};
feature = {
type: "Feature",
geometry: polygonWithHole,
properties: null
};
feature = {
type: "Feature",
geometry: multiPoint,
properties: null
};
feature = {
type: "Feature",
geometry: multiLineString,
properties: null
};
feature = {
type: "Feature",
geometry: multiPolygon,
properties: null
};
feature = {
type: "Feature",
geometry: geometryCollection,
properties: null
};
featureCollection = {
type: "FeatureCollection",
features: [
{
type: "Feature",
geometry: lineString,
properties: { test: "OK" }
}, {
type: "Feature",
geometry: polygon,
properties: { test: "OK" }
}, {
type: "Feature",
geometry: polygonWithHole,
properties: { test: "OK" }
}, {
type: "Feature",
geometry: multiPoint,
properties: { test: "OK" }
}, {
type: "Feature",
geometry: multiLineString,
properties: { test: "OK" }
}, {
type: "Feature",
geometry: multiPolygon,
properties: { test: "OK" }
}, {
type: "Feature",
geometry: geometryCollection,
properties: { test: "OK" }
}
]
};
// Allow access to custom properties
const pt: Feature<Point> = {
type: "Feature",
properties: {
foo: "bar",
hello: "world",
1: 2
},
geometry: {
type: "Point",
coordinates: [0, 0]
}
};
if (pt.properties) {
if (pt.properties.foo == null || pt.properties.hello == null || pt.properties[1] == null) {
throw TypeError("Properties should not be null or undefined.");
}
} else {
throw TypeError("Feature should have a 'properties' property.");
}
// Optional generic for properties
interface TestProperty {
foo: "bar" | "baz";
hello: string;
}
const testProps: TestProperty = {
foo: "baz",
hello: "world"
};
const typedPropertiesFeature: Feature<Point> = {
type: "Feature",
properties: testProps,
geometry: {
type: "Point",
coordinates: [0, 0]
}
};
const typedPropertiesFeatureCollection: FeatureCollection<Point> = {
type: "FeatureCollection",
features: [typedPropertiesFeature]
};
// Strict Null Checks
let isNull: null;
let isPoint: Point;
let isPointOrNull: Point | null;
let isProperty: TestProperty;
let isPropertyOrNull: TestProperty | null;
const featureAllNull: Feature<null, null> = {
type: "Feature",
properties: null,
geometry: null
};
const featurePropertyNull: Feature<Point, null> = {
type: "Feature",
properties: null,
geometry: point
};
const featureGeometryNull: Feature<null, TestProperty> = {
type: "Feature",
properties: testProps,
geometry: null
};
featureGeometryNull.properties.foo; // $ExpectType "bar" | "baz"
const featureNoNull: Feature<Point, TestProperty> = {
type: "Feature",
properties: testProps,
geometry: point
};
featureNoNull.geometry.type; // $ExpectType "Point"
const collectionAllNull: FeatureCollection<null, null> = {
type: "FeatureCollection",
features: [featureAllNull],
};
const collectionMaybeNull: FeatureCollection<Point | null, TestProperty | null> = {
type: "FeatureCollection",
features: [featureAllNull, featurePropertyNull, featureGeometryNull, featureNoNull],
};
const collectionPropertyMaybeNull: FeatureCollection<Point, TestProperty | null> = {
type: "FeatureCollection",
features: [featurePropertyNull, featureNoNull],
};
const collectionGeometryMaybeNull: FeatureCollection<Point | null, TestProperty> = {
type: "FeatureCollection",
features: [featureGeometryNull, featureNoNull],
};
collectionGeometryMaybeNull.features[0].geometry; // $ExpectType Point | null
const collectionNoNull: FeatureCollection<Point, TestProperty> = {
type: "FeatureCollection",
features: [featureNoNull],
};
const collectionDefault: FeatureCollection = {
type: "FeatureCollection",
features: []
};
collectionDefault.features[0].geometry; // $ExpectType Geometry
collectionDefault.features[0].properties!.foo; // $ExpectType any
isNull = featureAllNull.geometry;
isPoint = featurePropertyNull.geometry;
isNull = featureAllNull.properties;
isProperty = featureGeometryNull.properties;
isNull = collectionAllNull.features[0].geometry;
isPointOrNull = collectionMaybeNull.features[0].geometry;
isPoint = collectionPropertyMaybeNull.features[0].geometry;
isPointOrNull = collectionGeometryMaybeNull.features[0].geometry;
isPoint = collectionNoNull.features[0].geometry;
isNull = collectionAllNull.features[0].properties;
isPropertyOrNull = collectionMaybeNull.features[0].properties;
isPropertyOrNull = collectionPropertyMaybeNull.features[0].properties;
isProperty = collectionGeometryMaybeNull.features[0].properties;
isProperty = collectionNoNull.features[0].properties;
for (const { geometry } of collectionDefault.features) {
switch (geometry.type) {
case "Point":
isPoint = geometry;
break;
case "GeometryCollection":
for (const child of geometry.geometries) {
if (child.type === "Point") {
isPoint = child;
}
}
break;
}
}
| types/geojson/geojson-tests.ts | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/c2426c074c86b337e01714cb1b5b20cdf359509f | [
0.000924440217204392,
0.00019275638624094427,
0.00016790327208582312,
0.0001739166909828782,
0.00012031405640300363
] |
{
"id": 2,
"code_window": [
"nodeCleanup(cleanupHandler);\n",
"nodeCleanup(cleanupHandler, undefined);\n",
"nodeCleanup(cleanupHandler, stderrMessages);\n",
"nodeCleanup(undefined, stderrMessages);\n",
"nodeCleanup.uninstall();"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep"
],
"after_edit": [
"nodeCleanup(voidHandler);\n"
],
"file_path": "types/node-cleanup/node-cleanup-tests.ts",
"type": "add",
"edit_start_line_idx": 11
} | import nodeCleanup = require('node-cleanup');
function cleanupHandler(exitCode: number | null, signal: string | null): boolean | undefined {
return true;
}
const stderrMessages = { ctrl_C: 'ctrl_c', uncaughtException: 'UncaughtException' };
nodeCleanup();
nodeCleanup(cleanupHandler);
nodeCleanup(cleanupHandler, undefined);
nodeCleanup(cleanupHandler, stderrMessages);
nodeCleanup(undefined, stderrMessages);
nodeCleanup.uninstall();
| types/node-cleanup/node-cleanup-tests.ts | 1 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/c2426c074c86b337e01714cb1b5b20cdf359509f | [
0.7379613518714905,
0.37729084491729736,
0.016620339825749397,
0.37729084491729736,
0.3606705069541931
] |
{
"id": 2,
"code_window": [
"nodeCleanup(cleanupHandler);\n",
"nodeCleanup(cleanupHandler, undefined);\n",
"nodeCleanup(cleanupHandler, stderrMessages);\n",
"nodeCleanup(undefined, stderrMessages);\n",
"nodeCleanup.uninstall();"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep"
],
"after_edit": [
"nodeCleanup(voidHandler);\n"
],
"file_path": "types/node-cleanup/node-cleanup-tests.ts",
"type": "add",
"edit_start_line_idx": 11
} | {
"extends": "dtslint/dt.json",
"rules": {
"adjacent-overload-signatures": false,
"array-type": false,
"arrow-return-shorthand": false,
"ban-types": false,
"callable-types": false,
"comment-format": false,
"dt-header": false,
"npm-naming": false,
"eofline": false,
"export-just-namespace": false,
"import-spacing": false,
"interface-name": false,
"interface-over-type-literal": false,
"jsdoc-format": false,
"max-line-length": false,
"member-access": false,
"new-parens": false,
"no-any-union": false,
"no-boolean-literal-compare": false,
"no-conditional-assignment": false,
"no-consecutive-blank-lines": false,
"no-construct": false,
"no-declare-current-package": false,
"no-duplicate-imports": false,
"no-duplicate-variable": false,
"no-empty-interface": false,
"no-for-in-array": false,
"no-inferrable-types": false,
"no-internal-module": false,
"no-irregular-whitespace": false,
"no-mergeable-namespace": false,
"no-misused-new": false,
"no-namespace": false,
"no-object-literal-type-assertion": false,
"no-padding": false,
"no-redundant-jsdoc": false,
"no-redundant-jsdoc-2": false,
"no-redundant-undefined": false,
"no-reference-import": false,
"no-relative-import-in-test": false,
"no-self-import": false,
"no-single-declare-module": false,
"no-string-throw": false,
"no-unnecessary-callback-wrapper": false,
"no-unnecessary-class": false,
"no-unnecessary-generics": false,
"no-unnecessary-qualifier": false,
"no-unnecessary-type-assertion": false,
"no-useless-files": false,
"no-var-keyword": false,
"no-var-requires": false,
"no-void-expression": false,
"no-trailing-whitespace": false,
"object-literal-key-quotes": false,
"object-literal-shorthand": false,
"one-line": false,
"one-variable-per-declaration": false,
"only-arrow-functions": false,
"prefer-conditional-expression": false,
"prefer-const": false,
"prefer-declare-function": false,
"prefer-for-of": false,
"prefer-method-signature": false,
"prefer-template": false,
"radix": false,
"semicolon": false,
"space-before-function-paren": false,
"space-within-parens": false,
"strict-export-declare-modifiers": false,
"trim-file": false,
"triple-equals": false,
"typedef-whitespace": false,
"unified-signatures": false,
"void-return": false,
"whitespace": false
}
}
| types/fb/tslint.json | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/c2426c074c86b337e01714cb1b5b20cdf359509f | [
0.00017710581596475095,
0.00017067950102500618,
0.0001680991699686274,
0.00016978381609078497,
0.0000026398752197565045
] |
{
"id": 2,
"code_window": [
"nodeCleanup(cleanupHandler);\n",
"nodeCleanup(cleanupHandler, undefined);\n",
"nodeCleanup(cleanupHandler, stderrMessages);\n",
"nodeCleanup(undefined, stderrMessages);\n",
"nodeCleanup.uninstall();"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep"
],
"after_edit": [
"nodeCleanup(voidHandler);\n"
],
"file_path": "types/node-cleanup/node-cleanup-tests.ts",
"type": "add",
"edit_start_line_idx": 11
} | {
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6",
"dom"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"jweixin-tests.ts"
]
} | types/jweixin/tsconfig.json | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/c2426c074c86b337e01714cb1b5b20cdf359509f | [
0.0001725679321680218,
0.0001707721530692652,
0.00016982931992970407,
0.0001699192071100697,
0.0000012703376341960393
] |
{
"id": 2,
"code_window": [
"nodeCleanup(cleanupHandler);\n",
"nodeCleanup(cleanupHandler, undefined);\n",
"nodeCleanup(cleanupHandler, stderrMessages);\n",
"nodeCleanup(undefined, stderrMessages);\n",
"nodeCleanup.uninstall();"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep"
],
"after_edit": [
"nodeCleanup(voidHandler);\n"
],
"file_path": "types/node-cleanup/node-cleanup-tests.ts",
"type": "add",
"edit_start_line_idx": 11
} | // Type definitions for user-event 4.1
// Project: https://github.com/testing-library/user-event
// Definitions by: Wu Haotian <https://github.com/whtsky>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export interface UserOpts {
allAtOnce?: boolean;
delay?: number;
}
declare const userEvent: {
click: (element: Element | Window) => void;
dblClick: (element: Element | Window) => void;
selectOptions: (element: Element | Window, values: string | string[]) => void;
type: (element: Element | Window, text: string, userOpts?: UserOpts) => Promise<void>;
};
export default userEvent;
| types/user-event/index.d.ts | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/c2426c074c86b337e01714cb1b5b20cdf359509f | [
0.0001735605183057487,
0.00017334110452793539,
0.00017312169075012207,
0.00017334110452793539,
2.194137778133154e-7
] |
{
"id": 0,
"code_window": [
"\n",
" this.setupGlobal();\n",
" appEvents.on('show-modal', () => (this.modalOpen = true));\n",
" $rootScope.onAppEvent('openTimepicker', () => (this.timepickerOpen = true));\n",
" }\n",
"\n",
" setupGlobal() {\n",
" this.bind(['?', 'h'], this.showHelpModal);\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" $rootScope.onAppEvent('escTimepicker', () => {\n",
" if (!this.timepickerOpen) {\n",
" this.timepickerOpen = true;\n",
" } else {\n",
" this.timepickerOpen = false;\n",
" }\n",
" });\n"
],
"file_path": "public/app/core/services/keybindingSrv.ts",
"type": "replace",
"edit_start_line_idx": 25
} | import _ from 'lodash';
import angular from 'angular';
import moment from 'moment';
import * as rangeUtil from 'app/core/utils/rangeutil';
export class TimePickerCtrl {
static tooltipFormat = 'MMM D, YYYY HH:mm:ss';
static defaults = {
time_options: ['5m', '15m', '1h', '6h', '12h', '24h', '2d', '7d', '30d'],
refresh_intervals: ['5s', '10s', '30s', '1m', '5m', '15m', '30m', '1h', '2h', '1d'],
};
dashboard: any;
panel: any;
absolute: any;
timeRaw: any;
editTimeRaw: any;
tooltip: string;
rangeString: string;
timeOptions: any;
refresh: any;
isUtc: boolean;
firstDayOfWeek: number;
closeDropdown: any;
isOpen: boolean;
/** @ngInject */
constructor(private $scope, private $rootScope, private timeSrv) {
this.$scope.ctrl = this;
$rootScope.onAppEvent('shift-time-forward', () => this.move(1), $scope);
$rootScope.onAppEvent('shift-time-backward', () => this.move(-1), $scope);
$rootScope.onAppEvent('refresh', this.onRefresh.bind(this), $scope);
$rootScope.onAppEvent('closeTimepicker', this.openDropdown.bind(this), $scope);
// init options
this.panel = this.dashboard.timepicker;
_.defaults(this.panel, TimePickerCtrl.defaults);
this.firstDayOfWeek = moment.localeData().firstDayOfWeek();
// init time stuff
this.onRefresh();
}
onRefresh() {
var time = angular.copy(this.timeSrv.timeRange());
var timeRaw = angular.copy(time.raw);
if (!this.dashboard.isTimezoneUtc()) {
time.from.local();
time.to.local();
if (moment.isMoment(timeRaw.from)) {
timeRaw.from.local();
}
if (moment.isMoment(timeRaw.to)) {
timeRaw.to.local();
}
this.isUtc = false;
} else {
this.isUtc = true;
}
this.rangeString = rangeUtil.describeTimeRange(timeRaw);
this.absolute = { fromJs: time.from.toDate(), toJs: time.to.toDate() };
this.tooltip = this.dashboard.formatDate(time.from) + ' <br>to<br>';
this.tooltip += this.dashboard.formatDate(time.to);
this.timeRaw = timeRaw;
}
zoom(factor) {
this.$rootScope.appEvent('zoom-out', 2);
}
move(direction) {
var range = this.timeSrv.timeRange();
var timespan = (range.to.valueOf() - range.from.valueOf()) / 2;
var to, from;
if (direction === -1) {
to = range.to.valueOf() - timespan;
from = range.from.valueOf() - timespan;
} else if (direction === 1) {
to = range.to.valueOf() + timespan;
from = range.from.valueOf() + timespan;
if (to > Date.now() && range.to < Date.now()) {
to = Date.now();
from = range.from.valueOf();
}
} else {
to = range.to.valueOf();
from = range.from.valueOf();
}
this.timeSrv.setTime({ from: moment.utc(from), to: moment.utc(to) });
}
openDropdown() {
if (this.isOpen) {
this.isOpen = false;
return;
}
this.$rootScope.appEvent('openTimepicker');
this.onRefresh();
this.editTimeRaw = this.timeRaw;
this.timeOptions = rangeUtil.getRelativeTimesList(this.panel, this.rangeString);
this.refresh = {
value: this.dashboard.refresh,
options: _.map(this.panel.refresh_intervals, (interval: any) => {
return { text: interval, value: interval };
}),
};
this.refresh.options.unshift({ text: 'off' });
this.isOpen = true;
}
applyCustom() {
if (this.refresh.value !== this.dashboard.refresh) {
this.timeSrv.setAutoRefresh(this.refresh.value);
}
this.timeSrv.setTime(this.editTimeRaw);
this.isOpen = false;
}
absoluteFromChanged() {
this.editTimeRaw.from = this.getAbsoluteMomentForTimezone(this.absolute.fromJs);
}
absoluteToChanged() {
this.editTimeRaw.to = this.getAbsoluteMomentForTimezone(this.absolute.toJs);
}
getAbsoluteMomentForTimezone(jsDate) {
return this.dashboard.isTimezoneUtc() ? moment(jsDate).utc() : moment(jsDate);
}
setRelativeFilter(timespan) {
var range = { from: timespan.from, to: timespan.to };
if (this.panel.nowDelay && range.to === 'now') {
range.to = 'now-' + this.panel.nowDelay;
}
this.timeSrv.setTime(range);
this.isOpen = false;
}
}
export function settingsDirective() {
return {
restrict: 'E',
templateUrl: 'public/app/features/dashboard/timepicker/settings.html',
controller: TimePickerCtrl,
bindToController: true,
controllerAs: 'ctrl',
scope: {
dashboard: '=',
},
};
}
export function timePickerDirective() {
return {
restrict: 'E',
templateUrl: 'public/app/features/dashboard/timepicker/timepicker.html',
controller: TimePickerCtrl,
bindToController: true,
controllerAs: 'ctrl',
scope: {
dashboard: '=',
},
};
}
angular.module('grafana.directives').directive('gfTimePickerSettings', settingsDirective);
angular.module('grafana.directives').directive('gfTimePicker', timePickerDirective);
import { inputDateDirective } from './input_date';
angular.module('grafana.directives').directive('inputDatetime', inputDateDirective);
| public/app/features/dashboard/timepicker/timepicker.ts | 1 | https://github.com/grafana/grafana/commit/98e1404fed0a1cab9cdc6f7404d805459f374f48 | [
0.0013285333989188075,
0.0003786581219173968,
0.00016689561016391963,
0.0001716700498946011,
0.00037678718217648566
] |
{
"id": 0,
"code_window": [
"\n",
" this.setupGlobal();\n",
" appEvents.on('show-modal', () => (this.modalOpen = true));\n",
" $rootScope.onAppEvent('openTimepicker', () => (this.timepickerOpen = true));\n",
" }\n",
"\n",
" setupGlobal() {\n",
" this.bind(['?', 'h'], this.showHelpModal);\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" $rootScope.onAppEvent('escTimepicker', () => {\n",
" if (!this.timepickerOpen) {\n",
" this.timepickerOpen = true;\n",
" } else {\n",
" this.timepickerOpen = false;\n",
" }\n",
" });\n"
],
"file_path": "public/app/core/services/keybindingSrv.ts",
"type": "replace",
"edit_start_line_idx": 25
} | package plugins
import (
"context"
"path/filepath"
"testing"
"github.com/grafana/grafana/pkg/setting"
. "github.com/smartystreets/goconvey/convey"
"gopkg.in/ini.v1"
)
func TestPluginScans(t *testing.T) {
Convey("When scaning for plugins", t, func() {
setting.StaticRootPath, _ = filepath.Abs("../../public/")
setting.Cfg = ini.Empty()
err := initPlugins(context.Background())
So(err, ShouldBeNil)
So(len(DataSources), ShouldBeGreaterThan, 1)
So(len(Panels), ShouldBeGreaterThan, 1)
Convey("Should set module automatically", func() {
So(DataSources["graphite"].Module, ShouldEqual, "app/plugins/datasource/graphite/module")
})
})
Convey("When reading app plugin definition", t, func() {
setting.Cfg = ini.Empty()
sec, _ := setting.Cfg.NewSection("plugin.nginx-app")
sec.NewKey("path", "../../tests/test-app")
err := initPlugins(context.Background())
So(err, ShouldBeNil)
So(len(Apps), ShouldBeGreaterThan, 0)
So(Apps["test-app"].Info.Logos.Large, ShouldEqual, "public/plugins/test-app/img/logo_large.png")
So(Apps["test-app"].Info.Screenshots[1].Path, ShouldEqual, "public/plugins/test-app/img/screenshot2.png")
})
}
| pkg/plugins/plugins_test.go | 0 | https://github.com/grafana/grafana/commit/98e1404fed0a1cab9cdc6f7404d805459f374f48 | [
0.0001772984251147136,
0.00017423229292035103,
0.0001715743273962289,
0.0001730817457428202,
0.0000024884348022169434
] |
{
"id": 0,
"code_window": [
"\n",
" this.setupGlobal();\n",
" appEvents.on('show-modal', () => (this.modalOpen = true));\n",
" $rootScope.onAppEvent('openTimepicker', () => (this.timepickerOpen = true));\n",
" }\n",
"\n",
" setupGlobal() {\n",
" this.bind(['?', 'h'], this.showHelpModal);\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" $rootScope.onAppEvent('escTimepicker', () => {\n",
" if (!this.timepickerOpen) {\n",
" this.timepickerOpen = true;\n",
" } else {\n",
" this.timepickerOpen = false;\n",
" }\n",
" });\n"
],
"file_path": "public/app/core/services/keybindingSrv.ts",
"type": "replace",
"edit_start_line_idx": 25
} | #! /usr/bin/env bash
# chkconfig: 2345 80 05
# description: Grafana web server & backend
# processname: grafana
# config: /etc/grafana/grafana.ini
# pidfile: /var/run/grafana.pid
### BEGIN INIT INFO
# Provides: grafana
# Required-Start: $all
# Required-Stop: $remote_fs $syslog
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Start grafana at boot time
### END INIT INFO
# tested on
# 1. New lsb that define start-stop-daemon
# 3. Centos with initscripts package installed
PATH=/bin:/usr/bin:/sbin:/usr/sbin
NAME=grafana-server
DESC="Grafana Server"
GRAFANA_USER=grafana
GRAFANA_GROUP=grafana
GRAFANA_HOME=/usr/share/grafana
CONF_DIR=/etc/grafana
WORK_DIR=$GRAFANA_HOME
DATA_DIR=/var/lib/grafana
PLUGINS_DIR=/var/lib/grafana/plugins
LOG_DIR=/var/log/grafana
CONF_FILE=$CONF_DIR/grafana.ini
PROVISIONING_CFG_DIR=$CONF_DIR/provisioning
MAX_OPEN_FILES=10000
PID_FILE=/var/run/$NAME.pid
DAEMON=/usr/sbin/$NAME
if [ ! -x $DAEMON ]; then
echo "Program not installed or not executable"
exit 5
fi
#
# init.d / servicectl compatibility (openSUSE)
#
if [ -f /etc/rc.status ]; then
. /etc/rc.status
rc_reset
fi
#
# Source function library.
#
if [ -f /etc/rc.d/init.d/functions ]; then
. /etc/rc.d/init.d/functions
fi
# overwrite settings from default file
[ -e /etc/sysconfig/$NAME ] && . /etc/sysconfig/$NAME
DAEMON_OPTS="--pidfile=${PID_FILE} --config=${CONF_FILE} cfg:default.paths.provisioning=$PROVISIONING_CFG_DIR cfg:default.paths.data=${DATA_DIR} cfg:default.paths.logs=${LOG_DIR} cfg:default.paths.plugins=${PLUGINS_DIR}"
function isRunning() {
status -p $PID_FILE $NAME > /dev/null 2>&1
}
function checkUser() {
if [ `id -u` -ne 0 ]; then
echo "You need root privileges to run this script"
exit 4
fi
}
case "$1" in
start)
checkUser
isRunning
if [ $? -eq 0 ]; then
echo "Already running."
exit 0
fi
# Prepare environment
mkdir -p "$LOG_DIR" "$DATA_DIR" && chown "$GRAFANA_USER":"$GRAFANA_GROUP" "$LOG_DIR" "$DATA_DIR"
touch "$PID_FILE" && chown "$GRAFANA_USER":"$GRAFANA_GROUP" "$PID_FILE"
if [ -n "$MAX_OPEN_FILES" ]; then
ulimit -n $MAX_OPEN_FILES
fi
# Start Daemon
cd $GRAFANA_HOME
action $"Starting $DESC: ..." su -s /bin/sh -c "nohup ${DAEMON} ${DAEMON_OPTS} >> /dev/null 3>&1 &" $GRAFANA_USER 2> /dev/null
return=$?
if [ $return -eq 0 ]
then
sleep 1
# check if pid file has been written to
if ! [[ -s $PID_FILE ]]; then
echo "FAILED"
exit 1
fi
i=0
timeout=10
# Wait for the process to be properly started before exiting
until { cat "$PID_FILE" | xargs kill -0; } >/dev/null 2>&1
do
sleep 1
i=$(($i + 1))
if [ $i -gt $timeout ]; then
echo "FAILED"
exit 1
fi
done
fi
exit $return
;;
stop)
checkUser
echo -n "Stopping $DESC: ..."
if [ -f "$PID_FILE" ]; then
killproc -p $PID_FILE -d 20 $NAME
if [ $? -eq 1 ]; then
echo "$DESC is not running but pid file exists, cleaning up"
elif [ $? -eq 3 ]; then
PID="`cat $PID_FILE`"
echo "Failed to stop $DESC (pid $PID)"
exit 1
fi
rm -f "$PID_FILE"
echo ""
exit 0
else
echo "(not running)"
fi
exit 0
;;
status)
status -p $PID_FILE $NAME
exit $?
;;
restart|force-reload)
if [ -f "$PID_FILE" ]; then
$0 stop
sleep 1
fi
$0 start
;;
*)
echo "Usage: $0 {start|stop|restart|force-reload|status}"
exit 3
;;
esac
| packaging/rpm/init.d/grafana-server | 0 | https://github.com/grafana/grafana/commit/98e1404fed0a1cab9cdc6f7404d805459f374f48 | [
0.00018465984612703323,
0.00017422012751922011,
0.00016005516226869076,
0.00017493370978627354,
0.000005114030045660911
] |
{
"id": 0,
"code_window": [
"\n",
" this.setupGlobal();\n",
" appEvents.on('show-modal', () => (this.modalOpen = true));\n",
" $rootScope.onAppEvent('openTimepicker', () => (this.timepickerOpen = true));\n",
" }\n",
"\n",
" setupGlobal() {\n",
" this.bind(['?', 'h'], this.showHelpModal);\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" $rootScope.onAppEvent('escTimepicker', () => {\n",
" if (!this.timepickerOpen) {\n",
" this.timepickerOpen = true;\n",
" } else {\n",
" this.timepickerOpen = false;\n",
" }\n",
" });\n"
],
"file_path": "public/app/core/services/keybindingSrv.ts",
"type": "replace",
"edit_start_line_idx": 25
} | package cp
var cp1255 *charsetMap = &charsetMap{
sb: [256]rune{
0x0000, //NULL
0x0001, //START OF HEADING
0x0002, //START OF TEXT
0x0003, //END OF TEXT
0x0004, //END OF TRANSMISSION
0x0005, //ENQUIRY
0x0006, //ACKNOWLEDGE
0x0007, //BELL
0x0008, //BACKSPACE
0x0009, //HORIZONTAL TABULATION
0x000A, //LINE FEED
0x000B, //VERTICAL TABULATION
0x000C, //FORM FEED
0x000D, //CARRIAGE RETURN
0x000E, //SHIFT OUT
0x000F, //SHIFT IN
0x0010, //DATA LINK ESCAPE
0x0011, //DEVICE CONTROL ONE
0x0012, //DEVICE CONTROL TWO
0x0013, //DEVICE CONTROL THREE
0x0014, //DEVICE CONTROL FOUR
0x0015, //NEGATIVE ACKNOWLEDGE
0x0016, //SYNCHRONOUS IDLE
0x0017, //END OF TRANSMISSION BLOCK
0x0018, //CANCEL
0x0019, //END OF MEDIUM
0x001A, //SUBSTITUTE
0x001B, //ESCAPE
0x001C, //FILE SEPARATOR
0x001D, //GROUP SEPARATOR
0x001E, //RECORD SEPARATOR
0x001F, //UNIT SEPARATOR
0x0020, //SPACE
0x0021, //EXCLAMATION MARK
0x0022, //QUOTATION MARK
0x0023, //NUMBER SIGN
0x0024, //DOLLAR SIGN
0x0025, //PERCENT SIGN
0x0026, //AMPERSAND
0x0027, //APOSTROPHE
0x0028, //LEFT PARENTHESIS
0x0029, //RIGHT PARENTHESIS
0x002A, //ASTERISK
0x002B, //PLUS SIGN
0x002C, //COMMA
0x002D, //HYPHEN-MINUS
0x002E, //FULL STOP
0x002F, //SOLIDUS
0x0030, //DIGIT ZERO
0x0031, //DIGIT ONE
0x0032, //DIGIT TWO
0x0033, //DIGIT THREE
0x0034, //DIGIT FOUR
0x0035, //DIGIT FIVE
0x0036, //DIGIT SIX
0x0037, //DIGIT SEVEN
0x0038, //DIGIT EIGHT
0x0039, //DIGIT NINE
0x003A, //COLON
0x003B, //SEMICOLON
0x003C, //LESS-THAN SIGN
0x003D, //EQUALS SIGN
0x003E, //GREATER-THAN SIGN
0x003F, //QUESTION MARK
0x0040, //COMMERCIAL AT
0x0041, //LATIN CAPITAL LETTER A
0x0042, //LATIN CAPITAL LETTER B
0x0043, //LATIN CAPITAL LETTER C
0x0044, //LATIN CAPITAL LETTER D
0x0045, //LATIN CAPITAL LETTER E
0x0046, //LATIN CAPITAL LETTER F
0x0047, //LATIN CAPITAL LETTER G
0x0048, //LATIN CAPITAL LETTER H
0x0049, //LATIN CAPITAL LETTER I
0x004A, //LATIN CAPITAL LETTER J
0x004B, //LATIN CAPITAL LETTER K
0x004C, //LATIN CAPITAL LETTER L
0x004D, //LATIN CAPITAL LETTER M
0x004E, //LATIN CAPITAL LETTER N
0x004F, //LATIN CAPITAL LETTER O
0x0050, //LATIN CAPITAL LETTER P
0x0051, //LATIN CAPITAL LETTER Q
0x0052, //LATIN CAPITAL LETTER R
0x0053, //LATIN CAPITAL LETTER S
0x0054, //LATIN CAPITAL LETTER T
0x0055, //LATIN CAPITAL LETTER U
0x0056, //LATIN CAPITAL LETTER V
0x0057, //LATIN CAPITAL LETTER W
0x0058, //LATIN CAPITAL LETTER X
0x0059, //LATIN CAPITAL LETTER Y
0x005A, //LATIN CAPITAL LETTER Z
0x005B, //LEFT SQUARE BRACKET
0x005C, //REVERSE SOLIDUS
0x005D, //RIGHT SQUARE BRACKET
0x005E, //CIRCUMFLEX ACCENT
0x005F, //LOW LINE
0x0060, //GRAVE ACCENT
0x0061, //LATIN SMALL LETTER A
0x0062, //LATIN SMALL LETTER B
0x0063, //LATIN SMALL LETTER C
0x0064, //LATIN SMALL LETTER D
0x0065, //LATIN SMALL LETTER E
0x0066, //LATIN SMALL LETTER F
0x0067, //LATIN SMALL LETTER G
0x0068, //LATIN SMALL LETTER H
0x0069, //LATIN SMALL LETTER I
0x006A, //LATIN SMALL LETTER J
0x006B, //LATIN SMALL LETTER K
0x006C, //LATIN SMALL LETTER L
0x006D, //LATIN SMALL LETTER M
0x006E, //LATIN SMALL LETTER N
0x006F, //LATIN SMALL LETTER O
0x0070, //LATIN SMALL LETTER P
0x0071, //LATIN SMALL LETTER Q
0x0072, //LATIN SMALL LETTER R
0x0073, //LATIN SMALL LETTER S
0x0074, //LATIN SMALL LETTER T
0x0075, //LATIN SMALL LETTER U
0x0076, //LATIN SMALL LETTER V
0x0077, //LATIN SMALL LETTER W
0x0078, //LATIN SMALL LETTER X
0x0079, //LATIN SMALL LETTER Y
0x007A, //LATIN SMALL LETTER Z
0x007B, //LEFT CURLY BRACKET
0x007C, //VERTICAL LINE
0x007D, //RIGHT CURLY BRACKET
0x007E, //TILDE
0x007F, //DELETE
0x20AC, //EURO SIGN
0xFFFD, //UNDEFINED
0x201A, //SINGLE LOW-9 QUOTATION MARK
0x0192, //LATIN SMALL LETTER F WITH HOOK
0x201E, //DOUBLE LOW-9 QUOTATION MARK
0x2026, //HORIZONTAL ELLIPSIS
0x2020, //DAGGER
0x2021, //DOUBLE DAGGER
0x02C6, //MODIFIER LETTER CIRCUMFLEX ACCENT
0x2030, //PER MILLE SIGN
0xFFFD, //UNDEFINED
0x2039, //SINGLE LEFT-POINTING ANGLE QUOTATION MARK
0xFFFD, //UNDEFINED
0xFFFD, //UNDEFINED
0xFFFD, //UNDEFINED
0xFFFD, //UNDEFINED
0xFFFD, //UNDEFINED
0x2018, //LEFT SINGLE QUOTATION MARK
0x2019, //RIGHT SINGLE QUOTATION MARK
0x201C, //LEFT DOUBLE QUOTATION MARK
0x201D, //RIGHT DOUBLE QUOTATION MARK
0x2022, //BULLET
0x2013, //EN DASH
0x2014, //EM DASH
0x02DC, //SMALL TILDE
0x2122, //TRADE MARK SIGN
0xFFFD, //UNDEFINED
0x203A, //SINGLE RIGHT-POINTING ANGLE QUOTATION MARK
0xFFFD, //UNDEFINED
0xFFFD, //UNDEFINED
0xFFFD, //UNDEFINED
0xFFFD, //UNDEFINED
0x00A0, //NO-BREAK SPACE
0x00A1, //INVERTED EXCLAMATION MARK
0x00A2, //CENT SIGN
0x00A3, //POUND SIGN
0x20AA, //NEW SHEQEL SIGN
0x00A5, //YEN SIGN
0x00A6, //BROKEN BAR
0x00A7, //SECTION SIGN
0x00A8, //DIAERESIS
0x00A9, //COPYRIGHT SIGN
0x00D7, //MULTIPLICATION SIGN
0x00AB, //LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
0x00AC, //NOT SIGN
0x00AD, //SOFT HYPHEN
0x00AE, //REGISTERED SIGN
0x00AF, //MACRON
0x00B0, //DEGREE SIGN
0x00B1, //PLUS-MINUS SIGN
0x00B2, //SUPERSCRIPT TWO
0x00B3, //SUPERSCRIPT THREE
0x00B4, //ACUTE ACCENT
0x00B5, //MICRO SIGN
0x00B6, //PILCROW SIGN
0x00B7, //MIDDLE DOT
0x00B8, //CEDILLA
0x00B9, //SUPERSCRIPT ONE
0x00F7, //DIVISION SIGN
0x00BB, //RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
0x00BC, //VULGAR FRACTION ONE QUARTER
0x00BD, //VULGAR FRACTION ONE HALF
0x00BE, //VULGAR FRACTION THREE QUARTERS
0x00BF, //INVERTED QUESTION MARK
0x05B0, //HEBREW POINT SHEVA
0x05B1, //HEBREW POINT HATAF SEGOL
0x05B2, //HEBREW POINT HATAF PATAH
0x05B3, //HEBREW POINT HATAF QAMATS
0x05B4, //HEBREW POINT HIRIQ
0x05B5, //HEBREW POINT TSERE
0x05B6, //HEBREW POINT SEGOL
0x05B7, //HEBREW POINT PATAH
0x05B8, //HEBREW POINT QAMATS
0x05B9, //HEBREW POINT HOLAM
0xFFFD, //UNDEFINED
0x05BB, //HEBREW POINT QUBUTS
0x05BC, //HEBREW POINT DAGESH OR MAPIQ
0x05BD, //HEBREW POINT METEG
0x05BE, //HEBREW PUNCTUATION MAQAF
0x05BF, //HEBREW POINT RAFE
0x05C0, //HEBREW PUNCTUATION PASEQ
0x05C1, //HEBREW POINT SHIN DOT
0x05C2, //HEBREW POINT SIN DOT
0x05C3, //HEBREW PUNCTUATION SOF PASUQ
0x05F0, //HEBREW LIGATURE YIDDISH DOUBLE VAV
0x05F1, //HEBREW LIGATURE YIDDISH VAV YOD
0x05F2, //HEBREW LIGATURE YIDDISH DOUBLE YOD
0x05F3, //HEBREW PUNCTUATION GERESH
0x05F4, //HEBREW PUNCTUATION GERSHAYIM
0xFFFD, //UNDEFINED
0xFFFD, //UNDEFINED
0xFFFD, //UNDEFINED
0xFFFD, //UNDEFINED
0xFFFD, //UNDEFINED
0xFFFD, //UNDEFINED
0xFFFD, //UNDEFINED
0x05D0, //HEBREW LETTER ALEF
0x05D1, //HEBREW LETTER BET
0x05D2, //HEBREW LETTER GIMEL
0x05D3, //HEBREW LETTER DALET
0x05D4, //HEBREW LETTER HE
0x05D5, //HEBREW LETTER VAV
0x05D6, //HEBREW LETTER ZAYIN
0x05D7, //HEBREW LETTER HET
0x05D8, //HEBREW LETTER TET
0x05D9, //HEBREW LETTER YOD
0x05DA, //HEBREW LETTER FINAL KAF
0x05DB, //HEBREW LETTER KAF
0x05DC, //HEBREW LETTER LAMED
0x05DD, //HEBREW LETTER FINAL MEM
0x05DE, //HEBREW LETTER MEM
0x05DF, //HEBREW LETTER FINAL NUN
0x05E0, //HEBREW LETTER NUN
0x05E1, //HEBREW LETTER SAMEKH
0x05E2, //HEBREW LETTER AYIN
0x05E3, //HEBREW LETTER FINAL PE
0x05E4, //HEBREW LETTER PE
0x05E5, //HEBREW LETTER FINAL TSADI
0x05E6, //HEBREW LETTER TSADI
0x05E7, //HEBREW LETTER QOF
0x05E8, //HEBREW LETTER RESH
0x05E9, //HEBREW LETTER SHIN
0x05EA, //HEBREW LETTER TAV
0xFFFD, //UNDEFINED
0xFFFD, //UNDEFINED
0x200E, //LEFT-TO-RIGHT MARK
0x200F, //RIGHT-TO-LEFT MARK
0xFFFD, //UNDEFINED
},
}
| vendor/github.com/denisenkom/go-mssqldb/internal/cp/cp1255.go | 0 | https://github.com/grafana/grafana/commit/98e1404fed0a1cab9cdc6f7404d805459f374f48 | [
0.0001761285529937595,
0.00017042251420207322,
0.00016434176359325647,
0.00017031955940183252,
0.0000025932752123480896
] |
{
"id": 1,
"code_window": [
" this.timeSrv.setTime({ from: moment.utc(from), to: moment.utc(to) });\n",
" }\n",
"\n",
" openDropdown() {\n",
" if (this.isOpen) {\n",
" this.isOpen = false;\n",
" return;\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" this.$rootScope.appEvent('escTimepicker');\n"
],
"file_path": "public/app/features/dashboard/timepicker/timepicker.ts",
"type": "add",
"edit_start_line_idx": 98
} | import _ from 'lodash';
import angular from 'angular';
import moment from 'moment';
import * as rangeUtil from 'app/core/utils/rangeutil';
export class TimePickerCtrl {
static tooltipFormat = 'MMM D, YYYY HH:mm:ss';
static defaults = {
time_options: ['5m', '15m', '1h', '6h', '12h', '24h', '2d', '7d', '30d'],
refresh_intervals: ['5s', '10s', '30s', '1m', '5m', '15m', '30m', '1h', '2h', '1d'],
};
dashboard: any;
panel: any;
absolute: any;
timeRaw: any;
editTimeRaw: any;
tooltip: string;
rangeString: string;
timeOptions: any;
refresh: any;
isUtc: boolean;
firstDayOfWeek: number;
closeDropdown: any;
isOpen: boolean;
/** @ngInject */
constructor(private $scope, private $rootScope, private timeSrv) {
this.$scope.ctrl = this;
$rootScope.onAppEvent('shift-time-forward', () => this.move(1), $scope);
$rootScope.onAppEvent('shift-time-backward', () => this.move(-1), $scope);
$rootScope.onAppEvent('refresh', this.onRefresh.bind(this), $scope);
$rootScope.onAppEvent('closeTimepicker', this.openDropdown.bind(this), $scope);
// init options
this.panel = this.dashboard.timepicker;
_.defaults(this.panel, TimePickerCtrl.defaults);
this.firstDayOfWeek = moment.localeData().firstDayOfWeek();
// init time stuff
this.onRefresh();
}
onRefresh() {
var time = angular.copy(this.timeSrv.timeRange());
var timeRaw = angular.copy(time.raw);
if (!this.dashboard.isTimezoneUtc()) {
time.from.local();
time.to.local();
if (moment.isMoment(timeRaw.from)) {
timeRaw.from.local();
}
if (moment.isMoment(timeRaw.to)) {
timeRaw.to.local();
}
this.isUtc = false;
} else {
this.isUtc = true;
}
this.rangeString = rangeUtil.describeTimeRange(timeRaw);
this.absolute = { fromJs: time.from.toDate(), toJs: time.to.toDate() };
this.tooltip = this.dashboard.formatDate(time.from) + ' <br>to<br>';
this.tooltip += this.dashboard.formatDate(time.to);
this.timeRaw = timeRaw;
}
zoom(factor) {
this.$rootScope.appEvent('zoom-out', 2);
}
move(direction) {
var range = this.timeSrv.timeRange();
var timespan = (range.to.valueOf() - range.from.valueOf()) / 2;
var to, from;
if (direction === -1) {
to = range.to.valueOf() - timespan;
from = range.from.valueOf() - timespan;
} else if (direction === 1) {
to = range.to.valueOf() + timespan;
from = range.from.valueOf() + timespan;
if (to > Date.now() && range.to < Date.now()) {
to = Date.now();
from = range.from.valueOf();
}
} else {
to = range.to.valueOf();
from = range.from.valueOf();
}
this.timeSrv.setTime({ from: moment.utc(from), to: moment.utc(to) });
}
openDropdown() {
if (this.isOpen) {
this.isOpen = false;
return;
}
this.$rootScope.appEvent('openTimepicker');
this.onRefresh();
this.editTimeRaw = this.timeRaw;
this.timeOptions = rangeUtil.getRelativeTimesList(this.panel, this.rangeString);
this.refresh = {
value: this.dashboard.refresh,
options: _.map(this.panel.refresh_intervals, (interval: any) => {
return { text: interval, value: interval };
}),
};
this.refresh.options.unshift({ text: 'off' });
this.isOpen = true;
}
applyCustom() {
if (this.refresh.value !== this.dashboard.refresh) {
this.timeSrv.setAutoRefresh(this.refresh.value);
}
this.timeSrv.setTime(this.editTimeRaw);
this.isOpen = false;
}
absoluteFromChanged() {
this.editTimeRaw.from = this.getAbsoluteMomentForTimezone(this.absolute.fromJs);
}
absoluteToChanged() {
this.editTimeRaw.to = this.getAbsoluteMomentForTimezone(this.absolute.toJs);
}
getAbsoluteMomentForTimezone(jsDate) {
return this.dashboard.isTimezoneUtc() ? moment(jsDate).utc() : moment(jsDate);
}
setRelativeFilter(timespan) {
var range = { from: timespan.from, to: timespan.to };
if (this.panel.nowDelay && range.to === 'now') {
range.to = 'now-' + this.panel.nowDelay;
}
this.timeSrv.setTime(range);
this.isOpen = false;
}
}
export function settingsDirective() {
return {
restrict: 'E',
templateUrl: 'public/app/features/dashboard/timepicker/settings.html',
controller: TimePickerCtrl,
bindToController: true,
controllerAs: 'ctrl',
scope: {
dashboard: '=',
},
};
}
export function timePickerDirective() {
return {
restrict: 'E',
templateUrl: 'public/app/features/dashboard/timepicker/timepicker.html',
controller: TimePickerCtrl,
bindToController: true,
controllerAs: 'ctrl',
scope: {
dashboard: '=',
},
};
}
angular.module('grafana.directives').directive('gfTimePickerSettings', settingsDirective);
angular.module('grafana.directives').directive('gfTimePicker', timePickerDirective);
import { inputDateDirective } from './input_date';
angular.module('grafana.directives').directive('inputDatetime', inputDateDirective);
| public/app/features/dashboard/timepicker/timepicker.ts | 1 | https://github.com/grafana/grafana/commit/98e1404fed0a1cab9cdc6f7404d805459f374f48 | [
0.9989564418792725,
0.1097140908241272,
0.00016741279978305101,
0.0009503283072263002,
0.3029869794845581
] |
{
"id": 1,
"code_window": [
" this.timeSrv.setTime({ from: moment.utc(from), to: moment.utc(to) });\n",
" }\n",
"\n",
" openDropdown() {\n",
" if (this.isOpen) {\n",
" this.isOpen = false;\n",
" return;\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" this.$rootScope.appEvent('escTimepicker');\n"
],
"file_path": "public/app/features/dashboard/timepicker/timepicker.ts",
"type": "add",
"edit_start_line_idx": 98
} | // Copyright 2014 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.
package hpack
import (
"io"
)
const (
uint32Max = ^uint32(0)
initialHeaderTableSize = 4096
)
type Encoder struct {
dynTab dynamicTable
// minSize is the minimum table size set by
// SetMaxDynamicTableSize after the previous Header Table Size
// Update.
minSize uint32
// maxSizeLimit is the maximum table size this encoder
// supports. This will protect the encoder from too large
// size.
maxSizeLimit uint32
// tableSizeUpdate indicates whether "Header Table Size
// Update" is required.
tableSizeUpdate bool
w io.Writer
buf []byte
}
// NewEncoder returns a new Encoder which performs HPACK encoding. An
// encoded data is written to w.
func NewEncoder(w io.Writer) *Encoder {
e := &Encoder{
minSize: uint32Max,
maxSizeLimit: initialHeaderTableSize,
tableSizeUpdate: false,
w: w,
}
e.dynTab.table.init()
e.dynTab.setMaxSize(initialHeaderTableSize)
return e
}
// WriteField encodes f into a single Write to e's underlying Writer.
// This function may also produce bytes for "Header Table Size Update"
// if necessary. If produced, it is done before encoding f.
func (e *Encoder) WriteField(f HeaderField) error {
e.buf = e.buf[:0]
if e.tableSizeUpdate {
e.tableSizeUpdate = false
if e.minSize < e.dynTab.maxSize {
e.buf = appendTableSize(e.buf, e.minSize)
}
e.minSize = uint32Max
e.buf = appendTableSize(e.buf, e.dynTab.maxSize)
}
idx, nameValueMatch := e.searchTable(f)
if nameValueMatch {
e.buf = appendIndexed(e.buf, idx)
} else {
indexing := e.shouldIndex(f)
if indexing {
e.dynTab.add(f)
}
if idx == 0 {
e.buf = appendNewName(e.buf, f, indexing)
} else {
e.buf = appendIndexedName(e.buf, f, idx, indexing)
}
}
n, err := e.w.Write(e.buf)
if err == nil && n != len(e.buf) {
err = io.ErrShortWrite
}
return err
}
// searchTable searches f in both stable and dynamic header tables.
// The static header table is searched first. Only when there is no
// exact match for both name and value, the dynamic header table is
// then searched. If there is no match, i is 0. If both name and value
// match, i is the matched index and nameValueMatch becomes true. If
// only name matches, i points to that index and nameValueMatch
// becomes false.
func (e *Encoder) searchTable(f HeaderField) (i uint64, nameValueMatch bool) {
i, nameValueMatch = staticTable.search(f)
if nameValueMatch {
return i, true
}
j, nameValueMatch := e.dynTab.table.search(f)
if nameValueMatch || (i == 0 && j != 0) {
return j + uint64(staticTable.len()), nameValueMatch
}
return i, false
}
// SetMaxDynamicTableSize changes the dynamic header table size to v.
// The actual size is bounded by the value passed to
// SetMaxDynamicTableSizeLimit.
func (e *Encoder) SetMaxDynamicTableSize(v uint32) {
if v > e.maxSizeLimit {
v = e.maxSizeLimit
}
if v < e.minSize {
e.minSize = v
}
e.tableSizeUpdate = true
e.dynTab.setMaxSize(v)
}
// SetMaxDynamicTableSizeLimit changes the maximum value that can be
// specified in SetMaxDynamicTableSize to v. By default, it is set to
// 4096, which is the same size of the default dynamic header table
// size described in HPACK specification. If the current maximum
// dynamic header table size is strictly greater than v, "Header Table
// Size Update" will be done in the next WriteField call and the
// maximum dynamic header table size is truncated to v.
func (e *Encoder) SetMaxDynamicTableSizeLimit(v uint32) {
e.maxSizeLimit = v
if e.dynTab.maxSize > v {
e.tableSizeUpdate = true
e.dynTab.setMaxSize(v)
}
}
// shouldIndex reports whether f should be indexed.
func (e *Encoder) shouldIndex(f HeaderField) bool {
return !f.Sensitive && f.Size() <= e.dynTab.maxSize
}
// appendIndexed appends index i, as encoded in "Indexed Header Field"
// representation, to dst and returns the extended buffer.
func appendIndexed(dst []byte, i uint64) []byte {
first := len(dst)
dst = appendVarInt(dst, 7, i)
dst[first] |= 0x80
return dst
}
// appendNewName appends f, as encoded in one of "Literal Header field
// - New Name" representation variants, to dst and returns the
// extended buffer.
//
// If f.Sensitive is true, "Never Indexed" representation is used. If
// f.Sensitive is false and indexing is true, "Inremental Indexing"
// representation is used.
func appendNewName(dst []byte, f HeaderField, indexing bool) []byte {
dst = append(dst, encodeTypeByte(indexing, f.Sensitive))
dst = appendHpackString(dst, f.Name)
return appendHpackString(dst, f.Value)
}
// appendIndexedName appends f and index i referring indexed name
// entry, as encoded in one of "Literal Header field - Indexed Name"
// representation variants, to dst and returns the extended buffer.
//
// If f.Sensitive is true, "Never Indexed" representation is used. If
// f.Sensitive is false and indexing is true, "Incremental Indexing"
// representation is used.
func appendIndexedName(dst []byte, f HeaderField, i uint64, indexing bool) []byte {
first := len(dst)
var n byte
if indexing {
n = 6
} else {
n = 4
}
dst = appendVarInt(dst, n, i)
dst[first] |= encodeTypeByte(indexing, f.Sensitive)
return appendHpackString(dst, f.Value)
}
// appendTableSize appends v, as encoded in "Header Table Size Update"
// representation, to dst and returns the extended buffer.
func appendTableSize(dst []byte, v uint32) []byte {
first := len(dst)
dst = appendVarInt(dst, 5, uint64(v))
dst[first] |= 0x20
return dst
}
// appendVarInt appends i, as encoded in variable integer form using n
// bit prefix, to dst and returns the extended buffer.
//
// See
// http://http2.github.io/http2-spec/compression.html#integer.representation
func appendVarInt(dst []byte, n byte, i uint64) []byte {
k := uint64((1 << n) - 1)
if i < k {
return append(dst, byte(i))
}
dst = append(dst, byte(k))
i -= k
for ; i >= 128; i >>= 7 {
dst = append(dst, byte(0x80|(i&0x7f)))
}
return append(dst, byte(i))
}
// appendHpackString appends s, as encoded in "String Literal"
// representation, to dst and returns the the extended buffer.
//
// s will be encoded in Huffman codes only when it produces strictly
// shorter byte string.
func appendHpackString(dst []byte, s string) []byte {
huffmanLength := HuffmanEncodeLength(s)
if huffmanLength < uint64(len(s)) {
first := len(dst)
dst = appendVarInt(dst, 7, huffmanLength)
dst = AppendHuffmanString(dst, s)
dst[first] |= 0x80
} else {
dst = appendVarInt(dst, 7, uint64(len(s)))
dst = append(dst, s...)
}
return dst
}
// encodeTypeByte returns type byte. If sensitive is true, type byte
// for "Never Indexed" representation is returned. If sensitive is
// false and indexing is true, type byte for "Incremental Indexing"
// representation is returned. Otherwise, type byte for "Without
// Indexing" is returned.
func encodeTypeByte(indexing, sensitive bool) byte {
if sensitive {
return 0x10
}
if indexing {
return 0x40
}
return 0
}
| vendor/golang.org/x/net/http2/hpack/encode.go | 0 | https://github.com/grafana/grafana/commit/98e1404fed0a1cab9cdc6f7404d805459f374f48 | [
0.00022982072550803423,
0.00017488599405623972,
0.00016627325385343283,
0.00017155599198304117,
0.000012938192412548233
] |
{
"id": 1,
"code_window": [
" this.timeSrv.setTime({ from: moment.utc(from), to: moment.utc(to) });\n",
" }\n",
"\n",
" openDropdown() {\n",
" if (this.isOpen) {\n",
" this.isOpen = false;\n",
" return;\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" this.$rootScope.appEvent('escTimepicker');\n"
],
"file_path": "public/app/features/dashboard/timepicker/timepicker.ts",
"type": "add",
"edit_start_line_idx": 98
} | package imguploader
import (
"bytes"
"context"
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"encoding/xml"
"fmt"
"io"
"io/ioutil"
"mime"
"net/http"
"net/url"
"os"
"path"
"sort"
"strconv"
"strings"
"time"
"github.com/grafana/grafana/pkg/log"
"github.com/grafana/grafana/pkg/util"
)
type AzureBlobUploader struct {
account_name string
account_key string
container_name string
log log.Logger
}
func NewAzureBlobUploader(account_name string, account_key string, container_name string) *AzureBlobUploader {
return &AzureBlobUploader{
account_name: account_name,
account_key: account_key,
container_name: container_name,
log: log.New("azureBlobUploader"),
}
}
// Receive path of image on disk and return azure blob url
func (az *AzureBlobUploader) Upload(ctx context.Context, imageDiskPath string) (string, error) {
// setup client
blob := NewStorageClient(az.account_name, az.account_key)
file, err := os.Open(imageDiskPath)
if err != nil {
return "", err
}
randomFileName := util.GetRandomString(30) + ".png"
// upload image
az.log.Debug("Uploading image to azure_blob", "conatiner_name", az.container_name, "blob_name", randomFileName)
resp, err := blob.FileUpload(az.container_name, randomFileName, file)
if err != nil {
return "", err
}
if resp.StatusCode > 400 && resp.StatusCode < 600 {
body, _ := ioutil.ReadAll(io.LimitReader(resp.Body, 1<<20))
aerr := &Error{
Code: resp.StatusCode,
Status: resp.Status,
Body: body,
Header: resp.Header,
}
aerr.parseXML()
resp.Body.Close()
return "", aerr
}
if err != nil {
return "", err
}
url := fmt.Sprintf("https://%s.blob.core.windows.net/%s/%s", az.account_name, az.container_name, randomFileName)
return url, nil
}
// --- AZURE LIBRARY
type Blobs struct {
XMLName xml.Name `xml:"EnumerationResults"`
Items []Blob `xml:"Blobs>Blob"`
}
type Blob struct {
Name string `xml:"Name"`
Property Property `xml:"Properties"`
}
type Property struct {
LastModified string `xml:"Last-Modified"`
Etag string `xml:"Etag"`
ContentLength int `xml:"Content-Length"`
ContentType string `xml:"Content-Type"`
BlobType string `xml:"BlobType"`
LeaseStatus string `xml:"LeaseStatus"`
}
type Error struct {
Code int
Status string
Body []byte
Header http.Header
AzureCode string
}
func (e *Error) Error() string {
return fmt.Sprintf("status %d: %s", e.Code, e.Body)
}
func (e *Error) parseXML() {
var xe xmlError
_ = xml.NewDecoder(bytes.NewReader(e.Body)).Decode(&xe)
e.AzureCode = xe.Code
}
type xmlError struct {
XMLName xml.Name `xml:"Error"`
Code string
Message string
}
const ms_date_layout = "Mon, 02 Jan 2006 15:04:05 GMT"
const version = "2017-04-17"
var client = &http.Client{}
type StorageClient struct {
Auth *Auth
Transport http.RoundTripper
}
func (c *StorageClient) transport() http.RoundTripper {
if c.Transport != nil {
return c.Transport
}
return http.DefaultTransport
}
func NewStorageClient(account, accessKey string) *StorageClient {
return &StorageClient{
Auth: &Auth{
account,
accessKey,
},
Transport: nil,
}
}
func (c *StorageClient) absUrl(format string, a ...interface{}) string {
part := fmt.Sprintf(format, a...)
return fmt.Sprintf("https://%s.blob.core.windows.net/%s", c.Auth.Account, part)
}
func copyHeadersToRequest(req *http.Request, headers map[string]string) {
for k, v := range headers {
req.Header[k] = []string{v}
}
}
func (c *StorageClient) FileUpload(container, blobName string, body io.Reader) (*http.Response, error) {
blobName = escape(blobName)
extension := strings.ToLower(path.Ext(blobName))
contentType := mime.TypeByExtension(extension)
buf := new(bytes.Buffer)
buf.ReadFrom(body)
req, err := http.NewRequest(
"PUT",
c.absUrl("%s/%s", container, blobName),
buf,
)
if err != nil {
return nil, err
}
copyHeadersToRequest(req, map[string]string{
"x-ms-blob-type": "BlockBlob",
"x-ms-date": time.Now().UTC().Format(ms_date_layout),
"x-ms-version": version,
"Accept-Charset": "UTF-8",
"Content-Type": contentType,
"Content-Length": strconv.Itoa(buf.Len()),
})
c.Auth.SignRequest(req)
return c.transport().RoundTrip(req)
}
func escape(content string) string {
content = url.QueryEscape(content)
// the Azure's behavior uses %20 to represent whitespace instead of + (plus)
content = strings.Replace(content, "+", "%20", -1)
// the Azure's behavior uses slash instead of + %2F
content = strings.Replace(content, "%2F", "/", -1)
return content
}
type Auth struct {
Account string
Key string
}
func (a *Auth) SignRequest(req *http.Request) {
strToSign := fmt.Sprintf("%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s",
strings.ToUpper(req.Method),
tryget(req.Header, "Content-Encoding"),
tryget(req.Header, "Content-Language"),
tryget(req.Header, "Content-Length"),
tryget(req.Header, "Content-MD5"),
tryget(req.Header, "Content-Type"),
tryget(req.Header, "Date"),
tryget(req.Header, "If-Modified-Since"),
tryget(req.Header, "If-Match"),
tryget(req.Header, "If-None-Match"),
tryget(req.Header, "If-Unmodified-Since"),
tryget(req.Header, "Range"),
a.canonicalizedHeaders(req),
a.canonicalizedResource(req),
)
decodedKey, _ := base64.StdEncoding.DecodeString(a.Key)
sha256 := hmac.New(sha256.New, []byte(decodedKey))
sha256.Write([]byte(strToSign))
signature := base64.StdEncoding.EncodeToString(sha256.Sum(nil))
copyHeadersToRequest(req, map[string]string{
"Authorization": fmt.Sprintf("SharedKey %s:%s", a.Account, signature),
})
}
func tryget(headers map[string][]string, key string) string {
// We default to empty string for "0" values to match server side behavior when generating signatures.
if len(headers[key]) > 0 { // && headers[key][0] != "0" { //&& key != "Content-Length" {
return headers[key][0]
}
return ""
}
//
// The following is copied ~95% verbatim from:
// http://github.com/loldesign/azure/ -> core/core.go
//
/*
Based on Azure docs:
Link: http://msdn.microsoft.com/en-us/library/windowsazure/dd179428.aspx#Constructing_Element
1) Retrieve all headers for the resource that begin with x-ms-, including the x-ms-date header.
2) Convert each HTTP header name to lowercase.
3) Sort the headers lexicographically by header name, in ascending order. Note that each header may appear only once in the string.
4) Unfold the string by replacing any breaking white space with a single space.
5) Trim any white space around the colon in the header.
6) Finally, append a new line character to each canonicalized header in the resulting list. Construct the CanonicalizedHeaders string by concatenating all headers in this list into a single string.
*/
func (a *Auth) canonicalizedHeaders(req *http.Request) string {
var buffer bytes.Buffer
for key, value := range req.Header {
lowerKey := strings.ToLower(key)
if strings.HasPrefix(lowerKey, "x-ms-") {
if buffer.Len() == 0 {
buffer.WriteString(fmt.Sprintf("%s:%s", lowerKey, value[0]))
} else {
buffer.WriteString(fmt.Sprintf("\n%s:%s", lowerKey, value[0]))
}
}
}
splitted := strings.Split(buffer.String(), "\n")
sort.Strings(splitted)
return strings.Join(splitted, "\n")
}
/*
Based on Azure docs
Link: http://msdn.microsoft.com/en-us/library/windowsazure/dd179428.aspx#Constructing_Element
1) Beginning with an empty string (""), append a forward slash (/), followed by the name of the account that owns the resource being accessed.
2) Append the resource's encoded URI path, without any query parameters.
3) Retrieve all query parameters on the resource URI, including the comp parameter if it exists.
4) Convert all parameter names to lowercase.
5) Sort the query parameters lexicographically by parameter name, in ascending order.
6) URL-decode each query parameter name and value.
7) Append each query parameter name and value to the string in the following format, making sure to include the colon (:) between the name and the value:
parameter-name:parameter-value
8) If a query parameter has more than one value, sort all values lexicographically, then include them in a comma-separated list:
parameter-name:parameter-value-1,parameter-value-2,parameter-value-n
9) Append a new line character (\n) after each name-value pair.
Rules:
1) Avoid using the new line character (\n) in values for query parameters. If it must be used, ensure that it does not affect the format of the canonicalized resource string.
2) Avoid using commas in query parameter values.
*/
func (a *Auth) canonicalizedResource(req *http.Request) string {
var buffer bytes.Buffer
buffer.WriteString(fmt.Sprintf("/%s%s", a.Account, req.URL.Path))
queries := req.URL.Query()
for key, values := range queries {
sort.Strings(values)
buffer.WriteString(fmt.Sprintf("\n%s:%s", key, strings.Join(values, ",")))
}
splitted := strings.Split(buffer.String(), "\n")
sort.Strings(splitted)
return strings.Join(splitted, "\n")
}
| pkg/components/imguploader/azureblobuploader.go | 0 | https://github.com/grafana/grafana/commit/98e1404fed0a1cab9cdc6f7404d805459f374f48 | [
0.0003532784176059067,
0.00017734432185534388,
0.0001641564886085689,
0.00017131210188381374,
0.00003147365714539774
] |
{
"id": 1,
"code_window": [
" this.timeSrv.setTime({ from: moment.utc(from), to: moment.utc(to) });\n",
" }\n",
"\n",
" openDropdown() {\n",
" if (this.isOpen) {\n",
" this.isOpen = false;\n",
" return;\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" this.$rootScope.appEvent('escTimepicker');\n"
],
"file_path": "public/app/features/dashboard/timepicker/timepicker.ts",
"type": "add",
"edit_start_line_idx": 98
} | // Go support for Protocol Buffers - Google's data interchange format
//
// Copyright 2010 The Go Authors. All rights reserved.
// https://github.com/golang/protobuf
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package proto
/*
* Support for message sets.
*/
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"reflect"
"sort"
)
// errNoMessageTypeID occurs when a protocol buffer does not have a message type ID.
// A message type ID is required for storing a protocol buffer in a message set.
var errNoMessageTypeID = errors.New("proto does not have a message type ID")
// The first two types (_MessageSet_Item and messageSet)
// model what the protocol compiler produces for the following protocol message:
// message MessageSet {
// repeated group Item = 1 {
// required int32 type_id = 2;
// required string message = 3;
// };
// }
// That is the MessageSet wire format. We can't use a proto to generate these
// because that would introduce a circular dependency between it and this package.
type _MessageSet_Item struct {
TypeId *int32 `protobuf:"varint,2,req,name=type_id"`
Message []byte `protobuf:"bytes,3,req,name=message"`
}
type messageSet struct {
Item []*_MessageSet_Item `protobuf:"group,1,rep"`
XXX_unrecognized []byte
// TODO: caching?
}
// Make sure messageSet is a Message.
var _ Message = (*messageSet)(nil)
// messageTypeIder is an interface satisfied by a protocol buffer type
// that may be stored in a MessageSet.
type messageTypeIder interface {
MessageTypeId() int32
}
func (ms *messageSet) find(pb Message) *_MessageSet_Item {
mti, ok := pb.(messageTypeIder)
if !ok {
return nil
}
id := mti.MessageTypeId()
for _, item := range ms.Item {
if *item.TypeId == id {
return item
}
}
return nil
}
func (ms *messageSet) Has(pb Message) bool {
if ms.find(pb) != nil {
return true
}
return false
}
func (ms *messageSet) Unmarshal(pb Message) error {
if item := ms.find(pb); item != nil {
return Unmarshal(item.Message, pb)
}
if _, ok := pb.(messageTypeIder); !ok {
return errNoMessageTypeID
}
return nil // TODO: return error instead?
}
func (ms *messageSet) Marshal(pb Message) error {
msg, err := Marshal(pb)
if err != nil {
return err
}
if item := ms.find(pb); item != nil {
// reuse existing item
item.Message = msg
return nil
}
mti, ok := pb.(messageTypeIder)
if !ok {
return errNoMessageTypeID
}
mtid := mti.MessageTypeId()
ms.Item = append(ms.Item, &_MessageSet_Item{
TypeId: &mtid,
Message: msg,
})
return nil
}
func (ms *messageSet) Reset() { *ms = messageSet{} }
func (ms *messageSet) String() string { return CompactTextString(ms) }
func (*messageSet) ProtoMessage() {}
// Support for the message_set_wire_format message option.
func skipVarint(buf []byte) []byte {
i := 0
for ; buf[i]&0x80 != 0; i++ {
}
return buf[i+1:]
}
// MarshalMessageSet encodes the extension map represented by m in the message set wire format.
// It is called by generated Marshal methods on protocol buffer messages with the message_set_wire_format option.
func MarshalMessageSet(exts interface{}) ([]byte, error) {
var m map[int32]Extension
switch exts := exts.(type) {
case *XXX_InternalExtensions:
if err := encodeExtensions(exts); err != nil {
return nil, err
}
m, _ = exts.extensionsRead()
case map[int32]Extension:
if err := encodeExtensionsMap(exts); err != nil {
return nil, err
}
m = exts
default:
return nil, errors.New("proto: not an extension map")
}
// Sort extension IDs to provide a deterministic encoding.
// See also enc_map in encode.go.
ids := make([]int, 0, len(m))
for id := range m {
ids = append(ids, int(id))
}
sort.Ints(ids)
ms := &messageSet{Item: make([]*_MessageSet_Item, 0, len(m))}
for _, id := range ids {
e := m[int32(id)]
// Remove the wire type and field number varint, as well as the length varint.
msg := skipVarint(skipVarint(e.enc))
ms.Item = append(ms.Item, &_MessageSet_Item{
TypeId: Int32(int32(id)),
Message: msg,
})
}
return Marshal(ms)
}
// UnmarshalMessageSet decodes the extension map encoded in buf in the message set wire format.
// It is called by generated Unmarshal methods on protocol buffer messages with the message_set_wire_format option.
func UnmarshalMessageSet(buf []byte, exts interface{}) error {
var m map[int32]Extension
switch exts := exts.(type) {
case *XXX_InternalExtensions:
m = exts.extensionsWrite()
case map[int32]Extension:
m = exts
default:
return errors.New("proto: not an extension map")
}
ms := new(messageSet)
if err := Unmarshal(buf, ms); err != nil {
return err
}
for _, item := range ms.Item {
id := *item.TypeId
msg := item.Message
// Restore wire type and field number varint, plus length varint.
// Be careful to preserve duplicate items.
b := EncodeVarint(uint64(id)<<3 | WireBytes)
if ext, ok := m[id]; ok {
// Existing data; rip off the tag and length varint
// so we join the new data correctly.
// We can assume that ext.enc is set because we are unmarshaling.
o := ext.enc[len(b):] // skip wire type and field number
_, n := DecodeVarint(o) // calculate length of length varint
o = o[n:] // skip length varint
msg = append(o, msg...) // join old data and new data
}
b = append(b, EncodeVarint(uint64(len(msg)))...)
b = append(b, msg...)
m[id] = Extension{enc: b}
}
return nil
}
// MarshalMessageSetJSON encodes the extension map represented by m in JSON format.
// It is called by generated MarshalJSON methods on protocol buffer messages with the message_set_wire_format option.
func MarshalMessageSetJSON(exts interface{}) ([]byte, error) {
var m map[int32]Extension
switch exts := exts.(type) {
case *XXX_InternalExtensions:
m, _ = exts.extensionsRead()
case map[int32]Extension:
m = exts
default:
return nil, errors.New("proto: not an extension map")
}
var b bytes.Buffer
b.WriteByte('{')
// Process the map in key order for deterministic output.
ids := make([]int32, 0, len(m))
for id := range m {
ids = append(ids, id)
}
sort.Sort(int32Slice(ids)) // int32Slice defined in text.go
for i, id := range ids {
ext := m[id]
if i > 0 {
b.WriteByte(',')
}
msd, ok := messageSetMap[id]
if !ok {
// Unknown type; we can't render it, so skip it.
continue
}
fmt.Fprintf(&b, `"[%s]":`, msd.name)
x := ext.value
if x == nil {
x = reflect.New(msd.t.Elem()).Interface()
if err := Unmarshal(ext.enc, x.(Message)); err != nil {
return nil, err
}
}
d, err := json.Marshal(x)
if err != nil {
return nil, err
}
b.Write(d)
}
b.WriteByte('}')
return b.Bytes(), nil
}
// UnmarshalMessageSetJSON decodes the extension map encoded in buf in JSON format.
// It is called by generated UnmarshalJSON methods on protocol buffer messages with the message_set_wire_format option.
func UnmarshalMessageSetJSON(buf []byte, exts interface{}) error {
// Common-case fast path.
if len(buf) == 0 || bytes.Equal(buf, []byte("{}")) {
return nil
}
// This is fairly tricky, and it's not clear that it is needed.
return errors.New("TODO: UnmarshalMessageSetJSON not yet implemented")
}
// A global registry of types that can be used in a MessageSet.
var messageSetMap = make(map[int32]messageSetDesc)
type messageSetDesc struct {
t reflect.Type // pointer to struct
name string
}
// RegisterMessageSetType is called from the generated code.
func RegisterMessageSetType(m Message, fieldNum int32, name string) {
messageSetMap[fieldNum] = messageSetDesc{
t: reflect.TypeOf(m),
name: name,
}
}
| vendor/github.com/golang/protobuf/proto/message_set.go | 0 | https://github.com/grafana/grafana/commit/98e1404fed0a1cab9cdc6f7404d805459f374f48 | [
0.0002569618518464267,
0.00017797586042433977,
0.00016710389172658324,
0.00017312343697994947,
0.00001881920798041392
] |
{
"id": 2,
"code_window": [
" return;\n",
" }\n",
"\n",
" this.$rootScope.appEvent('openTimepicker');\n",
"\n",
" this.onRefresh();\n",
" this.editTimeRaw = this.timeRaw;\n",
" this.timeOptions = rangeUtil.getRelativeTimesList(this.panel, this.rangeString);\n",
" this.refresh = {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "public/app/features/dashboard/timepicker/timepicker.ts",
"type": "replace",
"edit_start_line_idx": 103
} | import _ from 'lodash';
import angular from 'angular';
import moment from 'moment';
import * as rangeUtil from 'app/core/utils/rangeutil';
export class TimePickerCtrl {
static tooltipFormat = 'MMM D, YYYY HH:mm:ss';
static defaults = {
time_options: ['5m', '15m', '1h', '6h', '12h', '24h', '2d', '7d', '30d'],
refresh_intervals: ['5s', '10s', '30s', '1m', '5m', '15m', '30m', '1h', '2h', '1d'],
};
dashboard: any;
panel: any;
absolute: any;
timeRaw: any;
editTimeRaw: any;
tooltip: string;
rangeString: string;
timeOptions: any;
refresh: any;
isUtc: boolean;
firstDayOfWeek: number;
closeDropdown: any;
isOpen: boolean;
/** @ngInject */
constructor(private $scope, private $rootScope, private timeSrv) {
this.$scope.ctrl = this;
$rootScope.onAppEvent('shift-time-forward', () => this.move(1), $scope);
$rootScope.onAppEvent('shift-time-backward', () => this.move(-1), $scope);
$rootScope.onAppEvent('refresh', this.onRefresh.bind(this), $scope);
$rootScope.onAppEvent('closeTimepicker', this.openDropdown.bind(this), $scope);
// init options
this.panel = this.dashboard.timepicker;
_.defaults(this.panel, TimePickerCtrl.defaults);
this.firstDayOfWeek = moment.localeData().firstDayOfWeek();
// init time stuff
this.onRefresh();
}
onRefresh() {
var time = angular.copy(this.timeSrv.timeRange());
var timeRaw = angular.copy(time.raw);
if (!this.dashboard.isTimezoneUtc()) {
time.from.local();
time.to.local();
if (moment.isMoment(timeRaw.from)) {
timeRaw.from.local();
}
if (moment.isMoment(timeRaw.to)) {
timeRaw.to.local();
}
this.isUtc = false;
} else {
this.isUtc = true;
}
this.rangeString = rangeUtil.describeTimeRange(timeRaw);
this.absolute = { fromJs: time.from.toDate(), toJs: time.to.toDate() };
this.tooltip = this.dashboard.formatDate(time.from) + ' <br>to<br>';
this.tooltip += this.dashboard.formatDate(time.to);
this.timeRaw = timeRaw;
}
zoom(factor) {
this.$rootScope.appEvent('zoom-out', 2);
}
move(direction) {
var range = this.timeSrv.timeRange();
var timespan = (range.to.valueOf() - range.from.valueOf()) / 2;
var to, from;
if (direction === -1) {
to = range.to.valueOf() - timespan;
from = range.from.valueOf() - timespan;
} else if (direction === 1) {
to = range.to.valueOf() + timespan;
from = range.from.valueOf() + timespan;
if (to > Date.now() && range.to < Date.now()) {
to = Date.now();
from = range.from.valueOf();
}
} else {
to = range.to.valueOf();
from = range.from.valueOf();
}
this.timeSrv.setTime({ from: moment.utc(from), to: moment.utc(to) });
}
openDropdown() {
if (this.isOpen) {
this.isOpen = false;
return;
}
this.$rootScope.appEvent('openTimepicker');
this.onRefresh();
this.editTimeRaw = this.timeRaw;
this.timeOptions = rangeUtil.getRelativeTimesList(this.panel, this.rangeString);
this.refresh = {
value: this.dashboard.refresh,
options: _.map(this.panel.refresh_intervals, (interval: any) => {
return { text: interval, value: interval };
}),
};
this.refresh.options.unshift({ text: 'off' });
this.isOpen = true;
}
applyCustom() {
if (this.refresh.value !== this.dashboard.refresh) {
this.timeSrv.setAutoRefresh(this.refresh.value);
}
this.timeSrv.setTime(this.editTimeRaw);
this.isOpen = false;
}
absoluteFromChanged() {
this.editTimeRaw.from = this.getAbsoluteMomentForTimezone(this.absolute.fromJs);
}
absoluteToChanged() {
this.editTimeRaw.to = this.getAbsoluteMomentForTimezone(this.absolute.toJs);
}
getAbsoluteMomentForTimezone(jsDate) {
return this.dashboard.isTimezoneUtc() ? moment(jsDate).utc() : moment(jsDate);
}
setRelativeFilter(timespan) {
var range = { from: timespan.from, to: timespan.to };
if (this.panel.nowDelay && range.to === 'now') {
range.to = 'now-' + this.panel.nowDelay;
}
this.timeSrv.setTime(range);
this.isOpen = false;
}
}
export function settingsDirective() {
return {
restrict: 'E',
templateUrl: 'public/app/features/dashboard/timepicker/settings.html',
controller: TimePickerCtrl,
bindToController: true,
controllerAs: 'ctrl',
scope: {
dashboard: '=',
},
};
}
export function timePickerDirective() {
return {
restrict: 'E',
templateUrl: 'public/app/features/dashboard/timepicker/timepicker.html',
controller: TimePickerCtrl,
bindToController: true,
controllerAs: 'ctrl',
scope: {
dashboard: '=',
},
};
}
angular.module('grafana.directives').directive('gfTimePickerSettings', settingsDirective);
angular.module('grafana.directives').directive('gfTimePicker', timePickerDirective);
import { inputDateDirective } from './input_date';
angular.module('grafana.directives').directive('inputDatetime', inputDateDirective);
| public/app/features/dashboard/timepicker/timepicker.ts | 1 | https://github.com/grafana/grafana/commit/98e1404fed0a1cab9cdc6f7404d805459f374f48 | [
0.9982779026031494,
0.1537717878818512,
0.00016487746324855834,
0.001741908024996519,
0.3401762545108795
] |
{
"id": 2,
"code_window": [
" return;\n",
" }\n",
"\n",
" this.$rootScope.appEvent('openTimepicker');\n",
"\n",
" this.onRefresh();\n",
" this.editTimeRaw = this.timeRaw;\n",
" this.timeOptions = rangeUtil.getRelativeTimesList(this.panel, this.rangeString);\n",
" this.refresh = {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "public/app/features/dashboard/timepicker/timepicker.ts",
"type": "replace",
"edit_start_line_idx": 103
} | // Copyright 2017 Prometheus Team
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package procfs
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
// XfrmStat models the contents of /proc/net/xfrm_stat.
type XfrmStat struct {
// All errors which are not matched by other
XfrmInError int
// No buffer is left
XfrmInBufferError int
// Header Error
XfrmInHdrError int
// No state found
// i.e. either inbound SPI, address, or IPSEC protocol at SA is wrong
XfrmInNoStates int
// Transformation protocol specific error
// e.g. SA Key is wrong
XfrmInStateProtoError int
// Transformation mode specific error
XfrmInStateModeError int
// Sequence error
// e.g. sequence number is out of window
XfrmInStateSeqError int
// State is expired
XfrmInStateExpired int
// State has mismatch option
// e.g. UDP encapsulation type is mismatched
XfrmInStateMismatch int
// State is invalid
XfrmInStateInvalid int
// No matching template for states
// e.g. Inbound SAs are correct but SP rule is wrong
XfrmInTmplMismatch int
// No policy is found for states
// e.g. Inbound SAs are correct but no SP is found
XfrmInNoPols int
// Policy discards
XfrmInPolBlock int
// Policy error
XfrmInPolError int
// All errors which are not matched by others
XfrmOutError int
// Bundle generation error
XfrmOutBundleGenError int
// Bundle check error
XfrmOutBundleCheckError int
// No state was found
XfrmOutNoStates int
// Transformation protocol specific error
XfrmOutStateProtoError int
// Transportation mode specific error
XfrmOutStateModeError int
// Sequence error
// i.e sequence number overflow
XfrmOutStateSeqError int
// State is expired
XfrmOutStateExpired int
// Policy discads
XfrmOutPolBlock int
// Policy is dead
XfrmOutPolDead int
// Policy Error
XfrmOutPolError int
XfrmFwdHdrError int
XfrmOutStateInvalid int
XfrmAcquireError int
}
// NewXfrmStat reads the xfrm_stat statistics.
func NewXfrmStat() (XfrmStat, error) {
fs, err := NewFS(DefaultMountPoint)
if err != nil {
return XfrmStat{}, err
}
return fs.NewXfrmStat()
}
// NewXfrmStat reads the xfrm_stat statistics from the 'proc' filesystem.
func (fs FS) NewXfrmStat() (XfrmStat, error) {
file, err := os.Open(fs.Path("net/xfrm_stat"))
if err != nil {
return XfrmStat{}, err
}
defer file.Close()
var (
x = XfrmStat{}
s = bufio.NewScanner(file)
)
for s.Scan() {
fields := strings.Fields(s.Text())
if len(fields) != 2 {
return XfrmStat{}, fmt.Errorf(
"couldnt parse %s line %s", file.Name(), s.Text())
}
name := fields[0]
value, err := strconv.Atoi(fields[1])
if err != nil {
return XfrmStat{}, err
}
switch name {
case "XfrmInError":
x.XfrmInError = value
case "XfrmInBufferError":
x.XfrmInBufferError = value
case "XfrmInHdrError":
x.XfrmInHdrError = value
case "XfrmInNoStates":
x.XfrmInNoStates = value
case "XfrmInStateProtoError":
x.XfrmInStateProtoError = value
case "XfrmInStateModeError":
x.XfrmInStateModeError = value
case "XfrmInStateSeqError":
x.XfrmInStateSeqError = value
case "XfrmInStateExpired":
x.XfrmInStateExpired = value
case "XfrmInStateInvalid":
x.XfrmInStateInvalid = value
case "XfrmInTmplMismatch":
x.XfrmInTmplMismatch = value
case "XfrmInNoPols":
x.XfrmInNoPols = value
case "XfrmInPolBlock":
x.XfrmInPolBlock = value
case "XfrmInPolError":
x.XfrmInPolError = value
case "XfrmOutError":
x.XfrmOutError = value
case "XfrmInStateMismatch":
x.XfrmInStateMismatch = value
case "XfrmOutBundleGenError":
x.XfrmOutBundleGenError = value
case "XfrmOutBundleCheckError":
x.XfrmOutBundleCheckError = value
case "XfrmOutNoStates":
x.XfrmOutNoStates = value
case "XfrmOutStateProtoError":
x.XfrmOutStateProtoError = value
case "XfrmOutStateModeError":
x.XfrmOutStateModeError = value
case "XfrmOutStateSeqError":
x.XfrmOutStateSeqError = value
case "XfrmOutStateExpired":
x.XfrmOutStateExpired = value
case "XfrmOutPolBlock":
x.XfrmOutPolBlock = value
case "XfrmOutPolDead":
x.XfrmOutPolDead = value
case "XfrmOutPolError":
x.XfrmOutPolError = value
case "XfrmFwdHdrError":
x.XfrmFwdHdrError = value
case "XfrmOutStateInvalid":
x.XfrmOutStateInvalid = value
case "XfrmAcquireError":
x.XfrmAcquireError = value
}
}
return x, s.Err()
}
| vendor/github.com/prometheus/procfs/xfrm.go | 0 | https://github.com/grafana/grafana/commit/98e1404fed0a1cab9cdc6f7404d805459f374f48 | [
0.00017670282977633178,
0.0001721963781164959,
0.0001638323301449418,
0.00017365736130159348,
0.0000032561035823164275
] |
{
"id": 2,
"code_window": [
" return;\n",
" }\n",
"\n",
" this.$rootScope.appEvent('openTimepicker');\n",
"\n",
" this.onRefresh();\n",
" this.editTimeRaw = this.timeRaw;\n",
" this.timeOptions = rangeUtil.getRelativeTimesList(this.panel, this.rangeString);\n",
" this.refresh = {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "public/app/features/dashboard/timepicker/timepicker.ts",
"type": "replace",
"edit_start_line_idx": 103
} | // Copyright 2017 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.
// Functions to access/create device major and minor numbers matching the
// encoding used in NetBSD's sys/types.h header.
package unix
// Major returns the major component of a NetBSD device number.
func Major(dev uint64) uint32 {
return uint32((dev & 0x000fff00) >> 8)
}
// Minor returns the minor component of a NetBSD device number.
func Minor(dev uint64) uint32 {
minor := uint32((dev & 0x000000ff) >> 0)
minor |= uint32((dev & 0xfff00000) >> 12)
return minor
}
// Mkdev returns a NetBSD device number generated from the given major and minor
// components.
func Mkdev(major, minor uint32) uint64 {
dev := (uint64(major) << 8) & 0x000fff00
dev |= (uint64(minor) << 12) & 0xfff00000
dev |= (uint64(minor) << 0) & 0x000000ff
return dev
}
| vendor/golang.org/x/sys/unix/dev_netbsd.go | 0 | https://github.com/grafana/grafana/commit/98e1404fed0a1cab9cdc6f7404d805459f374f48 | [
0.00017288498929701746,
0.00016844373021740466,
0.00016461560153402388,
0.00016783059982117265,
0.0000034036881970678223
] |
{
"id": 2,
"code_window": [
" return;\n",
" }\n",
"\n",
" this.$rootScope.appEvent('openTimepicker');\n",
"\n",
" this.onRefresh();\n",
" this.editTimeRaw = this.timeRaw;\n",
" this.timeOptions = rangeUtil.getRelativeTimesList(this.panel, this.rangeString);\n",
" this.refresh = {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "public/app/features/dashboard/timepicker/timepicker.ts",
"type": "replace",
"edit_start_line_idx": 103
} | // Copyright 2015 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 go1.9
package http2
import (
"net/http"
)
func configureServer19(s *http.Server, conf *Server) error {
s.RegisterOnShutdown(conf.state.startGracefulShutdown)
return nil
}
| vendor/golang.org/x/net/http2/go19.go | 0 | https://github.com/grafana/grafana/commit/98e1404fed0a1cab9cdc6f7404d805459f374f48 | [
0.00017635289987083524,
0.00017137263785116374,
0.00016639237583149225,
0.00017137263785116374,
0.0000049802620196715
] |
{
"id": 3,
"code_window": [
" this.isOpen = true;\n",
" }\n",
"\n",
" applyCustom() {\n",
" if (this.refresh.value !== this.dashboard.refresh) {\n",
" this.timeSrv.setAutoRefresh(this.refresh.value);\n",
" }\n",
"\n",
" this.timeSrv.setTime(this.editTimeRaw);\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" this.$rootScope.appEvent('escTimepicker');\n"
],
"file_path": "public/app/features/dashboard/timepicker/timepicker.ts",
"type": "add",
"edit_start_line_idx": 120
} | import _ from 'lodash';
import angular from 'angular';
import moment from 'moment';
import * as rangeUtil from 'app/core/utils/rangeutil';
export class TimePickerCtrl {
static tooltipFormat = 'MMM D, YYYY HH:mm:ss';
static defaults = {
time_options: ['5m', '15m', '1h', '6h', '12h', '24h', '2d', '7d', '30d'],
refresh_intervals: ['5s', '10s', '30s', '1m', '5m', '15m', '30m', '1h', '2h', '1d'],
};
dashboard: any;
panel: any;
absolute: any;
timeRaw: any;
editTimeRaw: any;
tooltip: string;
rangeString: string;
timeOptions: any;
refresh: any;
isUtc: boolean;
firstDayOfWeek: number;
closeDropdown: any;
isOpen: boolean;
/** @ngInject */
constructor(private $scope, private $rootScope, private timeSrv) {
this.$scope.ctrl = this;
$rootScope.onAppEvent('shift-time-forward', () => this.move(1), $scope);
$rootScope.onAppEvent('shift-time-backward', () => this.move(-1), $scope);
$rootScope.onAppEvent('refresh', this.onRefresh.bind(this), $scope);
$rootScope.onAppEvent('closeTimepicker', this.openDropdown.bind(this), $scope);
// init options
this.panel = this.dashboard.timepicker;
_.defaults(this.panel, TimePickerCtrl.defaults);
this.firstDayOfWeek = moment.localeData().firstDayOfWeek();
// init time stuff
this.onRefresh();
}
onRefresh() {
var time = angular.copy(this.timeSrv.timeRange());
var timeRaw = angular.copy(time.raw);
if (!this.dashboard.isTimezoneUtc()) {
time.from.local();
time.to.local();
if (moment.isMoment(timeRaw.from)) {
timeRaw.from.local();
}
if (moment.isMoment(timeRaw.to)) {
timeRaw.to.local();
}
this.isUtc = false;
} else {
this.isUtc = true;
}
this.rangeString = rangeUtil.describeTimeRange(timeRaw);
this.absolute = { fromJs: time.from.toDate(), toJs: time.to.toDate() };
this.tooltip = this.dashboard.formatDate(time.from) + ' <br>to<br>';
this.tooltip += this.dashboard.formatDate(time.to);
this.timeRaw = timeRaw;
}
zoom(factor) {
this.$rootScope.appEvent('zoom-out', 2);
}
move(direction) {
var range = this.timeSrv.timeRange();
var timespan = (range.to.valueOf() - range.from.valueOf()) / 2;
var to, from;
if (direction === -1) {
to = range.to.valueOf() - timespan;
from = range.from.valueOf() - timespan;
} else if (direction === 1) {
to = range.to.valueOf() + timespan;
from = range.from.valueOf() + timespan;
if (to > Date.now() && range.to < Date.now()) {
to = Date.now();
from = range.from.valueOf();
}
} else {
to = range.to.valueOf();
from = range.from.valueOf();
}
this.timeSrv.setTime({ from: moment.utc(from), to: moment.utc(to) });
}
openDropdown() {
if (this.isOpen) {
this.isOpen = false;
return;
}
this.$rootScope.appEvent('openTimepicker');
this.onRefresh();
this.editTimeRaw = this.timeRaw;
this.timeOptions = rangeUtil.getRelativeTimesList(this.panel, this.rangeString);
this.refresh = {
value: this.dashboard.refresh,
options: _.map(this.panel.refresh_intervals, (interval: any) => {
return { text: interval, value: interval };
}),
};
this.refresh.options.unshift({ text: 'off' });
this.isOpen = true;
}
applyCustom() {
if (this.refresh.value !== this.dashboard.refresh) {
this.timeSrv.setAutoRefresh(this.refresh.value);
}
this.timeSrv.setTime(this.editTimeRaw);
this.isOpen = false;
}
absoluteFromChanged() {
this.editTimeRaw.from = this.getAbsoluteMomentForTimezone(this.absolute.fromJs);
}
absoluteToChanged() {
this.editTimeRaw.to = this.getAbsoluteMomentForTimezone(this.absolute.toJs);
}
getAbsoluteMomentForTimezone(jsDate) {
return this.dashboard.isTimezoneUtc() ? moment(jsDate).utc() : moment(jsDate);
}
setRelativeFilter(timespan) {
var range = { from: timespan.from, to: timespan.to };
if (this.panel.nowDelay && range.to === 'now') {
range.to = 'now-' + this.panel.nowDelay;
}
this.timeSrv.setTime(range);
this.isOpen = false;
}
}
export function settingsDirective() {
return {
restrict: 'E',
templateUrl: 'public/app/features/dashboard/timepicker/settings.html',
controller: TimePickerCtrl,
bindToController: true,
controllerAs: 'ctrl',
scope: {
dashboard: '=',
},
};
}
export function timePickerDirective() {
return {
restrict: 'E',
templateUrl: 'public/app/features/dashboard/timepicker/timepicker.html',
controller: TimePickerCtrl,
bindToController: true,
controllerAs: 'ctrl',
scope: {
dashboard: '=',
},
};
}
angular.module('grafana.directives').directive('gfTimePickerSettings', settingsDirective);
angular.module('grafana.directives').directive('gfTimePicker', timePickerDirective);
import { inputDateDirective } from './input_date';
angular.module('grafana.directives').directive('inputDatetime', inputDateDirective);
| public/app/features/dashboard/timepicker/timepicker.ts | 1 | https://github.com/grafana/grafana/commit/98e1404fed0a1cab9cdc6f7404d805459f374f48 | [
0.9954806566238403,
0.06830786168575287,
0.00016665388830006123,
0.0023028794676065445,
0.22389428317546844
] |
{
"id": 3,
"code_window": [
" this.isOpen = true;\n",
" }\n",
"\n",
" applyCustom() {\n",
" if (this.refresh.value !== this.dashboard.refresh) {\n",
" this.timeSrv.setAutoRefresh(this.refresh.value);\n",
" }\n",
"\n",
" this.timeSrv.setTime(this.editTimeRaw);\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" this.$rootScope.appEvent('escTimepicker');\n"
],
"file_path": "public/app/features/dashboard/timepicker/timepicker.ts",
"type": "add",
"edit_start_line_idx": 120
} | import _ from 'lodash';
import TableModel from 'app/core/table_model';
export default class InfluxSeries {
series: any;
alias: any;
annotation: any;
constructor(options) {
this.series = options.series;
this.alias = options.alias;
this.annotation = options.annotation;
}
getTimeSeries() {
var output = [];
var i, j;
if (this.series.length === 0) {
return output;
}
_.each(this.series, series => {
var columns = series.columns.length;
var tags = _.map(series.tags, function(value, key) {
return key + ': ' + value;
});
for (j = 1; j < columns; j++) {
var seriesName = series.name;
var columnName = series.columns[j];
if (columnName !== 'value') {
seriesName = seriesName + '.' + columnName;
}
if (this.alias) {
seriesName = this._getSeriesName(series, j);
} else if (series.tags) {
seriesName = seriesName + ' {' + tags.join(', ') + '}';
}
var datapoints = [];
if (series.values) {
for (i = 0; i < series.values.length; i++) {
datapoints[i] = [series.values[i][j], series.values[i][0]];
}
}
output.push({ target: seriesName, datapoints: datapoints });
}
});
return output;
}
_getSeriesName(series, index) {
var regex = /\$(\w+)|\[\[([\s\S]+?)\]\]/g;
var segments = series.name.split('.');
return this.alias.replace(regex, function(match, g1, g2) {
var group = g1 || g2;
var segIndex = parseInt(group, 10);
if (group === 'm' || group === 'measurement') {
return series.name;
}
if (group === 'col') {
return series.columns[index];
}
if (!isNaN(segIndex)) {
return segments[segIndex];
}
if (group.indexOf('tag_') !== 0) {
return match;
}
var tag = group.replace('tag_', '');
if (!series.tags) {
return match;
}
return series.tags[tag];
});
}
getAnnotations() {
var list = [];
_.each(this.series, series => {
var titleCol = null;
var timeCol = null;
var tagsCol = [];
var textCol = null;
_.each(series.columns, (column, index) => {
if (column === 'time') {
timeCol = index;
return;
}
if (column === 'sequence_number') {
return;
}
if (!titleCol) {
titleCol = index;
}
if (column === this.annotation.titleColumn) {
titleCol = index;
return;
}
if (_.includes((this.annotation.tagsColumn || '').replace(' ', '').split(','), column)) {
tagsCol.push(index);
return;
}
if (column === this.annotation.textColumn) {
textCol = index;
return;
}
});
_.each(series.values, value => {
var data = {
annotation: this.annotation,
time: +new Date(value[timeCol]),
title: value[titleCol],
// Remove empty values, then split in different tags for comma separated values
tags: _.flatten(
tagsCol
.filter(function(t) {
return value[t];
})
.map(function(t) {
return value[t].split(',');
})
),
text: value[textCol],
};
list.push(data);
});
});
return list;
}
getTable() {
var table = new TableModel();
var i, j;
if (this.series.length === 0) {
return table;
}
_.each(this.series, (series, seriesIndex) => {
if (seriesIndex === 0) {
table.columns.push({ text: 'Time', type: 'time' });
_.each(_.keys(series.tags), function(key) {
table.columns.push({ text: key });
});
for (j = 1; j < series.columns.length; j++) {
table.columns.push({ text: series.columns[j] });
}
}
if (series.values) {
for (i = 0; i < series.values.length; i++) {
var values = series.values[i];
var reordered = [values[0]];
if (series.tags) {
for (var key in series.tags) {
if (series.tags.hasOwnProperty(key)) {
reordered.push(series.tags[key]);
}
}
}
for (j = 1; j < values.length; j++) {
reordered.push(values[j]);
}
table.rows.push(reordered);
}
}
});
return table;
}
}
| public/app/plugins/datasource/influxdb/influx_series.ts | 0 | https://github.com/grafana/grafana/commit/98e1404fed0a1cab9cdc6f7404d805459f374f48 | [
0.0001784607593435794,
0.00017215005937032402,
0.00016696436796337366,
0.00017172162188217044,
0.000003186959929735167
] |
{
"id": 3,
"code_window": [
" this.isOpen = true;\n",
" }\n",
"\n",
" applyCustom() {\n",
" if (this.refresh.value !== this.dashboard.refresh) {\n",
" this.timeSrv.setAutoRefresh(this.refresh.value);\n",
" }\n",
"\n",
" this.timeSrv.setTime(this.editTimeRaw);\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" this.$rootScope.appEvent('escTimepicker');\n"
],
"file_path": "public/app/features/dashboard/timepicker/timepicker.ts",
"type": "add",
"edit_start_line_idx": 120
} | package dashboards
import (
"time"
"github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/services/dashboards"
"github.com/grafana/grafana/pkg/models"
)
type DashboardsAsConfig struct {
Name string
Type string
OrgId int64
Folder string
Editable bool
Options map[string]interface{}
DisableDeletion bool
}
type DashboardsAsConfigV0 struct {
Name string `json:"name" yaml:"name"`
Type string `json:"type" yaml:"type"`
OrgId int64 `json:"org_id" yaml:"org_id"`
Folder string `json:"folder" yaml:"folder"`
Editable bool `json:"editable" yaml:"editable"`
Options map[string]interface{} `json:"options" yaml:"options"`
DisableDeletion bool `json:"disableDeletion" yaml:"disableDeletion"`
}
type ConfigVersion struct {
ApiVersion int64 `json:"apiVersion" yaml:"apiVersion"`
}
type DashboardAsConfigV1 struct {
Providers []*DashboardProviderConfigs `json:"providers" yaml:"providers"`
}
type DashboardProviderConfigs struct {
Name string `json:"name" yaml:"name"`
Type string `json:"type" yaml:"type"`
OrgId int64 `json:"orgId" yaml:"orgId"`
Folder string `json:"folder" yaml:"folder"`
Editable bool `json:"editable" yaml:"editable"`
Options map[string]interface{} `json:"options" yaml:"options"`
DisableDeletion bool `json:"disableDeletion" yaml:"disableDeletion"`
}
func createDashboardJson(data *simplejson.Json, lastModified time.Time, cfg *DashboardsAsConfig, folderId int64) (*dashboards.SaveDashboardDTO, error) {
dash := &dashboards.SaveDashboardDTO{}
dash.Dashboard = models.NewDashboardFromJson(data)
dash.UpdatedAt = lastModified
dash.Overwrite = true
dash.OrgId = cfg.OrgId
dash.Dashboard.OrgId = cfg.OrgId
dash.Dashboard.FolderId = folderId
if !cfg.Editable {
dash.Dashboard.Data.Set("editable", cfg.Editable)
}
if dash.Dashboard.Title == "" {
return nil, models.ErrDashboardTitleEmpty
}
return dash, nil
}
func mapV0ToDashboardAsConfig(v0 []*DashboardsAsConfigV0) []*DashboardsAsConfig {
var r []*DashboardsAsConfig
for _, v := range v0 {
r = append(r, &DashboardsAsConfig{
Name: v.Name,
Type: v.Type,
OrgId: v.OrgId,
Folder: v.Folder,
Editable: v.Editable,
Options: v.Options,
DisableDeletion: v.DisableDeletion,
})
}
return r
}
func (dc *DashboardAsConfigV1) mapToDashboardAsConfig() []*DashboardsAsConfig {
var r []*DashboardsAsConfig
for _, v := range dc.Providers {
r = append(r, &DashboardsAsConfig{
Name: v.Name,
Type: v.Type,
OrgId: v.OrgId,
Folder: v.Folder,
Editable: v.Editable,
Options: v.Options,
DisableDeletion: v.DisableDeletion,
})
}
return r
}
| pkg/services/provisioning/dashboards/types.go | 0 | https://github.com/grafana/grafana/commit/98e1404fed0a1cab9cdc6f7404d805459f374f48 | [
0.0013198187807574868,
0.000423416611738503,
0.00016419922758359462,
0.00020787694666069,
0.0003571441338863224
] |
{
"id": 3,
"code_window": [
" this.isOpen = true;\n",
" }\n",
"\n",
" applyCustom() {\n",
" if (this.refresh.value !== this.dashboard.refresh) {\n",
" this.timeSrv.setAutoRefresh(this.refresh.value);\n",
" }\n",
"\n",
" this.timeSrv.setTime(this.editTimeRaw);\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" this.$rootScope.appEvent('escTimepicker');\n"
],
"file_path": "public/app/features/dashboard/timepicker/timepicker.ts",
"type": "add",
"edit_start_line_idx": 120
} | import React, { Component } from 'react';
const xCount = 50;
const yCount = 50;
function Cell({ x, y, flipIndex }) {
const index = (y * xCount) + x;
const bgColor1 = getColor(x, y);
return (
<div className={`login-bg__item ${flipIndex === index ? 'login-bg-flip' : ''}`} key={index} style={{background: bgColor1}} />
);
}
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min; //The maximum is exclusive and the minimum is inclusive
}
export default class LoginBackground extends Component<any, any> {
cancelInterval: any;
constructor(props) {
super(props);
this.state = {
flipIndex: null,
};
this.flipElements = this.flipElements.bind(this);
}
flipElements() {
const elementIndexToFlip = getRandomInt(0, (xCount * yCount) - 1);
this.setState(prevState => {
return {
...prevState,
flipIndex: elementIndexToFlip,
};
});
}
componentWillMount() {
this.cancelInterval = setInterval(this.flipElements, 3000);
}
componentWillUnmount() {
clearInterval(this.cancelInterval);
}
render() {
console.log('re-render!', this.state.flipIndex);
return (
<div className="login-bg">
{Array.from(Array(yCount)).map((el, y) => {
return (
<div className="login-bg__row">
{Array.from(Array(xCount)).map((el2, x) => {
return (
<Cell y={y} x={x} flipIndex={this.state.flipIndex} />
);
})}
</div>
);
})}
</div>
);
}
}
function getColor(x, y) {
const colors = [
'#14161A',
'#111920',
'#121E27',
'#13212B',
'#122029',
'#101C24',
'#0F1B23',
'#0F1B22',
'#111C24',
'#101A22',
'#101A21',
'#111D25',
'#101E27',
'#101D26',
'#101B23',
'#11191E',
'#131519',
'#131518',
'#101B21',
'#121F29',
'#10232D',
'#11212B',
'#0E1C25',
'#0E1C24',
'#111F29',
'#11222B',
'#101E28',
'#102028',
'#111F2A',
'#11202A',
'#11191F',
'#121417',
'#12191D',
'#101D25',
'#11212C',
'#10242F',
'#0F212B',
'#0F1E27',
'#0F1D26',
'#0F1F29',
'#0F2029',
'#11232E',
'#10212B',
'#10222C',
'#0F202A',
'#112530',
'#10252F',
'#0F242E',
'#10222D',
'#10202A',
'#0F1C24',
'#0F1E28',
'#0F212A',
'#0F222B',
'#14171A',
'#0F1A20',
'#0F1C25',
'#10232E',
'#0E202A',
'#0E1E27',
'#0E1D26',
'#0F202B',
'#11232F',
'#102632',
'#102530',
'#122430',
'#0F1B21',
'#0F212C',
'#0E1F29',
'#112531',
'#0F2734',
'#0F2835',
'#0D1B23',
'#0F1A21',
'#0F1A23',
'#0F1D27',
'#0F222D',
'#102430',
'#102531',
'#10222E',
'#0F232D',
'#0E2633',
'#0E2734',
'#0F2834',
'#0E2835',
'#0F2633',
'#0F2532',
'#0E1A22',
'#0D1C24',
'#0F2735',
'#0F2937',
'#102A38',
'#112938',
'#102A39',
'#0F2A38',
'#102836',
'#0E1B23',
'#0F2938',
'#102A3A',
'#102D3D',
'#0F3040',
'#102D3E',
'#0F2E3E',
'#112C3B',
'#102B3B',
'#102B3A',
'#102D3C',
'#0F2A39',
'#0F2634',
'#0E2029',
'#0E1A21',
'#0F2B39',
'#0F2D3D',
'#0F2F40',
'#0E3142',
'#113445',
'#122431',
'#102E3E',
'#0F3345',
'#0E2F40',
'#0F3143',
'#102C3C',
'#0F2B3A',
'#0F1F28',
'#0F3344',
'#113548',
'#113C51',
'#144258',
'#103A4E',
'#103A4F',
'#103547',
'#10364A',
'#103649',
'#0F3448',
'#102C3A',
'#0F2836',
'#103447',
'#0F384C',
'#123F55',
'#15445A',
'#133F55',
'#103B50',
'#113E54',
'#103446',
'#0F3A4F',
'#0F3548',
'#0D3142',
'#102C3B',
'#0E2937',
'#103D52',
'#0E3544',
'#184C65',
'#154760',
'#14435B',
'#15465F',
'#124159',
'#0F3D53',
'#103C51',
'#0F3447',
'#0E3243',
'#113143',
'#113D53',
'#184B64',
'#184D67',
'#184C66',
'#174A63',
'#15455C',
'#13425A',
'#14445A',
'#10384C',
'#0E3446',
'#10181E',
'#103243',
'#0F384D',
'#14455C',
'#164761',
'#164C66',
'#1D627D',
'#12425A',
'#164A63',
'#14465D',
'#13435A',
'#0A2B38',
'#0F3446',
'#0D2F40',
'#0D2F3F',
'#0F2531',
'#102937',
'#10384B',
'#0F3649',
'#184E68',
'#1A5472',
'#184D68',
'#154A63',
'#19506B',
'#19536F',
'#1A4F69',
'#144760',
'#114058',
'#0E3A4F',
'#0E3547',
'#0C3042',
'#0E1B24',
'#11222C',
'#154C65',
'#1A5776',
'#1B5675',
'#113847',
'#1A5371',
'#194E68',
'#0E2D3D',
'#112D3B',
'#113D52',
'#18516D',
'#1A5979',
'#1B5878',
'#19526E',
'#1A526E',
'#13435B',
'#0F3E55',
'#0B374C',
'#0E3448',
'#0D2E3F',
'#0F2B3B',
'#112E3E',
'#113B50',
'#15465D',
'#1A526F',
'#1E5E81',
'#1D5B7B',
'#1A5777',
'#154456',
'#113949',
'#0D394E',
'#0F3549',
'#0F2C3B',
'#0E2733',
'#112E3D',
'#123D52',
'#10394C',
'#1B5674',
'#1A5370',
'#144861',
'#104058',
'#104159',
'#0E384C',
'#0D2D3D',
'#0E2533',
'#112C3A',
'#1B5979',
'#1B5C7D',
'#1A5675',
'#104057',
'#0F3C51',
'#11425A',
'#0E394D',
'#0C3243',
'#0E2735',
'#112F3E',
'#134158',
'#1D5E7F',
'#1D6083',
'#1C5877',
'#1A5573',
'#184D66',
'#164962',
'#0F3D54',
'#0E3D53',
'#0E3447',
'#0F2A3A',
'#0F2936',
'#101F28',
'#103040',
'#124056',
'#164E69',
'#144B64',
'#164D66',
'#0F3E54',
'#0E3B51',
'#0D3346',
'#0E1F27',
'#124158',
'#164961',
'#0E3C52',
'#19506C',
'#0F2C3C',
'#0E3244',
'#0E2A39',
'#0E2938',
'#113040',
'#134057',
'#1A5471',
'#154B63',
'#1C597A',
'#164760',
'#10374B',
'#0E374C',
'#0E384D',
'#11242F',
'#10394D',
'#18526E',
'#154B65',
'#103F55',
'#0D3345',
'#102532',
'#102029',
'#113142',
'#1B5973',
'#1A516B',
'#1C5979',
'#1C5A7A',
'#184A65',
'#164C65',
'#0D3041',
'#123142',
'#123E54',
'#1B5877',
'#1A5574',
'#1C5878',
'#13435C',
'#0F374B',
'#0C3143',
'#112F40',
'#123C51',
'#174E68',
'#1D5C7D',
'#14465F',
'#0F3F56',
'#0B3041',
'#123243',
'#15435B',
'#19516D',
'#1D5D7E',
'#1C5C7D',
'#184F69',
'#11374B',
'#103E54',
'#0E3143',
'#0F2D3C',
'#11242E',
'#133445',
'#1A5674',
'#1D6184',
'#1F658B',
'#0D3A50',
'#0C374B',
'#154862',
'#164B64',
'#154961',
'#0D384D',
'#102631',
'#113242',
'#134259',
'#185270',
'#1D6386',
'#1E678C',
'#1C5978',
'#0D3549',
'#0F2632',
'#184961',
'#1D5E80',
'#1E6488',
'#1F678D',
'#1E5B7C',
'#164862',
'#19526D',
'#113C52',
'#15455E',
'#0F2F3F',
'#144259',
'#194D67',
'#1D6991',
'#195777',
'#19516C',
'#103F56',
'#144660',
'#0D2E3E',
'#10212A',
'#113141',
'#16455C',
'#1D5B7C',
'#1F6589',
'#1E668C',
'#1E5F81',
'#0F3B50',
'#0D3244',
'#164A64',
'#184E69',
'#0E364A',
'#0E2E3E',
'#10222B',
'#19475E',
'#1B5A7B',
'#1E5D7F',
'#1E678D',
'#1E6184',
'#19506A',
'#1B5370',
'#1B5573',
'#0E3041',
'#122E3E',
'#16455B',
'#195370',
'#1D6489',
'#1D6B93',
'#164A65',
'#154A64',
'#1A5572',
'#1D6082',
'#1F6286',
'#1D6C94',
'#1E709A',
'#174A65',
'#1B526F',
'#1E6589',
'#1D6384',
'#0D3143',
'#0E2F3F',
'#174760',
'#1F6487',
'#1D668C',
'#0D2F41',
'#103B4F',
'#1C5C7E',
'#1F688F',
'#1C5B7C',
'#164D68',
'#1D6285',
'#0D364A',
'#1D5A7A',
'#1E6990',
'#1D6488',
'#18516B',
'#1A506B',
'#0E3B50',
'#0E3548',
'#124259',
'#13455C',
'#14485F',
'#1E5C7D',
'#122D3C',
'#1E6E98',
'#1E6A91',
'#1E6286',
'#1E6C95',
'#1D6990',
'#101F29',
'#174A62',
'#10394E',
'#1D6D96',
'#1E688E',
'#1D6E97',
'#1E6C94',
'#0E394E',
'#112B39',
'#195270',
'#1E668B',
'#1E6386',
'#1D6385',
'#0C3142',
'#1E6083',
'#1E729C',
'#1F709A',
'#1E6F98',
'#1D5F81',
'#1F688D',
'#1C6488',
'#1D6588',
'#1C6A93',
'#1E658B',
'#1F6C95',
'#0D3C52',
'#1C6385',
'#1E5F82',
'#0E3D54',
'#0F3244',
'#18485F',
'#1E6991',
'#1C5B7B',
'#1F6082',
'#0F3346',
'#18536F',
'#114056',
'#1D6B92',
'#1B5776',
'#0F3C52',
'#1E6890',
'#1F688E',
'#0C394E',
'#0F1D25',
'#1F6386',
'#1E688D',
'#1F6488',
'#20668C',
'#1D5978',
'#0F3D52',
'#0F1E26',
'#13465F',
'#0D374C',
'#1B5C7C',
'#0E1A23',
'#0F374A',
'#1B5574',
'#0F394C',
'#0E2A38',
'#102A37',
'#18506B',
'#1E5A7A',
'#0F3245',
'#0E2E3F',
'#1E678E',
'#1C5D7E',
'#1A5A7A',
'#0E2837',
'#102733',
'#0F3B51',
'#15475E',
'#1E6B93',
'#1E648A',
'#194961',
'#0F3A4E',
'#0E1D25',
'#194F69',
'#103345',
'#0F394D',
'#102B39',
'#103E55',
'#1B5572',
'#164861',
'#174861',
'#113B4F',
'#102936',
'#0F3041',
'#174961',
'#113E53',
'#134056',
'#124057',
'#194B63',
'#0E364B',
'#15445B',
'#16475E',
'#102F3F',
'#16485F',
'#0F2E3D',
'#101920',
'#12222C',
'#122C3B',
'#144157',
'#123B50',
'#16465D',
'#184960',
'#112B3A',
'#12232F',
'#132430',
'#113344',
'#11394C',
'#113649',
'#11364A',
'#133F56',
'#121D25',
'#112733',
'#112A38',
'#0F1F2A',
'#113447',
'#113A4E',
'#0F222C',
'#13222B',
'#112836',
'#102F3E',
'#113243',
'#123445',
'#12374B',
'#121E26',
'#122531',
'#11303F',
'#0D1D25',
'#102835',
'#112834',
'#101C23',
'#111C23',
'#12212B',
'#11222D',
'#0E1B22',
'#0E1D27',
'#121C22',
'#12202A',
'#101A20',
'#13191E',
'#111E28',
'#11212D',
'#0F1B24',
'#0F1C23',
'#13181D',
'#15171A',
'#121D23',
'#121F27',
'#111E27',
'#101B22',
'#121F28',
'#111E26',
'#101D24',
'#111C22',
'#12161E',
'#101925',
'#121E2D',
'#112033',
'#111E2F',
'#0F1B29',
'#0F1A28',
'#101B2A',
'#0E1A27',
'#101C2B',
'#111D2D',
'#111D2B',
'#0F1B28',
'#101923',
'#13161D',
'#13161C',
'#0F1A26',
'#101E2F',
'#112235',
'#102031',
'#0F1B2A',
'#112031',
'#102032',
'#101D2E',
'#121F2F',
'#112133',
'#101E30',
'#101F30',
'#102336',
'#101B2C',
'#0F1C2B',
'#111E2E',
'#0F2134',
'#102236',
'#0F2133',
'#101F31',
'#0F2438',
'#102337',
'#102235',
'#102133',
'#11171E',
'#101F2F',
'#102030',
'#102234',
'#102132',
'#12181F',
'#0F1A25',
'#0F2135',
'#0F1F30',
'#0F1C2D',
'#101D2C',
'#0F2033',
'#0E2338',
'#0F2237',
'#0F2236',
'#0B243B',
'#0D2338',
'#0E1A26',
'#0F1D2E',
'#0F2032',
'#0D2339',
'#0B253F',
'#0A253F',
'#0A253E',
'#0C2439',
'#0E1925',
'#0E2135',
'#0F2235',
'#0A243A',
'#08253E',
'#09253E',
'#0A263F',
'#0A243C',
'#0B233B',
'#0E1A28',
'#0D1A26',
'#09253F',
'#0A2743',
'#0B2844',
'#0B2641',
'#0A2744',
'#0A2844',
'#0B2743',
'#092745',
'#0F2337',
'#101D2D',
'#092743',
'#092846',
'#0E2B4C',
'#102E4F',
'#0E2C4D',
'#0B2A49',
'#082947',
'#0D2B4B',
'#0C2A4A',
'#092946',
'#082845',
'#0C2B4B',
'#0F2D4E',
'#103051',
'#133257',
'#0E2D4E',
'#143156',
'#112F51',
'#0B243A',
'#082744',
'#092844',
'#123054',
'#143359',
'#173A64',
'#183F6E',
'#173F6D',
'#153961',
'#163962',
'#133358',
'#15345B',
'#14345A',
'#102F50',
'#0A2948',
'#082844',
'#092641',
'#16375F',
'#193C69',
'#174170',
'#173E6B',
'#163A63',
'#173D69',
'#183D6A',
'#15365E',
'#112E50',
'#0A2A49',
'#082743',
'#0E1927',
'#173C68',
'#13487E',
'#164476',
'#174375',
'#193F6F',
'#173B66',
'#163B65',
'#082A48',
'#0A2641',
'#09243C',
'#174171',
'#14477C',
'#124980',
'#14487F',
'#174374',
'#15467B',
'#184172',
'#17406F',
'#184070',
'#163C67',
'#16355D',
'#123256',
'#0E1B29',
'#0F1923',
'#113052',
'#184274',
'#164579',
'#13477C',
'#193E6D',
'#0A243E',
'#0B233A',
'#0D1A29',
'#0B2742',
'#17365E',
'#163860',
'#124A84',
'#095191',
'#114A83',
'#0D4D8A',
'#0C4D8C',
'#104B85',
'#15477E',
'#174477',
'#183862',
'#0A233A',
'#092947',
'#09243D',
'#173963',
'#194173',
'#085396',
'#085394',
'#114B87',
'#144983',
'#094F8E',
'#075090',
'#0F4C89',
'#215287',
'#0E1A29',
'#184376',
'#0C4D8B',
'#07549A',
'#0A4E8D',
'#0F4C88',
'#0A4E8C',
'#174273',
'#193C6A',
'#0B2948',
'#0B2C4B',
'#0C4E8D',
'#1259A4',
'#0C579E',
'#0D4D8B',
'#095397',
'#085397',
'#085295',
'#144880',
'#173861',
'#15335A',
'#0F2C4D',
'#0C2949',
'#0B4E8D',
'#08559C',
'#07508F',
'#154578',
'#17365F',
'#122F53',
'#111D2C',
'#092A48',
'#08559D',
'#08559E',
'#0C56A1',
'#164271',
'#163E6A',
'#194071',
'#082642',
'#0F1E30',
'#0D2D4D',
'#114C87',
'#0E59A3',
'#135BA6',
'#085498',
'#085497',
'#095192',
'#0E4D8B',
'#0C4E8A',
'#134982',
'#17457B',
'#121F2E',
'#183E6C',
'#153E69',
'#07508E',
'#173F6C',
'#193D6B',
'#112D4F',
'#0A243B',
'#072946',
'#111E2D',
'#0B2740',
'#10497F',
'#17406E',
'#084F8D',
'#104A80',
'#0E2E4F',
'#143358',
'#16365D',
'#0A2742',
'#13477B',
'#154474',
'#104C86',
'#095291',
'#0B4F8E',
'#114A80',
'#095090',
'#075296',
'#163760',
'#2D6DB5',
'#0C2843',
'#0C233A',
'#153A62',
'#14467A',
'#075498',
'#085293',
'#09263F',
'#122030',
'#09559D',
'#0F4B83',
'#08549A',
'#14375D',
'#085499',
'#075499',
'#0A243D',
'#143E68',
'#10497E',
'#074F8E',
'#085496',
'#0C58A3',
'#065499',
'#085190',
'#0A2B4A',
'#104C88',
'#0D4F8E',
'#0F58A2',
'#0B569B',
'#0D58A1',
'#134A81',
'#09559C',
'#0A5293',
'#114B86',
'#0D2C4C',
'#103255',
'#16457A',
'#074F8C',
'#07559C',
'#185DA9',
'#1D61AD',
'#175CA8',
'#16406D',
'#153C65',
'#0E243A',
'#144679',
'#085192',
'#1A5EAC',
'#1D61AE',
'#11497F',
'#12487E',
'#0C243C',
'#123155',
'#0F59A3',
'#1B5FAB',
'#1E61AD',
'#145CA4',
'#0E599F',
'#11497E',
'#094F8D',
'#15345A',
'#134A85',
'#165CA8',
'#2263AF',
'#124466',
'#0A518F',
'#08569D',
'#16416F',
'#0B2B4A',
'#124A83',
'#0C57A2',
'#1E60AD',
'#1E62AE',
'#165DA8',
'#1059A4',
'#15406C',
'#0A4F8E',
'#12365A',
'#0A5191',
'#16355C',
'#1C5EAB',
'#155CA7',
'#085292',
'#174478',
'#153258',
'#111F2F',
'#174272',
'#1159A5',
'#1C5EAC',
'#2F74BB',
'#0C58A2',
'#0D59A3',
'#14477D',
'#132F53',
'#155BA6',
'#195FAA',
'#2366B1',
'#2967B2',
'#14477E',
'#1B5EAB',
'#175DA8',
'#0F4C86',
'#065090',
'#1C5FAC',
'#185CA8',
'#0D58A3',
'#0C4E8C',
'#134981',
'#14416D',
'#0F5AA5',
'#1F63AF',
'#114B88',
'#09508E',
'#0A569D',
'#195DAA',
'#0F1D2F',
'#1059A2',
'#0E599E',
'#2063AF',
'#1F63AE',
'#1A5EAA',
'#0C57A0',
'#195EAA',
'#1A5EA9',
'#0E4E8A',
'#12487D',
'#185DAA',
'#175EAA',
'#0A508E',
'#1559A6',
'#0E58A3',
'#095399',
'#0B4E8B',
'#0B569F',
'#0C57A1',
'#2967B1',
'#2365B0',
'#2163AE',
'#1A5DAA',
'#195EAB',
'#1E5FAC',
'#2564AF',
'#2767B1',
'#2766B1',
'#0D5A9F',
'#2062AE',
'#1F61AD',
'#195FAB',
'#0D4E8D',
'#173760',
'#111D2E',
'#09518F',
'#1A5FAC',
'#135BA7',
'#085291',
'#183761',
'#0B2845',
'#113457',
'#075393',
'#185EA9',
'#2B69B3',
'#2A67B2',
'#2867B1',
'#155DA8',
'#135CA6',
'#135AA5',
'#114980',
'#2566B1',
'#2064AF',
'#2364AF',
'#13365B',
'#154475',
'#08549B',
'#164373',
'#085392',
'#144576',
'#12497E',
'#0E5392',
'#135BA3',
'#0C5395',
'#0C5291',
'#0E579C',
'#0E5290',
'#134C83',
'#2163AC',
'#195CA6',
'#0D4E8C',
'#082945',
'#133256',
'#0E2F50',
'#105AA6',
'#134677',
'#144475',
'#145BA7',
'#154270',
'#1D60AD',
'#09569B',
'#09243E',
'#134A86',
'#0E59A4',
'#0A4E8B',
'#0E4B83',
'#1D5EAC',
'#101C2A',
'#134A84',
'#0E518F',
'#145CA7',
'#0E5699',
'#145BA5',
'#095292',
'#15416E',
'#153D67',
'#153F6B',
'#125AA5',
'#16406E',
'#0E1B27',
'#0D4F8C',
'#0F58A3',
'#114A82',
'#09569C',
'#0C2339',
'#0E1B28',
'#0D59A4',
'#07559D',
'#08569E',
'#095190',
'#0B253E',
'#0C2B49',
'#2264AF',
'#09549A',
'#09569F',
'#163D68',
'#0C263F',
'#143960',
'#183A65',
'#075496',
'#0C579F',
'#085191',
'#102438',
'#075295',
'#082946',
'#102437',
'#0C2642',
'#101C29',
'#0C253E',
'#15355C',
'#0B2E4D',
'#0F3253',
'#154577',
'#16335B',
'#0F1925',
'#0C2742',
'#0B2946',
'#0E2C4B',
'#0E2B48',
'#0E2237',
'#102237',
'#0B253D',
'#0A2946',
'#0C2841',
'#0D2A47',
'#0C2C4A',
'#08253F',
'#08243D',
'#111C2B',
'#0C2844',
'#0C2945',
'#0D243A',
'#122134',
'#0B2642',
'#113154',
'#113255',
'#0A2642',
'#0A2945',
'#0B263F',
'#0D2E4E',
'#0F1E2E',
'#0A2845',
'#0D2439',
'#0F1A29',
'#101C2E',
'#111923',
'#13181F',
'#111D2F',
'#111F30',
'#121E30',
'#121E2E',
'#101B27',
'#101A27',
'#13171F',
];
// let randX = getRandomInt(0, x);
// let randY = getRandomInt(0, y);
// let randIndex = randY * xCount + randX;
return colors[(y*xCount + x) % colors.length];
}
| public/app/core/components/Login/LoginBackground.tsx | 0 | https://github.com/grafana/grafana/commit/98e1404fed0a1cab9cdc6f7404d805459f374f48 | [
0.00017808526172302663,
0.000172413419932127,
0.00016634365601930767,
0.00017252532416023314,
0.0000011974046856266796
] |
{
"id": 4,
"code_window": [
" }\n",
"\n",
" setRelativeFilter(timespan) {\n",
" var range = { from: timespan.from, to: timespan.to };\n",
"\n",
" if (this.panel.nowDelay && range.to === 'now') {\n",
" range.to = 'now-' + this.panel.nowDelay;\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" this.$rootScope.appEvent('escTimepicker');\n"
],
"file_path": "public/app/features/dashboard/timepicker/timepicker.ts",
"type": "add",
"edit_start_line_idx": 141
} | import _ from 'lodash';
import angular from 'angular';
import moment from 'moment';
import * as rangeUtil from 'app/core/utils/rangeutil';
export class TimePickerCtrl {
static tooltipFormat = 'MMM D, YYYY HH:mm:ss';
static defaults = {
time_options: ['5m', '15m', '1h', '6h', '12h', '24h', '2d', '7d', '30d'],
refresh_intervals: ['5s', '10s', '30s', '1m', '5m', '15m', '30m', '1h', '2h', '1d'],
};
dashboard: any;
panel: any;
absolute: any;
timeRaw: any;
editTimeRaw: any;
tooltip: string;
rangeString: string;
timeOptions: any;
refresh: any;
isUtc: boolean;
firstDayOfWeek: number;
closeDropdown: any;
isOpen: boolean;
/** @ngInject */
constructor(private $scope, private $rootScope, private timeSrv) {
this.$scope.ctrl = this;
$rootScope.onAppEvent('shift-time-forward', () => this.move(1), $scope);
$rootScope.onAppEvent('shift-time-backward', () => this.move(-1), $scope);
$rootScope.onAppEvent('refresh', this.onRefresh.bind(this), $scope);
$rootScope.onAppEvent('closeTimepicker', this.openDropdown.bind(this), $scope);
// init options
this.panel = this.dashboard.timepicker;
_.defaults(this.panel, TimePickerCtrl.defaults);
this.firstDayOfWeek = moment.localeData().firstDayOfWeek();
// init time stuff
this.onRefresh();
}
onRefresh() {
var time = angular.copy(this.timeSrv.timeRange());
var timeRaw = angular.copy(time.raw);
if (!this.dashboard.isTimezoneUtc()) {
time.from.local();
time.to.local();
if (moment.isMoment(timeRaw.from)) {
timeRaw.from.local();
}
if (moment.isMoment(timeRaw.to)) {
timeRaw.to.local();
}
this.isUtc = false;
} else {
this.isUtc = true;
}
this.rangeString = rangeUtil.describeTimeRange(timeRaw);
this.absolute = { fromJs: time.from.toDate(), toJs: time.to.toDate() };
this.tooltip = this.dashboard.formatDate(time.from) + ' <br>to<br>';
this.tooltip += this.dashboard.formatDate(time.to);
this.timeRaw = timeRaw;
}
zoom(factor) {
this.$rootScope.appEvent('zoom-out', 2);
}
move(direction) {
var range = this.timeSrv.timeRange();
var timespan = (range.to.valueOf() - range.from.valueOf()) / 2;
var to, from;
if (direction === -1) {
to = range.to.valueOf() - timespan;
from = range.from.valueOf() - timespan;
} else if (direction === 1) {
to = range.to.valueOf() + timespan;
from = range.from.valueOf() + timespan;
if (to > Date.now() && range.to < Date.now()) {
to = Date.now();
from = range.from.valueOf();
}
} else {
to = range.to.valueOf();
from = range.from.valueOf();
}
this.timeSrv.setTime({ from: moment.utc(from), to: moment.utc(to) });
}
openDropdown() {
if (this.isOpen) {
this.isOpen = false;
return;
}
this.$rootScope.appEvent('openTimepicker');
this.onRefresh();
this.editTimeRaw = this.timeRaw;
this.timeOptions = rangeUtil.getRelativeTimesList(this.panel, this.rangeString);
this.refresh = {
value: this.dashboard.refresh,
options: _.map(this.panel.refresh_intervals, (interval: any) => {
return { text: interval, value: interval };
}),
};
this.refresh.options.unshift({ text: 'off' });
this.isOpen = true;
}
applyCustom() {
if (this.refresh.value !== this.dashboard.refresh) {
this.timeSrv.setAutoRefresh(this.refresh.value);
}
this.timeSrv.setTime(this.editTimeRaw);
this.isOpen = false;
}
absoluteFromChanged() {
this.editTimeRaw.from = this.getAbsoluteMomentForTimezone(this.absolute.fromJs);
}
absoluteToChanged() {
this.editTimeRaw.to = this.getAbsoluteMomentForTimezone(this.absolute.toJs);
}
getAbsoluteMomentForTimezone(jsDate) {
return this.dashboard.isTimezoneUtc() ? moment(jsDate).utc() : moment(jsDate);
}
setRelativeFilter(timespan) {
var range = { from: timespan.from, to: timespan.to };
if (this.panel.nowDelay && range.to === 'now') {
range.to = 'now-' + this.panel.nowDelay;
}
this.timeSrv.setTime(range);
this.isOpen = false;
}
}
export function settingsDirective() {
return {
restrict: 'E',
templateUrl: 'public/app/features/dashboard/timepicker/settings.html',
controller: TimePickerCtrl,
bindToController: true,
controllerAs: 'ctrl',
scope: {
dashboard: '=',
},
};
}
export function timePickerDirective() {
return {
restrict: 'E',
templateUrl: 'public/app/features/dashboard/timepicker/timepicker.html',
controller: TimePickerCtrl,
bindToController: true,
controllerAs: 'ctrl',
scope: {
dashboard: '=',
},
};
}
angular.module('grafana.directives').directive('gfTimePickerSettings', settingsDirective);
angular.module('grafana.directives').directive('gfTimePicker', timePickerDirective);
import { inputDateDirective } from './input_date';
angular.module('grafana.directives').directive('inputDatetime', inputDateDirective);
| public/app/features/dashboard/timepicker/timepicker.ts | 1 | https://github.com/grafana/grafana/commit/98e1404fed0a1cab9cdc6f7404d805459f374f48 | [
0.9989921450614929,
0.2005174160003662,
0.0001633328793104738,
0.00017562948050908744,
0.3834845721721649
] |
{
"id": 4,
"code_window": [
" }\n",
"\n",
" setRelativeFilter(timespan) {\n",
" var range = { from: timespan.from, to: timespan.to };\n",
"\n",
" if (this.panel.nowDelay && range.to === 'now') {\n",
" range.to = 'now-' + this.panel.nowDelay;\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" this.$rootScope.appEvent('escTimepicker');\n"
],
"file_path": "public/app/features/dashboard/timepicker/timepicker.ts",
"type": "add",
"edit_start_line_idx": 141
} | // Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT.
package ec2
import (
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/request"
)
// WaitUntilBundleTaskComplete uses the Amazon EC2 API operation
// DescribeBundleTasks to wait for a condition to be met before returning.
// If the condition is not met within the max attempt window, an error will
// be returned.
func (c *EC2) WaitUntilBundleTaskComplete(input *DescribeBundleTasksInput) error {
return c.WaitUntilBundleTaskCompleteWithContext(aws.BackgroundContext(), input)
}
// WaitUntilBundleTaskCompleteWithContext is an extended version of WaitUntilBundleTaskComplete.
// With the support for passing in a context and options to configure the
// Waiter and the underlying request options.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *EC2) WaitUntilBundleTaskCompleteWithContext(ctx aws.Context, input *DescribeBundleTasksInput, opts ...request.WaiterOption) error {
w := request.Waiter{
Name: "WaitUntilBundleTaskComplete",
MaxAttempts: 40,
Delay: request.ConstantWaiterDelay(15 * time.Second),
Acceptors: []request.WaiterAcceptor{
{
State: request.SuccessWaiterState,
Matcher: request.PathAllWaiterMatch, Argument: "BundleTasks[].State",
Expected: "complete",
},
{
State: request.FailureWaiterState,
Matcher: request.PathAnyWaiterMatch, Argument: "BundleTasks[].State",
Expected: "failed",
},
},
Logger: c.Config.Logger,
NewRequest: func(opts []request.Option) (*request.Request, error) {
var inCpy *DescribeBundleTasksInput
if input != nil {
tmp := *input
inCpy = &tmp
}
req, _ := c.DescribeBundleTasksRequest(inCpy)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return req, nil
},
}
w.ApplyOptions(opts...)
return w.WaitWithContext(ctx)
}
// WaitUntilConversionTaskCancelled uses the Amazon EC2 API operation
// DescribeConversionTasks to wait for a condition to be met before returning.
// If the condition is not met within the max attempt window, an error will
// be returned.
func (c *EC2) WaitUntilConversionTaskCancelled(input *DescribeConversionTasksInput) error {
return c.WaitUntilConversionTaskCancelledWithContext(aws.BackgroundContext(), input)
}
// WaitUntilConversionTaskCancelledWithContext is an extended version of WaitUntilConversionTaskCancelled.
// With the support for passing in a context and options to configure the
// Waiter and the underlying request options.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *EC2) WaitUntilConversionTaskCancelledWithContext(ctx aws.Context, input *DescribeConversionTasksInput, opts ...request.WaiterOption) error {
w := request.Waiter{
Name: "WaitUntilConversionTaskCancelled",
MaxAttempts: 40,
Delay: request.ConstantWaiterDelay(15 * time.Second),
Acceptors: []request.WaiterAcceptor{
{
State: request.SuccessWaiterState,
Matcher: request.PathAllWaiterMatch, Argument: "ConversionTasks[].State",
Expected: "cancelled",
},
},
Logger: c.Config.Logger,
NewRequest: func(opts []request.Option) (*request.Request, error) {
var inCpy *DescribeConversionTasksInput
if input != nil {
tmp := *input
inCpy = &tmp
}
req, _ := c.DescribeConversionTasksRequest(inCpy)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return req, nil
},
}
w.ApplyOptions(opts...)
return w.WaitWithContext(ctx)
}
// WaitUntilConversionTaskCompleted uses the Amazon EC2 API operation
// DescribeConversionTasks to wait for a condition to be met before returning.
// If the condition is not met within the max attempt window, an error will
// be returned.
func (c *EC2) WaitUntilConversionTaskCompleted(input *DescribeConversionTasksInput) error {
return c.WaitUntilConversionTaskCompletedWithContext(aws.BackgroundContext(), input)
}
// WaitUntilConversionTaskCompletedWithContext is an extended version of WaitUntilConversionTaskCompleted.
// With the support for passing in a context and options to configure the
// Waiter and the underlying request options.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *EC2) WaitUntilConversionTaskCompletedWithContext(ctx aws.Context, input *DescribeConversionTasksInput, opts ...request.WaiterOption) error {
w := request.Waiter{
Name: "WaitUntilConversionTaskCompleted",
MaxAttempts: 40,
Delay: request.ConstantWaiterDelay(15 * time.Second),
Acceptors: []request.WaiterAcceptor{
{
State: request.SuccessWaiterState,
Matcher: request.PathAllWaiterMatch, Argument: "ConversionTasks[].State",
Expected: "completed",
},
{
State: request.FailureWaiterState,
Matcher: request.PathAnyWaiterMatch, Argument: "ConversionTasks[].State",
Expected: "cancelled",
},
{
State: request.FailureWaiterState,
Matcher: request.PathAnyWaiterMatch, Argument: "ConversionTasks[].State",
Expected: "cancelling",
},
},
Logger: c.Config.Logger,
NewRequest: func(opts []request.Option) (*request.Request, error) {
var inCpy *DescribeConversionTasksInput
if input != nil {
tmp := *input
inCpy = &tmp
}
req, _ := c.DescribeConversionTasksRequest(inCpy)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return req, nil
},
}
w.ApplyOptions(opts...)
return w.WaitWithContext(ctx)
}
// WaitUntilConversionTaskDeleted uses the Amazon EC2 API operation
// DescribeConversionTasks to wait for a condition to be met before returning.
// If the condition is not met within the max attempt window, an error will
// be returned.
func (c *EC2) WaitUntilConversionTaskDeleted(input *DescribeConversionTasksInput) error {
return c.WaitUntilConversionTaskDeletedWithContext(aws.BackgroundContext(), input)
}
// WaitUntilConversionTaskDeletedWithContext is an extended version of WaitUntilConversionTaskDeleted.
// With the support for passing in a context and options to configure the
// Waiter and the underlying request options.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *EC2) WaitUntilConversionTaskDeletedWithContext(ctx aws.Context, input *DescribeConversionTasksInput, opts ...request.WaiterOption) error {
w := request.Waiter{
Name: "WaitUntilConversionTaskDeleted",
MaxAttempts: 40,
Delay: request.ConstantWaiterDelay(15 * time.Second),
Acceptors: []request.WaiterAcceptor{
{
State: request.SuccessWaiterState,
Matcher: request.PathAllWaiterMatch, Argument: "ConversionTasks[].State",
Expected: "deleted",
},
},
Logger: c.Config.Logger,
NewRequest: func(opts []request.Option) (*request.Request, error) {
var inCpy *DescribeConversionTasksInput
if input != nil {
tmp := *input
inCpy = &tmp
}
req, _ := c.DescribeConversionTasksRequest(inCpy)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return req, nil
},
}
w.ApplyOptions(opts...)
return w.WaitWithContext(ctx)
}
// WaitUntilCustomerGatewayAvailable uses the Amazon EC2 API operation
// DescribeCustomerGateways to wait for a condition to be met before returning.
// If the condition is not met within the max attempt window, an error will
// be returned.
func (c *EC2) WaitUntilCustomerGatewayAvailable(input *DescribeCustomerGatewaysInput) error {
return c.WaitUntilCustomerGatewayAvailableWithContext(aws.BackgroundContext(), input)
}
// WaitUntilCustomerGatewayAvailableWithContext is an extended version of WaitUntilCustomerGatewayAvailable.
// With the support for passing in a context and options to configure the
// Waiter and the underlying request options.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *EC2) WaitUntilCustomerGatewayAvailableWithContext(ctx aws.Context, input *DescribeCustomerGatewaysInput, opts ...request.WaiterOption) error {
w := request.Waiter{
Name: "WaitUntilCustomerGatewayAvailable",
MaxAttempts: 40,
Delay: request.ConstantWaiterDelay(15 * time.Second),
Acceptors: []request.WaiterAcceptor{
{
State: request.SuccessWaiterState,
Matcher: request.PathAllWaiterMatch, Argument: "CustomerGateways[].State",
Expected: "available",
},
{
State: request.FailureWaiterState,
Matcher: request.PathAnyWaiterMatch, Argument: "CustomerGateways[].State",
Expected: "deleted",
},
{
State: request.FailureWaiterState,
Matcher: request.PathAnyWaiterMatch, Argument: "CustomerGateways[].State",
Expected: "deleting",
},
},
Logger: c.Config.Logger,
NewRequest: func(opts []request.Option) (*request.Request, error) {
var inCpy *DescribeCustomerGatewaysInput
if input != nil {
tmp := *input
inCpy = &tmp
}
req, _ := c.DescribeCustomerGatewaysRequest(inCpy)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return req, nil
},
}
w.ApplyOptions(opts...)
return w.WaitWithContext(ctx)
}
// WaitUntilExportTaskCancelled uses the Amazon EC2 API operation
// DescribeExportTasks to wait for a condition to be met before returning.
// If the condition is not met within the max attempt window, an error will
// be returned.
func (c *EC2) WaitUntilExportTaskCancelled(input *DescribeExportTasksInput) error {
return c.WaitUntilExportTaskCancelledWithContext(aws.BackgroundContext(), input)
}
// WaitUntilExportTaskCancelledWithContext is an extended version of WaitUntilExportTaskCancelled.
// With the support for passing in a context and options to configure the
// Waiter and the underlying request options.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *EC2) WaitUntilExportTaskCancelledWithContext(ctx aws.Context, input *DescribeExportTasksInput, opts ...request.WaiterOption) error {
w := request.Waiter{
Name: "WaitUntilExportTaskCancelled",
MaxAttempts: 40,
Delay: request.ConstantWaiterDelay(15 * time.Second),
Acceptors: []request.WaiterAcceptor{
{
State: request.SuccessWaiterState,
Matcher: request.PathAllWaiterMatch, Argument: "ExportTasks[].State",
Expected: "cancelled",
},
},
Logger: c.Config.Logger,
NewRequest: func(opts []request.Option) (*request.Request, error) {
var inCpy *DescribeExportTasksInput
if input != nil {
tmp := *input
inCpy = &tmp
}
req, _ := c.DescribeExportTasksRequest(inCpy)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return req, nil
},
}
w.ApplyOptions(opts...)
return w.WaitWithContext(ctx)
}
// WaitUntilExportTaskCompleted uses the Amazon EC2 API operation
// DescribeExportTasks to wait for a condition to be met before returning.
// If the condition is not met within the max attempt window, an error will
// be returned.
func (c *EC2) WaitUntilExportTaskCompleted(input *DescribeExportTasksInput) error {
return c.WaitUntilExportTaskCompletedWithContext(aws.BackgroundContext(), input)
}
// WaitUntilExportTaskCompletedWithContext is an extended version of WaitUntilExportTaskCompleted.
// With the support for passing in a context and options to configure the
// Waiter and the underlying request options.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *EC2) WaitUntilExportTaskCompletedWithContext(ctx aws.Context, input *DescribeExportTasksInput, opts ...request.WaiterOption) error {
w := request.Waiter{
Name: "WaitUntilExportTaskCompleted",
MaxAttempts: 40,
Delay: request.ConstantWaiterDelay(15 * time.Second),
Acceptors: []request.WaiterAcceptor{
{
State: request.SuccessWaiterState,
Matcher: request.PathAllWaiterMatch, Argument: "ExportTasks[].State",
Expected: "completed",
},
},
Logger: c.Config.Logger,
NewRequest: func(opts []request.Option) (*request.Request, error) {
var inCpy *DescribeExportTasksInput
if input != nil {
tmp := *input
inCpy = &tmp
}
req, _ := c.DescribeExportTasksRequest(inCpy)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return req, nil
},
}
w.ApplyOptions(opts...)
return w.WaitWithContext(ctx)
}
// WaitUntilImageAvailable uses the Amazon EC2 API operation
// DescribeImages to wait for a condition to be met before returning.
// If the condition is not met within the max attempt window, an error will
// be returned.
func (c *EC2) WaitUntilImageAvailable(input *DescribeImagesInput) error {
return c.WaitUntilImageAvailableWithContext(aws.BackgroundContext(), input)
}
// WaitUntilImageAvailableWithContext is an extended version of WaitUntilImageAvailable.
// With the support for passing in a context and options to configure the
// Waiter and the underlying request options.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *EC2) WaitUntilImageAvailableWithContext(ctx aws.Context, input *DescribeImagesInput, opts ...request.WaiterOption) error {
w := request.Waiter{
Name: "WaitUntilImageAvailable",
MaxAttempts: 40,
Delay: request.ConstantWaiterDelay(15 * time.Second),
Acceptors: []request.WaiterAcceptor{
{
State: request.SuccessWaiterState,
Matcher: request.PathAllWaiterMatch, Argument: "Images[].State",
Expected: "available",
},
{
State: request.FailureWaiterState,
Matcher: request.PathAnyWaiterMatch, Argument: "Images[].State",
Expected: "failed",
},
},
Logger: c.Config.Logger,
NewRequest: func(opts []request.Option) (*request.Request, error) {
var inCpy *DescribeImagesInput
if input != nil {
tmp := *input
inCpy = &tmp
}
req, _ := c.DescribeImagesRequest(inCpy)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return req, nil
},
}
w.ApplyOptions(opts...)
return w.WaitWithContext(ctx)
}
// WaitUntilImageExists uses the Amazon EC2 API operation
// DescribeImages to wait for a condition to be met before returning.
// If the condition is not met within the max attempt window, an error will
// be returned.
func (c *EC2) WaitUntilImageExists(input *DescribeImagesInput) error {
return c.WaitUntilImageExistsWithContext(aws.BackgroundContext(), input)
}
// WaitUntilImageExistsWithContext is an extended version of WaitUntilImageExists.
// With the support for passing in a context and options to configure the
// Waiter and the underlying request options.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *EC2) WaitUntilImageExistsWithContext(ctx aws.Context, input *DescribeImagesInput, opts ...request.WaiterOption) error {
w := request.Waiter{
Name: "WaitUntilImageExists",
MaxAttempts: 40,
Delay: request.ConstantWaiterDelay(15 * time.Second),
Acceptors: []request.WaiterAcceptor{
{
State: request.SuccessWaiterState,
Matcher: request.PathWaiterMatch, Argument: "length(Images[]) > `0`",
Expected: true,
},
{
State: request.RetryWaiterState,
Matcher: request.ErrorWaiterMatch,
Expected: "InvalidAMIID.NotFound",
},
},
Logger: c.Config.Logger,
NewRequest: func(opts []request.Option) (*request.Request, error) {
var inCpy *DescribeImagesInput
if input != nil {
tmp := *input
inCpy = &tmp
}
req, _ := c.DescribeImagesRequest(inCpy)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return req, nil
},
}
w.ApplyOptions(opts...)
return w.WaitWithContext(ctx)
}
// WaitUntilInstanceExists uses the Amazon EC2 API operation
// DescribeInstances to wait for a condition to be met before returning.
// If the condition is not met within the max attempt window, an error will
// be returned.
func (c *EC2) WaitUntilInstanceExists(input *DescribeInstancesInput) error {
return c.WaitUntilInstanceExistsWithContext(aws.BackgroundContext(), input)
}
// WaitUntilInstanceExistsWithContext is an extended version of WaitUntilInstanceExists.
// With the support for passing in a context and options to configure the
// Waiter and the underlying request options.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *EC2) WaitUntilInstanceExistsWithContext(ctx aws.Context, input *DescribeInstancesInput, opts ...request.WaiterOption) error {
w := request.Waiter{
Name: "WaitUntilInstanceExists",
MaxAttempts: 40,
Delay: request.ConstantWaiterDelay(5 * time.Second),
Acceptors: []request.WaiterAcceptor{
{
State: request.SuccessWaiterState,
Matcher: request.PathWaiterMatch, Argument: "length(Reservations[]) > `0`",
Expected: true,
},
{
State: request.RetryWaiterState,
Matcher: request.ErrorWaiterMatch,
Expected: "InvalidInstanceID.NotFound",
},
},
Logger: c.Config.Logger,
NewRequest: func(opts []request.Option) (*request.Request, error) {
var inCpy *DescribeInstancesInput
if input != nil {
tmp := *input
inCpy = &tmp
}
req, _ := c.DescribeInstancesRequest(inCpy)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return req, nil
},
}
w.ApplyOptions(opts...)
return w.WaitWithContext(ctx)
}
// WaitUntilInstanceRunning uses the Amazon EC2 API operation
// DescribeInstances to wait for a condition to be met before returning.
// If the condition is not met within the max attempt window, an error will
// be returned.
func (c *EC2) WaitUntilInstanceRunning(input *DescribeInstancesInput) error {
return c.WaitUntilInstanceRunningWithContext(aws.BackgroundContext(), input)
}
// WaitUntilInstanceRunningWithContext is an extended version of WaitUntilInstanceRunning.
// With the support for passing in a context and options to configure the
// Waiter and the underlying request options.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *EC2) WaitUntilInstanceRunningWithContext(ctx aws.Context, input *DescribeInstancesInput, opts ...request.WaiterOption) error {
w := request.Waiter{
Name: "WaitUntilInstanceRunning",
MaxAttempts: 40,
Delay: request.ConstantWaiterDelay(15 * time.Second),
Acceptors: []request.WaiterAcceptor{
{
State: request.SuccessWaiterState,
Matcher: request.PathAllWaiterMatch, Argument: "Reservations[].Instances[].State.Name",
Expected: "running",
},
{
State: request.FailureWaiterState,
Matcher: request.PathAnyWaiterMatch, Argument: "Reservations[].Instances[].State.Name",
Expected: "shutting-down",
},
{
State: request.FailureWaiterState,
Matcher: request.PathAnyWaiterMatch, Argument: "Reservations[].Instances[].State.Name",
Expected: "terminated",
},
{
State: request.FailureWaiterState,
Matcher: request.PathAnyWaiterMatch, Argument: "Reservations[].Instances[].State.Name",
Expected: "stopping",
},
{
State: request.RetryWaiterState,
Matcher: request.ErrorWaiterMatch,
Expected: "InvalidInstanceID.NotFound",
},
},
Logger: c.Config.Logger,
NewRequest: func(opts []request.Option) (*request.Request, error) {
var inCpy *DescribeInstancesInput
if input != nil {
tmp := *input
inCpy = &tmp
}
req, _ := c.DescribeInstancesRequest(inCpy)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return req, nil
},
}
w.ApplyOptions(opts...)
return w.WaitWithContext(ctx)
}
// WaitUntilInstanceStatusOk uses the Amazon EC2 API operation
// DescribeInstanceStatus to wait for a condition to be met before returning.
// If the condition is not met within the max attempt window, an error will
// be returned.
func (c *EC2) WaitUntilInstanceStatusOk(input *DescribeInstanceStatusInput) error {
return c.WaitUntilInstanceStatusOkWithContext(aws.BackgroundContext(), input)
}
// WaitUntilInstanceStatusOkWithContext is an extended version of WaitUntilInstanceStatusOk.
// With the support for passing in a context and options to configure the
// Waiter and the underlying request options.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *EC2) WaitUntilInstanceStatusOkWithContext(ctx aws.Context, input *DescribeInstanceStatusInput, opts ...request.WaiterOption) error {
w := request.Waiter{
Name: "WaitUntilInstanceStatusOk",
MaxAttempts: 40,
Delay: request.ConstantWaiterDelay(15 * time.Second),
Acceptors: []request.WaiterAcceptor{
{
State: request.SuccessWaiterState,
Matcher: request.PathAllWaiterMatch, Argument: "InstanceStatuses[].InstanceStatus.Status",
Expected: "ok",
},
{
State: request.RetryWaiterState,
Matcher: request.ErrorWaiterMatch,
Expected: "InvalidInstanceID.NotFound",
},
},
Logger: c.Config.Logger,
NewRequest: func(opts []request.Option) (*request.Request, error) {
var inCpy *DescribeInstanceStatusInput
if input != nil {
tmp := *input
inCpy = &tmp
}
req, _ := c.DescribeInstanceStatusRequest(inCpy)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return req, nil
},
}
w.ApplyOptions(opts...)
return w.WaitWithContext(ctx)
}
// WaitUntilInstanceStopped uses the Amazon EC2 API operation
// DescribeInstances to wait for a condition to be met before returning.
// If the condition is not met within the max attempt window, an error will
// be returned.
func (c *EC2) WaitUntilInstanceStopped(input *DescribeInstancesInput) error {
return c.WaitUntilInstanceStoppedWithContext(aws.BackgroundContext(), input)
}
// WaitUntilInstanceStoppedWithContext is an extended version of WaitUntilInstanceStopped.
// With the support for passing in a context and options to configure the
// Waiter and the underlying request options.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *EC2) WaitUntilInstanceStoppedWithContext(ctx aws.Context, input *DescribeInstancesInput, opts ...request.WaiterOption) error {
w := request.Waiter{
Name: "WaitUntilInstanceStopped",
MaxAttempts: 40,
Delay: request.ConstantWaiterDelay(15 * time.Second),
Acceptors: []request.WaiterAcceptor{
{
State: request.SuccessWaiterState,
Matcher: request.PathAllWaiterMatch, Argument: "Reservations[].Instances[].State.Name",
Expected: "stopped",
},
{
State: request.FailureWaiterState,
Matcher: request.PathAnyWaiterMatch, Argument: "Reservations[].Instances[].State.Name",
Expected: "pending",
},
{
State: request.FailureWaiterState,
Matcher: request.PathAnyWaiterMatch, Argument: "Reservations[].Instances[].State.Name",
Expected: "terminated",
},
},
Logger: c.Config.Logger,
NewRequest: func(opts []request.Option) (*request.Request, error) {
var inCpy *DescribeInstancesInput
if input != nil {
tmp := *input
inCpy = &tmp
}
req, _ := c.DescribeInstancesRequest(inCpy)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return req, nil
},
}
w.ApplyOptions(opts...)
return w.WaitWithContext(ctx)
}
// WaitUntilInstanceTerminated uses the Amazon EC2 API operation
// DescribeInstances to wait for a condition to be met before returning.
// If the condition is not met within the max attempt window, an error will
// be returned.
func (c *EC2) WaitUntilInstanceTerminated(input *DescribeInstancesInput) error {
return c.WaitUntilInstanceTerminatedWithContext(aws.BackgroundContext(), input)
}
// WaitUntilInstanceTerminatedWithContext is an extended version of WaitUntilInstanceTerminated.
// With the support for passing in a context and options to configure the
// Waiter and the underlying request options.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *EC2) WaitUntilInstanceTerminatedWithContext(ctx aws.Context, input *DescribeInstancesInput, opts ...request.WaiterOption) error {
w := request.Waiter{
Name: "WaitUntilInstanceTerminated",
MaxAttempts: 40,
Delay: request.ConstantWaiterDelay(15 * time.Second),
Acceptors: []request.WaiterAcceptor{
{
State: request.SuccessWaiterState,
Matcher: request.PathAllWaiterMatch, Argument: "Reservations[].Instances[].State.Name",
Expected: "terminated",
},
{
State: request.FailureWaiterState,
Matcher: request.PathAnyWaiterMatch, Argument: "Reservations[].Instances[].State.Name",
Expected: "pending",
},
{
State: request.FailureWaiterState,
Matcher: request.PathAnyWaiterMatch, Argument: "Reservations[].Instances[].State.Name",
Expected: "stopping",
},
},
Logger: c.Config.Logger,
NewRequest: func(opts []request.Option) (*request.Request, error) {
var inCpy *DescribeInstancesInput
if input != nil {
tmp := *input
inCpy = &tmp
}
req, _ := c.DescribeInstancesRequest(inCpy)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return req, nil
},
}
w.ApplyOptions(opts...)
return w.WaitWithContext(ctx)
}
// WaitUntilKeyPairExists uses the Amazon EC2 API operation
// DescribeKeyPairs to wait for a condition to be met before returning.
// If the condition is not met within the max attempt window, an error will
// be returned.
func (c *EC2) WaitUntilKeyPairExists(input *DescribeKeyPairsInput) error {
return c.WaitUntilKeyPairExistsWithContext(aws.BackgroundContext(), input)
}
// WaitUntilKeyPairExistsWithContext is an extended version of WaitUntilKeyPairExists.
// With the support for passing in a context and options to configure the
// Waiter and the underlying request options.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *EC2) WaitUntilKeyPairExistsWithContext(ctx aws.Context, input *DescribeKeyPairsInput, opts ...request.WaiterOption) error {
w := request.Waiter{
Name: "WaitUntilKeyPairExists",
MaxAttempts: 6,
Delay: request.ConstantWaiterDelay(5 * time.Second),
Acceptors: []request.WaiterAcceptor{
{
State: request.SuccessWaiterState,
Matcher: request.PathWaiterMatch, Argument: "length(KeyPairs[].KeyName) > `0`",
Expected: true,
},
{
State: request.RetryWaiterState,
Matcher: request.ErrorWaiterMatch,
Expected: "InvalidKeyPair.NotFound",
},
},
Logger: c.Config.Logger,
NewRequest: func(opts []request.Option) (*request.Request, error) {
var inCpy *DescribeKeyPairsInput
if input != nil {
tmp := *input
inCpy = &tmp
}
req, _ := c.DescribeKeyPairsRequest(inCpy)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return req, nil
},
}
w.ApplyOptions(opts...)
return w.WaitWithContext(ctx)
}
// WaitUntilNatGatewayAvailable uses the Amazon EC2 API operation
// DescribeNatGateways to wait for a condition to be met before returning.
// If the condition is not met within the max attempt window, an error will
// be returned.
func (c *EC2) WaitUntilNatGatewayAvailable(input *DescribeNatGatewaysInput) error {
return c.WaitUntilNatGatewayAvailableWithContext(aws.BackgroundContext(), input)
}
// WaitUntilNatGatewayAvailableWithContext is an extended version of WaitUntilNatGatewayAvailable.
// With the support for passing in a context and options to configure the
// Waiter and the underlying request options.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *EC2) WaitUntilNatGatewayAvailableWithContext(ctx aws.Context, input *DescribeNatGatewaysInput, opts ...request.WaiterOption) error {
w := request.Waiter{
Name: "WaitUntilNatGatewayAvailable",
MaxAttempts: 40,
Delay: request.ConstantWaiterDelay(15 * time.Second),
Acceptors: []request.WaiterAcceptor{
{
State: request.SuccessWaiterState,
Matcher: request.PathAllWaiterMatch, Argument: "NatGateways[].State",
Expected: "available",
},
{
State: request.FailureWaiterState,
Matcher: request.PathAnyWaiterMatch, Argument: "NatGateways[].State",
Expected: "failed",
},
{
State: request.FailureWaiterState,
Matcher: request.PathAnyWaiterMatch, Argument: "NatGateways[].State",
Expected: "deleting",
},
{
State: request.FailureWaiterState,
Matcher: request.PathAnyWaiterMatch, Argument: "NatGateways[].State",
Expected: "deleted",
},
{
State: request.RetryWaiterState,
Matcher: request.ErrorWaiterMatch,
Expected: "NatGatewayNotFound",
},
},
Logger: c.Config.Logger,
NewRequest: func(opts []request.Option) (*request.Request, error) {
var inCpy *DescribeNatGatewaysInput
if input != nil {
tmp := *input
inCpy = &tmp
}
req, _ := c.DescribeNatGatewaysRequest(inCpy)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return req, nil
},
}
w.ApplyOptions(opts...)
return w.WaitWithContext(ctx)
}
// WaitUntilNetworkInterfaceAvailable uses the Amazon EC2 API operation
// DescribeNetworkInterfaces to wait for a condition to be met before returning.
// If the condition is not met within the max attempt window, an error will
// be returned.
func (c *EC2) WaitUntilNetworkInterfaceAvailable(input *DescribeNetworkInterfacesInput) error {
return c.WaitUntilNetworkInterfaceAvailableWithContext(aws.BackgroundContext(), input)
}
// WaitUntilNetworkInterfaceAvailableWithContext is an extended version of WaitUntilNetworkInterfaceAvailable.
// With the support for passing in a context and options to configure the
// Waiter and the underlying request options.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *EC2) WaitUntilNetworkInterfaceAvailableWithContext(ctx aws.Context, input *DescribeNetworkInterfacesInput, opts ...request.WaiterOption) error {
w := request.Waiter{
Name: "WaitUntilNetworkInterfaceAvailable",
MaxAttempts: 10,
Delay: request.ConstantWaiterDelay(20 * time.Second),
Acceptors: []request.WaiterAcceptor{
{
State: request.SuccessWaiterState,
Matcher: request.PathAllWaiterMatch, Argument: "NetworkInterfaces[].Status",
Expected: "available",
},
{
State: request.FailureWaiterState,
Matcher: request.ErrorWaiterMatch,
Expected: "InvalidNetworkInterfaceID.NotFound",
},
},
Logger: c.Config.Logger,
NewRequest: func(opts []request.Option) (*request.Request, error) {
var inCpy *DescribeNetworkInterfacesInput
if input != nil {
tmp := *input
inCpy = &tmp
}
req, _ := c.DescribeNetworkInterfacesRequest(inCpy)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return req, nil
},
}
w.ApplyOptions(opts...)
return w.WaitWithContext(ctx)
}
// WaitUntilPasswordDataAvailable uses the Amazon EC2 API operation
// GetPasswordData to wait for a condition to be met before returning.
// If the condition is not met within the max attempt window, an error will
// be returned.
func (c *EC2) WaitUntilPasswordDataAvailable(input *GetPasswordDataInput) error {
return c.WaitUntilPasswordDataAvailableWithContext(aws.BackgroundContext(), input)
}
// WaitUntilPasswordDataAvailableWithContext is an extended version of WaitUntilPasswordDataAvailable.
// With the support for passing in a context and options to configure the
// Waiter and the underlying request options.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *EC2) WaitUntilPasswordDataAvailableWithContext(ctx aws.Context, input *GetPasswordDataInput, opts ...request.WaiterOption) error {
w := request.Waiter{
Name: "WaitUntilPasswordDataAvailable",
MaxAttempts: 40,
Delay: request.ConstantWaiterDelay(15 * time.Second),
Acceptors: []request.WaiterAcceptor{
{
State: request.SuccessWaiterState,
Matcher: request.PathWaiterMatch, Argument: "length(PasswordData) > `0`",
Expected: true,
},
},
Logger: c.Config.Logger,
NewRequest: func(opts []request.Option) (*request.Request, error) {
var inCpy *GetPasswordDataInput
if input != nil {
tmp := *input
inCpy = &tmp
}
req, _ := c.GetPasswordDataRequest(inCpy)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return req, nil
},
}
w.ApplyOptions(opts...)
return w.WaitWithContext(ctx)
}
// WaitUntilSnapshotCompleted uses the Amazon EC2 API operation
// DescribeSnapshots to wait for a condition to be met before returning.
// If the condition is not met within the max attempt window, an error will
// be returned.
func (c *EC2) WaitUntilSnapshotCompleted(input *DescribeSnapshotsInput) error {
return c.WaitUntilSnapshotCompletedWithContext(aws.BackgroundContext(), input)
}
// WaitUntilSnapshotCompletedWithContext is an extended version of WaitUntilSnapshotCompleted.
// With the support for passing in a context and options to configure the
// Waiter and the underlying request options.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *EC2) WaitUntilSnapshotCompletedWithContext(ctx aws.Context, input *DescribeSnapshotsInput, opts ...request.WaiterOption) error {
w := request.Waiter{
Name: "WaitUntilSnapshotCompleted",
MaxAttempts: 40,
Delay: request.ConstantWaiterDelay(15 * time.Second),
Acceptors: []request.WaiterAcceptor{
{
State: request.SuccessWaiterState,
Matcher: request.PathAllWaiterMatch, Argument: "Snapshots[].State",
Expected: "completed",
},
},
Logger: c.Config.Logger,
NewRequest: func(opts []request.Option) (*request.Request, error) {
var inCpy *DescribeSnapshotsInput
if input != nil {
tmp := *input
inCpy = &tmp
}
req, _ := c.DescribeSnapshotsRequest(inCpy)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return req, nil
},
}
w.ApplyOptions(opts...)
return w.WaitWithContext(ctx)
}
// WaitUntilSpotInstanceRequestFulfilled uses the Amazon EC2 API operation
// DescribeSpotInstanceRequests to wait for a condition to be met before returning.
// If the condition is not met within the max attempt window, an error will
// be returned.
func (c *EC2) WaitUntilSpotInstanceRequestFulfilled(input *DescribeSpotInstanceRequestsInput) error {
return c.WaitUntilSpotInstanceRequestFulfilledWithContext(aws.BackgroundContext(), input)
}
// WaitUntilSpotInstanceRequestFulfilledWithContext is an extended version of WaitUntilSpotInstanceRequestFulfilled.
// With the support for passing in a context and options to configure the
// Waiter and the underlying request options.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *EC2) WaitUntilSpotInstanceRequestFulfilledWithContext(ctx aws.Context, input *DescribeSpotInstanceRequestsInput, opts ...request.WaiterOption) error {
w := request.Waiter{
Name: "WaitUntilSpotInstanceRequestFulfilled",
MaxAttempts: 40,
Delay: request.ConstantWaiterDelay(15 * time.Second),
Acceptors: []request.WaiterAcceptor{
{
State: request.SuccessWaiterState,
Matcher: request.PathAllWaiterMatch, Argument: "SpotInstanceRequests[].Status.Code",
Expected: "fulfilled",
},
{
State: request.SuccessWaiterState,
Matcher: request.PathAllWaiterMatch, Argument: "SpotInstanceRequests[].Status.Code",
Expected: "request-canceled-and-instance-running",
},
{
State: request.FailureWaiterState,
Matcher: request.PathAnyWaiterMatch, Argument: "SpotInstanceRequests[].Status.Code",
Expected: "schedule-expired",
},
{
State: request.FailureWaiterState,
Matcher: request.PathAnyWaiterMatch, Argument: "SpotInstanceRequests[].Status.Code",
Expected: "canceled-before-fulfillment",
},
{
State: request.FailureWaiterState,
Matcher: request.PathAnyWaiterMatch, Argument: "SpotInstanceRequests[].Status.Code",
Expected: "bad-parameters",
},
{
State: request.FailureWaiterState,
Matcher: request.PathAnyWaiterMatch, Argument: "SpotInstanceRequests[].Status.Code",
Expected: "system-error",
},
{
State: request.RetryWaiterState,
Matcher: request.ErrorWaiterMatch,
Expected: "InvalidSpotInstanceRequestID.NotFound",
},
},
Logger: c.Config.Logger,
NewRequest: func(opts []request.Option) (*request.Request, error) {
var inCpy *DescribeSpotInstanceRequestsInput
if input != nil {
tmp := *input
inCpy = &tmp
}
req, _ := c.DescribeSpotInstanceRequestsRequest(inCpy)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return req, nil
},
}
w.ApplyOptions(opts...)
return w.WaitWithContext(ctx)
}
// WaitUntilSubnetAvailable uses the Amazon EC2 API operation
// DescribeSubnets to wait for a condition to be met before returning.
// If the condition is not met within the max attempt window, an error will
// be returned.
func (c *EC2) WaitUntilSubnetAvailable(input *DescribeSubnetsInput) error {
return c.WaitUntilSubnetAvailableWithContext(aws.BackgroundContext(), input)
}
// WaitUntilSubnetAvailableWithContext is an extended version of WaitUntilSubnetAvailable.
// With the support for passing in a context and options to configure the
// Waiter and the underlying request options.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *EC2) WaitUntilSubnetAvailableWithContext(ctx aws.Context, input *DescribeSubnetsInput, opts ...request.WaiterOption) error {
w := request.Waiter{
Name: "WaitUntilSubnetAvailable",
MaxAttempts: 40,
Delay: request.ConstantWaiterDelay(15 * time.Second),
Acceptors: []request.WaiterAcceptor{
{
State: request.SuccessWaiterState,
Matcher: request.PathAllWaiterMatch, Argument: "Subnets[].State",
Expected: "available",
},
},
Logger: c.Config.Logger,
NewRequest: func(opts []request.Option) (*request.Request, error) {
var inCpy *DescribeSubnetsInput
if input != nil {
tmp := *input
inCpy = &tmp
}
req, _ := c.DescribeSubnetsRequest(inCpy)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return req, nil
},
}
w.ApplyOptions(opts...)
return w.WaitWithContext(ctx)
}
// WaitUntilSystemStatusOk uses the Amazon EC2 API operation
// DescribeInstanceStatus to wait for a condition to be met before returning.
// If the condition is not met within the max attempt window, an error will
// be returned.
func (c *EC2) WaitUntilSystemStatusOk(input *DescribeInstanceStatusInput) error {
return c.WaitUntilSystemStatusOkWithContext(aws.BackgroundContext(), input)
}
// WaitUntilSystemStatusOkWithContext is an extended version of WaitUntilSystemStatusOk.
// With the support for passing in a context and options to configure the
// Waiter and the underlying request options.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *EC2) WaitUntilSystemStatusOkWithContext(ctx aws.Context, input *DescribeInstanceStatusInput, opts ...request.WaiterOption) error {
w := request.Waiter{
Name: "WaitUntilSystemStatusOk",
MaxAttempts: 40,
Delay: request.ConstantWaiterDelay(15 * time.Second),
Acceptors: []request.WaiterAcceptor{
{
State: request.SuccessWaiterState,
Matcher: request.PathAllWaiterMatch, Argument: "InstanceStatuses[].SystemStatus.Status",
Expected: "ok",
},
},
Logger: c.Config.Logger,
NewRequest: func(opts []request.Option) (*request.Request, error) {
var inCpy *DescribeInstanceStatusInput
if input != nil {
tmp := *input
inCpy = &tmp
}
req, _ := c.DescribeInstanceStatusRequest(inCpy)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return req, nil
},
}
w.ApplyOptions(opts...)
return w.WaitWithContext(ctx)
}
// WaitUntilVolumeAvailable uses the Amazon EC2 API operation
// DescribeVolumes to wait for a condition to be met before returning.
// If the condition is not met within the max attempt window, an error will
// be returned.
func (c *EC2) WaitUntilVolumeAvailable(input *DescribeVolumesInput) error {
return c.WaitUntilVolumeAvailableWithContext(aws.BackgroundContext(), input)
}
// WaitUntilVolumeAvailableWithContext is an extended version of WaitUntilVolumeAvailable.
// With the support for passing in a context and options to configure the
// Waiter and the underlying request options.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *EC2) WaitUntilVolumeAvailableWithContext(ctx aws.Context, input *DescribeVolumesInput, opts ...request.WaiterOption) error {
w := request.Waiter{
Name: "WaitUntilVolumeAvailable",
MaxAttempts: 40,
Delay: request.ConstantWaiterDelay(15 * time.Second),
Acceptors: []request.WaiterAcceptor{
{
State: request.SuccessWaiterState,
Matcher: request.PathAllWaiterMatch, Argument: "Volumes[].State",
Expected: "available",
},
{
State: request.FailureWaiterState,
Matcher: request.PathAnyWaiterMatch, Argument: "Volumes[].State",
Expected: "deleted",
},
},
Logger: c.Config.Logger,
NewRequest: func(opts []request.Option) (*request.Request, error) {
var inCpy *DescribeVolumesInput
if input != nil {
tmp := *input
inCpy = &tmp
}
req, _ := c.DescribeVolumesRequest(inCpy)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return req, nil
},
}
w.ApplyOptions(opts...)
return w.WaitWithContext(ctx)
}
// WaitUntilVolumeDeleted uses the Amazon EC2 API operation
// DescribeVolumes to wait for a condition to be met before returning.
// If the condition is not met within the max attempt window, an error will
// be returned.
func (c *EC2) WaitUntilVolumeDeleted(input *DescribeVolumesInput) error {
return c.WaitUntilVolumeDeletedWithContext(aws.BackgroundContext(), input)
}
// WaitUntilVolumeDeletedWithContext is an extended version of WaitUntilVolumeDeleted.
// With the support for passing in a context and options to configure the
// Waiter and the underlying request options.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *EC2) WaitUntilVolumeDeletedWithContext(ctx aws.Context, input *DescribeVolumesInput, opts ...request.WaiterOption) error {
w := request.Waiter{
Name: "WaitUntilVolumeDeleted",
MaxAttempts: 40,
Delay: request.ConstantWaiterDelay(15 * time.Second),
Acceptors: []request.WaiterAcceptor{
{
State: request.SuccessWaiterState,
Matcher: request.PathAllWaiterMatch, Argument: "Volumes[].State",
Expected: "deleted",
},
{
State: request.SuccessWaiterState,
Matcher: request.ErrorWaiterMatch,
Expected: "InvalidVolume.NotFound",
},
},
Logger: c.Config.Logger,
NewRequest: func(opts []request.Option) (*request.Request, error) {
var inCpy *DescribeVolumesInput
if input != nil {
tmp := *input
inCpy = &tmp
}
req, _ := c.DescribeVolumesRequest(inCpy)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return req, nil
},
}
w.ApplyOptions(opts...)
return w.WaitWithContext(ctx)
}
// WaitUntilVolumeInUse uses the Amazon EC2 API operation
// DescribeVolumes to wait for a condition to be met before returning.
// If the condition is not met within the max attempt window, an error will
// be returned.
func (c *EC2) WaitUntilVolumeInUse(input *DescribeVolumesInput) error {
return c.WaitUntilVolumeInUseWithContext(aws.BackgroundContext(), input)
}
// WaitUntilVolumeInUseWithContext is an extended version of WaitUntilVolumeInUse.
// With the support for passing in a context and options to configure the
// Waiter and the underlying request options.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *EC2) WaitUntilVolumeInUseWithContext(ctx aws.Context, input *DescribeVolumesInput, opts ...request.WaiterOption) error {
w := request.Waiter{
Name: "WaitUntilVolumeInUse",
MaxAttempts: 40,
Delay: request.ConstantWaiterDelay(15 * time.Second),
Acceptors: []request.WaiterAcceptor{
{
State: request.SuccessWaiterState,
Matcher: request.PathAllWaiterMatch, Argument: "Volumes[].State",
Expected: "in-use",
},
{
State: request.FailureWaiterState,
Matcher: request.PathAnyWaiterMatch, Argument: "Volumes[].State",
Expected: "deleted",
},
},
Logger: c.Config.Logger,
NewRequest: func(opts []request.Option) (*request.Request, error) {
var inCpy *DescribeVolumesInput
if input != nil {
tmp := *input
inCpy = &tmp
}
req, _ := c.DescribeVolumesRequest(inCpy)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return req, nil
},
}
w.ApplyOptions(opts...)
return w.WaitWithContext(ctx)
}
// WaitUntilVpcAvailable uses the Amazon EC2 API operation
// DescribeVpcs to wait for a condition to be met before returning.
// If the condition is not met within the max attempt window, an error will
// be returned.
func (c *EC2) WaitUntilVpcAvailable(input *DescribeVpcsInput) error {
return c.WaitUntilVpcAvailableWithContext(aws.BackgroundContext(), input)
}
// WaitUntilVpcAvailableWithContext is an extended version of WaitUntilVpcAvailable.
// With the support for passing in a context and options to configure the
// Waiter and the underlying request options.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *EC2) WaitUntilVpcAvailableWithContext(ctx aws.Context, input *DescribeVpcsInput, opts ...request.WaiterOption) error {
w := request.Waiter{
Name: "WaitUntilVpcAvailable",
MaxAttempts: 40,
Delay: request.ConstantWaiterDelay(15 * time.Second),
Acceptors: []request.WaiterAcceptor{
{
State: request.SuccessWaiterState,
Matcher: request.PathAllWaiterMatch, Argument: "Vpcs[].State",
Expected: "available",
},
},
Logger: c.Config.Logger,
NewRequest: func(opts []request.Option) (*request.Request, error) {
var inCpy *DescribeVpcsInput
if input != nil {
tmp := *input
inCpy = &tmp
}
req, _ := c.DescribeVpcsRequest(inCpy)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return req, nil
},
}
w.ApplyOptions(opts...)
return w.WaitWithContext(ctx)
}
// WaitUntilVpcExists uses the Amazon EC2 API operation
// DescribeVpcs to wait for a condition to be met before returning.
// If the condition is not met within the max attempt window, an error will
// be returned.
func (c *EC2) WaitUntilVpcExists(input *DescribeVpcsInput) error {
return c.WaitUntilVpcExistsWithContext(aws.BackgroundContext(), input)
}
// WaitUntilVpcExistsWithContext is an extended version of WaitUntilVpcExists.
// With the support for passing in a context and options to configure the
// Waiter and the underlying request options.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *EC2) WaitUntilVpcExistsWithContext(ctx aws.Context, input *DescribeVpcsInput, opts ...request.WaiterOption) error {
w := request.Waiter{
Name: "WaitUntilVpcExists",
MaxAttempts: 5,
Delay: request.ConstantWaiterDelay(1 * time.Second),
Acceptors: []request.WaiterAcceptor{
{
State: request.SuccessWaiterState,
Matcher: request.StatusWaiterMatch,
Expected: 200,
},
{
State: request.RetryWaiterState,
Matcher: request.ErrorWaiterMatch,
Expected: "InvalidVpcID.NotFound",
},
},
Logger: c.Config.Logger,
NewRequest: func(opts []request.Option) (*request.Request, error) {
var inCpy *DescribeVpcsInput
if input != nil {
tmp := *input
inCpy = &tmp
}
req, _ := c.DescribeVpcsRequest(inCpy)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return req, nil
},
}
w.ApplyOptions(opts...)
return w.WaitWithContext(ctx)
}
// WaitUntilVpcPeeringConnectionDeleted uses the Amazon EC2 API operation
// DescribeVpcPeeringConnections to wait for a condition to be met before returning.
// If the condition is not met within the max attempt window, an error will
// be returned.
func (c *EC2) WaitUntilVpcPeeringConnectionDeleted(input *DescribeVpcPeeringConnectionsInput) error {
return c.WaitUntilVpcPeeringConnectionDeletedWithContext(aws.BackgroundContext(), input)
}
// WaitUntilVpcPeeringConnectionDeletedWithContext is an extended version of WaitUntilVpcPeeringConnectionDeleted.
// With the support for passing in a context and options to configure the
// Waiter and the underlying request options.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *EC2) WaitUntilVpcPeeringConnectionDeletedWithContext(ctx aws.Context, input *DescribeVpcPeeringConnectionsInput, opts ...request.WaiterOption) error {
w := request.Waiter{
Name: "WaitUntilVpcPeeringConnectionDeleted",
MaxAttempts: 40,
Delay: request.ConstantWaiterDelay(15 * time.Second),
Acceptors: []request.WaiterAcceptor{
{
State: request.SuccessWaiterState,
Matcher: request.PathAllWaiterMatch, Argument: "VpcPeeringConnections[].Status.Code",
Expected: "deleted",
},
{
State: request.SuccessWaiterState,
Matcher: request.ErrorWaiterMatch,
Expected: "InvalidVpcPeeringConnectionID.NotFound",
},
},
Logger: c.Config.Logger,
NewRequest: func(opts []request.Option) (*request.Request, error) {
var inCpy *DescribeVpcPeeringConnectionsInput
if input != nil {
tmp := *input
inCpy = &tmp
}
req, _ := c.DescribeVpcPeeringConnectionsRequest(inCpy)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return req, nil
},
}
w.ApplyOptions(opts...)
return w.WaitWithContext(ctx)
}
// WaitUntilVpcPeeringConnectionExists uses the Amazon EC2 API operation
// DescribeVpcPeeringConnections to wait for a condition to be met before returning.
// If the condition is not met within the max attempt window, an error will
// be returned.
func (c *EC2) WaitUntilVpcPeeringConnectionExists(input *DescribeVpcPeeringConnectionsInput) error {
return c.WaitUntilVpcPeeringConnectionExistsWithContext(aws.BackgroundContext(), input)
}
// WaitUntilVpcPeeringConnectionExistsWithContext is an extended version of WaitUntilVpcPeeringConnectionExists.
// With the support for passing in a context and options to configure the
// Waiter and the underlying request options.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *EC2) WaitUntilVpcPeeringConnectionExistsWithContext(ctx aws.Context, input *DescribeVpcPeeringConnectionsInput, opts ...request.WaiterOption) error {
w := request.Waiter{
Name: "WaitUntilVpcPeeringConnectionExists",
MaxAttempts: 40,
Delay: request.ConstantWaiterDelay(15 * time.Second),
Acceptors: []request.WaiterAcceptor{
{
State: request.SuccessWaiterState,
Matcher: request.StatusWaiterMatch,
Expected: 200,
},
{
State: request.RetryWaiterState,
Matcher: request.ErrorWaiterMatch,
Expected: "InvalidVpcPeeringConnectionID.NotFound",
},
},
Logger: c.Config.Logger,
NewRequest: func(opts []request.Option) (*request.Request, error) {
var inCpy *DescribeVpcPeeringConnectionsInput
if input != nil {
tmp := *input
inCpy = &tmp
}
req, _ := c.DescribeVpcPeeringConnectionsRequest(inCpy)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return req, nil
},
}
w.ApplyOptions(opts...)
return w.WaitWithContext(ctx)
}
// WaitUntilVpnConnectionAvailable uses the Amazon EC2 API operation
// DescribeVpnConnections to wait for a condition to be met before returning.
// If the condition is not met within the max attempt window, an error will
// be returned.
func (c *EC2) WaitUntilVpnConnectionAvailable(input *DescribeVpnConnectionsInput) error {
return c.WaitUntilVpnConnectionAvailableWithContext(aws.BackgroundContext(), input)
}
// WaitUntilVpnConnectionAvailableWithContext is an extended version of WaitUntilVpnConnectionAvailable.
// With the support for passing in a context and options to configure the
// Waiter and the underlying request options.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *EC2) WaitUntilVpnConnectionAvailableWithContext(ctx aws.Context, input *DescribeVpnConnectionsInput, opts ...request.WaiterOption) error {
w := request.Waiter{
Name: "WaitUntilVpnConnectionAvailable",
MaxAttempts: 40,
Delay: request.ConstantWaiterDelay(15 * time.Second),
Acceptors: []request.WaiterAcceptor{
{
State: request.SuccessWaiterState,
Matcher: request.PathAllWaiterMatch, Argument: "VpnConnections[].State",
Expected: "available",
},
{
State: request.FailureWaiterState,
Matcher: request.PathAnyWaiterMatch, Argument: "VpnConnections[].State",
Expected: "deleting",
},
{
State: request.FailureWaiterState,
Matcher: request.PathAnyWaiterMatch, Argument: "VpnConnections[].State",
Expected: "deleted",
},
},
Logger: c.Config.Logger,
NewRequest: func(opts []request.Option) (*request.Request, error) {
var inCpy *DescribeVpnConnectionsInput
if input != nil {
tmp := *input
inCpy = &tmp
}
req, _ := c.DescribeVpnConnectionsRequest(inCpy)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return req, nil
},
}
w.ApplyOptions(opts...)
return w.WaitWithContext(ctx)
}
// WaitUntilVpnConnectionDeleted uses the Amazon EC2 API operation
// DescribeVpnConnections to wait for a condition to be met before returning.
// If the condition is not met within the max attempt window, an error will
// be returned.
func (c *EC2) WaitUntilVpnConnectionDeleted(input *DescribeVpnConnectionsInput) error {
return c.WaitUntilVpnConnectionDeletedWithContext(aws.BackgroundContext(), input)
}
// WaitUntilVpnConnectionDeletedWithContext is an extended version of WaitUntilVpnConnectionDeleted.
// With the support for passing in a context and options to configure the
// Waiter and the underlying request options.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *EC2) WaitUntilVpnConnectionDeletedWithContext(ctx aws.Context, input *DescribeVpnConnectionsInput, opts ...request.WaiterOption) error {
w := request.Waiter{
Name: "WaitUntilVpnConnectionDeleted",
MaxAttempts: 40,
Delay: request.ConstantWaiterDelay(15 * time.Second),
Acceptors: []request.WaiterAcceptor{
{
State: request.SuccessWaiterState,
Matcher: request.PathAllWaiterMatch, Argument: "VpnConnections[].State",
Expected: "deleted",
},
{
State: request.FailureWaiterState,
Matcher: request.PathAnyWaiterMatch, Argument: "VpnConnections[].State",
Expected: "pending",
},
},
Logger: c.Config.Logger,
NewRequest: func(opts []request.Option) (*request.Request, error) {
var inCpy *DescribeVpnConnectionsInput
if input != nil {
tmp := *input
inCpy = &tmp
}
req, _ := c.DescribeVpnConnectionsRequest(inCpy)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return req, nil
},
}
w.ApplyOptions(opts...)
return w.WaitWithContext(ctx)
}
| vendor/github.com/aws/aws-sdk-go/service/ec2/waiters.go | 0 | https://github.com/grafana/grafana/commit/98e1404fed0a1cab9cdc6f7404d805459f374f48 | [
0.0004805001080967486,
0.00018002180149778724,
0.00016062421491369605,
0.00017188674246426672,
0.0000382894286303781
] |
{
"id": 4,
"code_window": [
" }\n",
"\n",
" setRelativeFilter(timespan) {\n",
" var range = { from: timespan.from, to: timespan.to };\n",
"\n",
" if (this.panel.nowDelay && range.to === 'now') {\n",
" range.to = 'now-' + this.panel.nowDelay;\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" this.$rootScope.appEvent('escTimepicker');\n"
],
"file_path": "public/app/features/dashboard/timepicker/timepicker.ts",
"type": "add",
"edit_start_line_idx": 141
} | // +build ignore
// Generate the table of OID values
// Run with 'go run gen.go'.
package main
import (
"database/sql"
"fmt"
"log"
"os"
"os/exec"
"strings"
_ "github.com/lib/pq"
)
// OID represent a postgres Object Identifier Type.
type OID struct {
ID int
Type string
}
// Name returns an upper case version of the oid type.
func (o OID) Name() string {
return strings.ToUpper(o.Type)
}
func main() {
datname := os.Getenv("PGDATABASE")
sslmode := os.Getenv("PGSSLMODE")
if datname == "" {
os.Setenv("PGDATABASE", "pqgotest")
}
if sslmode == "" {
os.Setenv("PGSSLMODE", "disable")
}
db, err := sql.Open("postgres", "")
if err != nil {
log.Fatal(err)
}
rows, err := db.Query(`
SELECT typname, oid
FROM pg_type WHERE oid < 10000
ORDER BY oid;
`)
if err != nil {
log.Fatal(err)
}
oids := make([]*OID, 0)
for rows.Next() {
var oid OID
if err = rows.Scan(&oid.Type, &oid.ID); err != nil {
log.Fatal(err)
}
oids = append(oids, &oid)
}
if err = rows.Err(); err != nil {
log.Fatal(err)
}
cmd := exec.Command("gofmt")
cmd.Stderr = os.Stderr
w, err := cmd.StdinPipe()
if err != nil {
log.Fatal(err)
}
f, err := os.Create("types.go")
if err != nil {
log.Fatal(err)
}
cmd.Stdout = f
err = cmd.Start()
if err != nil {
log.Fatal(err)
}
fmt.Fprintln(w, "// Code generated by gen.go. DO NOT EDIT.")
fmt.Fprintln(w, "\npackage oid")
fmt.Fprintln(w, "const (")
for _, oid := range oids {
fmt.Fprintf(w, "T_%s Oid = %d\n", oid.Type, oid.ID)
}
fmt.Fprintln(w, ")")
fmt.Fprintln(w, "var TypeName = map[Oid]string{")
for _, oid := range oids {
fmt.Fprintf(w, "T_%s: \"%s\",\n", oid.Type, oid.Name())
}
fmt.Fprintln(w, "}")
w.Close()
cmd.Wait()
}
| vendor/github.com/lib/pq/oid/gen.go | 0 | https://github.com/grafana/grafana/commit/98e1404fed0a1cab9cdc6f7404d805459f374f48 | [
0.00017633037350606173,
0.00017131035565398633,
0.00016721163410693407,
0.00016953100566752255,
0.000003205434722985956
] |
{
"id": 4,
"code_window": [
" }\n",
"\n",
" setRelativeFilter(timespan) {\n",
" var range = { from: timespan.from, to: timespan.to };\n",
"\n",
" if (this.panel.nowDelay && range.to === 'now') {\n",
" range.to = 'now-' + this.panel.nowDelay;\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" this.$rootScope.appEvent('escTimepicker');\n"
],
"file_path": "public/app/features/dashboard/timepicker/timepicker.ts",
"type": "add",
"edit_start_line_idx": 141
} | package testdata
import (
"encoding/json"
"math/rand"
"strconv"
"strings"
"time"
"github.com/grafana/grafana/pkg/components/null"
"github.com/grafana/grafana/pkg/log"
"github.com/grafana/grafana/pkg/tsdb"
)
type ScenarioHandler func(query *tsdb.Query, context *tsdb.TsdbQuery) *tsdb.QueryResult
type Scenario struct {
Id string `json:"id"`
Name string `json:"name"`
StringInput string `json:"stringOption"`
Description string `json:"description"`
Handler ScenarioHandler `json:"-"`
}
var ScenarioRegistry map[string]*Scenario
func init() {
ScenarioRegistry = make(map[string]*Scenario)
logger := log.New("tsdb.testdata")
logger.Debug("Initializing TestData Scenario")
registerScenario(&Scenario{
Id: "exponential_heatmap_bucket_data",
Name: "Exponential heatmap bucket data",
Handler: func(query *tsdb.Query, context *tsdb.TsdbQuery) *tsdb.QueryResult {
to := context.TimeRange.GetToAsMsEpoch()
var series []*tsdb.TimeSeries
start := 1
factor := 2
for i := 0; i < 10; i++ {
timeWalkerMs := context.TimeRange.GetFromAsMsEpoch()
serie := &tsdb.TimeSeries{Name: strconv.Itoa(start)}
start *= factor
points := make(tsdb.TimeSeriesPoints, 0)
for j := int64(0); j < 100 && timeWalkerMs < to; j++ {
v := float64(rand.Int63n(100))
points = append(points, tsdb.NewTimePoint(null.FloatFrom(v), float64(timeWalkerMs)))
timeWalkerMs += query.IntervalMs * 50
}
serie.Points = points
series = append(series, serie)
}
queryRes := tsdb.NewQueryResult()
queryRes.Series = append(queryRes.Series, series...)
return queryRes
},
})
registerScenario(&Scenario{
Id: "linear_heatmap_bucket_data",
Name: "Linear heatmap bucket data",
Handler: func(query *tsdb.Query, context *tsdb.TsdbQuery) *tsdb.QueryResult {
to := context.TimeRange.GetToAsMsEpoch()
var series []*tsdb.TimeSeries
for i := 0; i < 10; i++ {
timeWalkerMs := context.TimeRange.GetFromAsMsEpoch()
serie := &tsdb.TimeSeries{Name: strconv.Itoa(i * 10)}
points := make(tsdb.TimeSeriesPoints, 0)
for j := int64(0); j < 100 && timeWalkerMs < to; j++ {
v := float64(rand.Int63n(100))
points = append(points, tsdb.NewTimePoint(null.FloatFrom(v), float64(timeWalkerMs)))
timeWalkerMs += query.IntervalMs * 50
}
serie.Points = points
series = append(series, serie)
}
queryRes := tsdb.NewQueryResult()
queryRes.Series = append(queryRes.Series, series...)
return queryRes
},
})
registerScenario(&Scenario{
Id: "random_walk",
Name: "Random Walk",
Handler: func(query *tsdb.Query, tsdbQuery *tsdb.TsdbQuery) *tsdb.QueryResult {
timeWalkerMs := tsdbQuery.TimeRange.GetFromAsMsEpoch()
to := tsdbQuery.TimeRange.GetToAsMsEpoch()
series := newSeriesForQuery(query)
points := make(tsdb.TimeSeriesPoints, 0)
walker := rand.Float64() * 100
for i := int64(0); i < 10000 && timeWalkerMs < to; i++ {
points = append(points, tsdb.NewTimePoint(null.FloatFrom(walker), float64(timeWalkerMs)))
walker += rand.Float64() - 0.5
timeWalkerMs += query.IntervalMs
}
series.Points = points
queryRes := tsdb.NewQueryResult()
queryRes.Series = append(queryRes.Series, series)
return queryRes
},
})
registerScenario(&Scenario{
Id: "no_data_points",
Name: "No Data Points",
Handler: func(query *tsdb.Query, context *tsdb.TsdbQuery) *tsdb.QueryResult {
return tsdb.NewQueryResult()
},
})
registerScenario(&Scenario{
Id: "datapoints_outside_range",
Name: "Datapoints Outside Range",
Handler: func(query *tsdb.Query, context *tsdb.TsdbQuery) *tsdb.QueryResult {
queryRes := tsdb.NewQueryResult()
series := newSeriesForQuery(query)
outsideTime := context.TimeRange.MustGetFrom().Add(-1*time.Hour).Unix() * 1000
series.Points = append(series.Points, tsdb.NewTimePoint(null.FloatFrom(10), float64(outsideTime)))
queryRes.Series = append(queryRes.Series, series)
return queryRes
},
})
registerScenario(&Scenario{
Id: "manual_entry",
Name: "Manual Entry",
Handler: func(query *tsdb.Query, context *tsdb.TsdbQuery) *tsdb.QueryResult {
queryRes := tsdb.NewQueryResult()
points := query.Model.Get("points").MustArray()
series := newSeriesForQuery(query)
startTime := context.TimeRange.GetFromAsMsEpoch()
endTime := context.TimeRange.GetToAsMsEpoch()
for _, val := range points {
pointValues := val.([]interface{})
var value null.Float
var time int64
if valueFloat, err := strconv.ParseFloat(string(pointValues[0].(json.Number)), 64); err == nil {
value = null.FloatFrom(valueFloat)
}
if timeInt, err := strconv.ParseInt(string(pointValues[1].(json.Number)), 10, 64); err != nil {
continue
} else {
time = timeInt
}
if time >= startTime && time <= endTime {
series.Points = append(series.Points, tsdb.NewTimePoint(value, float64(time)))
}
}
queryRes.Series = append(queryRes.Series, series)
return queryRes
},
})
registerScenario(&Scenario{
Id: "csv_metric_values",
Name: "CSV Metric Values",
StringInput: "1,20,90,30,5,0",
Handler: func(query *tsdb.Query, context *tsdb.TsdbQuery) *tsdb.QueryResult {
queryRes := tsdb.NewQueryResult()
stringInput := query.Model.Get("stringInput").MustString()
stringInput = strings.Replace(stringInput, " ", "", -1)
values := []null.Float{}
for _, strVal := range strings.Split(stringInput, ",") {
if strVal == "null" {
values = append(values, null.FloatFromPtr(nil))
}
if val, err := strconv.ParseFloat(strVal, 64); err == nil {
values = append(values, null.FloatFrom(val))
}
}
if len(values) == 0 {
return queryRes
}
series := newSeriesForQuery(query)
startTime := context.TimeRange.GetFromAsMsEpoch()
endTime := context.TimeRange.GetToAsMsEpoch()
step := (endTime - startTime) / int64(len(values)-1)
for _, val := range values {
series.Points = append(series.Points, tsdb.TimePoint{val, null.FloatFrom(float64(startTime))})
startTime += step
}
queryRes.Series = append(queryRes.Series, series)
return queryRes
},
})
}
func registerScenario(scenario *Scenario) {
ScenarioRegistry[scenario.Id] = scenario
}
func newSeriesForQuery(query *tsdb.Query) *tsdb.TimeSeries {
alias := query.Model.Get("alias").MustString("")
if alias == "" {
alias = query.RefId + "-series"
}
return &tsdb.TimeSeries{Name: alias}
}
| pkg/tsdb/testdata/scenarios.go | 0 | https://github.com/grafana/grafana/commit/98e1404fed0a1cab9cdc6f7404d805459f374f48 | [
0.004436535760760307,
0.0005545523017644882,
0.0001666337193455547,
0.00017153742373920977,
0.0010691445786505938
] |
{
"id": 0,
"code_window": [
"\n",
"\tlogger.Debug(\"Saving alert states\", \"count\", len(states))\n",
"\tinstances := make([]ngModels.AlertInstance, 0, len(states))\n",
"\n",
"\tfor _, s := range states {\n",
"\t\tlabels := ngModels.InstanceLabels(s.Labels)\n",
"\t\t_, hash, err := labels.StringAndHash()\n",
"\t\tif err != nil {\n",
"\t\t\tlogger.Error(\"Failed to create a key for alert state to save it to database. The state will be ignored \", \"cacheID\", s.CacheID, \"error\", err)\n",
"\t\t\tcontinue\n",
"\t\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tkey, err := s.GetAlertInstanceKey()\n"
],
"file_path": "pkg/services/ngalert/state/manager.go",
"type": "replace",
"edit_start_line_idx": 293
} | package state
import (
"context"
"net/url"
"time"
"github.com/benbjohnson/clock"
"github.com/grafana/grafana-plugin-sdk-go/data"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/services/ngalert/eval"
"github.com/grafana/grafana/pkg/services/ngalert/image"
"github.com/grafana/grafana/pkg/services/ngalert/metrics"
ngModels "github.com/grafana/grafana/pkg/services/ngalert/models"
)
var (
ResendDelay = 30 * time.Second
MetricsScrapeInterval = 15 * time.Second // TODO: parameterize? // Setting to a reasonable default scrape interval for Prometheus.
)
// AlertInstanceManager defines the interface for querying the current alert instances.
type AlertInstanceManager interface {
GetAll(orgID int64) []*State
GetStatesForRuleUID(orgID int64, alertRuleUID string) []*State
}
type Manager struct {
log log.Logger
metrics *metrics.State
clock clock.Clock
cache *cache
ResendDelay time.Duration
instanceStore InstanceStore
imageService image.ImageService
historian Historian
externalURL *url.URL
}
func NewManager(metrics *metrics.State, externalURL *url.URL, instanceStore InstanceStore, imageService image.ImageService, clock clock.Clock, historian Historian) *Manager {
return &Manager{
cache: newCache(),
ResendDelay: ResendDelay, // TODO: make this configurable
log: log.New("ngalert.state.manager"),
metrics: metrics,
instanceStore: instanceStore,
imageService: imageService,
historian: historian,
clock: clock,
externalURL: externalURL,
}
}
func (st *Manager) Run(ctx context.Context) error {
ticker := st.clock.Ticker(MetricsScrapeInterval)
for {
select {
case <-ticker.C:
st.log.Debug("Recording state cache metrics", "now", st.clock.Now())
st.cache.recordMetrics(st.metrics)
case <-ctx.Done():
st.log.Debug("Stopping")
ticker.Stop()
return ctx.Err()
}
}
}
func (st *Manager) Warm(ctx context.Context, rulesReader RuleReader) {
if st.instanceStore == nil {
st.log.Info("Skip warming the state because instance store is not configured")
return
}
startTime := time.Now()
st.log.Info("Warming state cache for startup")
orgIds, err := st.instanceStore.FetchOrgIds(ctx)
if err != nil {
st.log.Error("Unable to fetch orgIds", "error", err)
}
statesCount := 0
states := make(map[int64]map[string]*ruleStates, len(orgIds))
for _, orgId := range orgIds {
// Get Rules
ruleCmd := ngModels.ListAlertRulesQuery{
OrgID: orgId,
}
if err := rulesReader.ListAlertRules(ctx, &ruleCmd); err != nil {
st.log.Error("Unable to fetch previous state", "error", err)
}
ruleByUID := make(map[string]*ngModels.AlertRule, len(ruleCmd.Result))
for _, rule := range ruleCmd.Result {
ruleByUID[rule.UID] = rule
}
orgStates := make(map[string]*ruleStates, len(ruleByUID))
states[orgId] = orgStates
// Get Instances
cmd := ngModels.ListAlertInstancesQuery{
RuleOrgID: orgId,
}
if err := st.instanceStore.ListAlertInstances(ctx, &cmd); err != nil {
st.log.Error("Unable to fetch previous state", "error", err)
}
for _, entry := range cmd.Result {
ruleForEntry, ok := ruleByUID[entry.RuleUID]
if !ok {
// TODO Should we delete the orphaned state from the db?
continue
}
rulesStates, ok := orgStates[entry.RuleUID]
if !ok {
rulesStates = &ruleStates{states: make(map[string]*State)}
orgStates[entry.RuleUID] = rulesStates
}
lbs := map[string]string(entry.Labels)
cacheID, err := entry.Labels.StringKey()
if err != nil {
st.log.Error("Error getting cacheId for entry", "error", err)
}
rulesStates.states[cacheID] = &State{
AlertRuleUID: entry.RuleUID,
OrgID: entry.RuleOrgID,
CacheID: cacheID,
Labels: lbs,
State: translateInstanceState(entry.CurrentState),
StateReason: entry.CurrentReason,
LastEvaluationString: "",
StartsAt: entry.CurrentStateSince,
EndsAt: entry.CurrentStateEnd,
LastEvaluationTime: entry.LastEvalTime,
Annotations: ruleForEntry.Annotations,
}
statesCount++
}
}
st.cache.setAllStates(states)
st.log.Info("State cache has been initialized", "states", statesCount, "duration", time.Since(startTime))
}
func (st *Manager) Get(orgID int64, alertRuleUID, stateId string) *State {
return st.cache.get(orgID, alertRuleUID, stateId)
}
// ResetStateByRuleUID deletes all entries in the state manager that match the given rule UID.
func (st *Manager) ResetStateByRuleUID(ctx context.Context, ruleKey ngModels.AlertRuleKey) []*State {
logger := st.log.New(ruleKey.LogContext()...)
logger.Debug("Resetting state of the rule")
states := st.cache.removeByRuleUID(ruleKey.OrgID, ruleKey.UID)
if len(states) > 0 && st.instanceStore != nil {
err := st.instanceStore.DeleteAlertInstancesByRule(ctx, ruleKey)
if err != nil {
logger.Error("Failed to delete states that belong to a rule from database", "error", err)
}
}
logger.Info("Rules state was reset", "states", len(states))
return states
}
// ProcessEvalResults updates the current states that belong to a rule with the evaluation results.
// if extraLabels is not empty, those labels will be added to every state. The extraLabels take precedence over rule labels and result labels
func (st *Manager) ProcessEvalResults(ctx context.Context, evaluatedAt time.Time, alertRule *ngModels.AlertRule, results eval.Results, extraLabels data.Labels) []*State {
logger := st.log.FromContext(ctx)
logger.Debug("State manager processing evaluation results", "resultCount", len(results))
var states []StateTransition
processedResults := make(map[string]*State, len(results))
for _, result := range results {
s := st.setNextState(ctx, alertRule, result, extraLabels, logger)
states = append(states, s)
processedResults[s.State.CacheID] = s.State
}
resolvedStates := st.staleResultsHandler(ctx, evaluatedAt, alertRule, processedResults, logger)
st.saveAlertStates(ctx, logger, states...)
changedStates := make([]StateTransition, 0, len(states))
for _, s := range states {
if s.changed() {
changedStates = append(changedStates, s)
}
}
if st.historian != nil {
st.historian.RecordStates(ctx, alertRule, changedStates)
}
deltas := append(states, resolvedStates...)
nextStates := make([]*State, 0, len(states))
for _, s := range deltas {
nextStates = append(nextStates, s.State)
}
return nextStates
}
// Set the current state based on evaluation results
func (st *Manager) setNextState(ctx context.Context, alertRule *ngModels.AlertRule, result eval.Result, extraLabels data.Labels, logger log.Logger) StateTransition {
currentState := st.cache.getOrCreate(ctx, st.log, alertRule, result, extraLabels, st.externalURL)
currentState.LastEvaluationTime = result.EvaluatedAt
currentState.EvaluationDuration = result.EvaluationDuration
currentState.Results = append(currentState.Results, Evaluation{
EvaluationTime: result.EvaluatedAt,
EvaluationState: result.State,
Values: NewEvaluationValues(result.Values),
Condition: alertRule.Condition,
})
currentState.LastEvaluationString = result.EvaluationString
currentState.TrimResults(alertRule)
oldState := currentState.State
oldReason := currentState.StateReason
logger.Debug("Setting alert state")
switch result.State {
case eval.Normal:
currentState.resultNormal(alertRule, result)
case eval.Alerting:
currentState.resultAlerting(alertRule, result)
case eval.Error:
currentState.resultError(alertRule, result)
case eval.NoData:
currentState.resultNoData(alertRule, result)
case eval.Pending: // we do not emit results with this state
}
// Set reason iff: result is different than state, reason is not Alerting or Normal
currentState.StateReason = ""
if currentState.State != result.State &&
result.State != eval.Normal &&
result.State != eval.Alerting {
currentState.StateReason = result.State.String()
}
// Set Resolved property so the scheduler knows to send a postable alert
// to Alertmanager.
currentState.Resolved = oldState == eval.Alerting && currentState.State == eval.Normal
if shouldTakeImage(currentState.State, oldState, currentState.Image, currentState.Resolved) {
image, err := takeImage(ctx, st.imageService, alertRule)
if err != nil {
logger.Warn("Failed to take an image",
"dashboard", alertRule.DashboardUID,
"panel", alertRule.PanelID,
"error", err)
} else if image != nil {
currentState.Image = image
}
}
st.cache.set(currentState)
nextState := StateTransition{
State: currentState,
PreviousState: oldState,
PreviousStateReason: oldReason,
}
return nextState
}
func (st *Manager) GetAll(orgID int64) []*State {
return st.cache.getAll(orgID)
}
func (st *Manager) GetStatesForRuleUID(orgID int64, alertRuleUID string) []*State {
return st.cache.getStatesForRuleUID(orgID, alertRuleUID)
}
func (st *Manager) Put(states []*State) {
for _, s := range states {
st.cache.set(s)
}
}
// TODO: Is the `State` type necessary? Should it embed the instance?
func (st *Manager) saveAlertStates(ctx context.Context, logger log.Logger, states ...StateTransition) {
if st.instanceStore == nil {
return
}
logger.Debug("Saving alert states", "count", len(states))
instances := make([]ngModels.AlertInstance, 0, len(states))
for _, s := range states {
labels := ngModels.InstanceLabels(s.Labels)
_, hash, err := labels.StringAndHash()
if err != nil {
logger.Error("Failed to create a key for alert state to save it to database. The state will be ignored ", "cacheID", s.CacheID, "error", err)
continue
}
fields := ngModels.AlertInstance{
AlertInstanceKey: ngModels.AlertInstanceKey{
RuleOrgID: s.OrgID,
RuleUID: s.AlertRuleUID,
LabelsHash: hash,
},
Labels: ngModels.InstanceLabels(s.Labels),
CurrentState: ngModels.InstanceStateType(s.State.State.String()),
CurrentReason: s.StateReason,
LastEvalTime: s.LastEvaluationTime,
CurrentStateSince: s.StartsAt,
CurrentStateEnd: s.EndsAt,
}
instances = append(instances, fields)
}
if err := st.instanceStore.SaveAlertInstances(ctx, instances...); err != nil {
type debugInfo struct {
State string
Labels string
}
debug := make([]debugInfo, 0)
for _, inst := range instances {
debug = append(debug, debugInfo{string(inst.CurrentState), data.Labels(inst.Labels).String()})
}
logger.Error("Failed to save alert states", "states", debug, "error", err)
}
}
// TODO: why wouldn't you allow other types like NoData or Error?
func translateInstanceState(state ngModels.InstanceStateType) eval.State {
switch {
case state == ngModels.InstanceStateFiring:
return eval.Alerting
case state == ngModels.InstanceStateNormal:
return eval.Normal
default:
return eval.Error
}
}
func (st *Manager) staleResultsHandler(ctx context.Context, evaluatedAt time.Time, alertRule *ngModels.AlertRule, states map[string]*State, logger log.Logger) []StateTransition {
// If we are removing two or more stale series it makes sense to share the resolved image as the alert rule is the same.
// TODO: We will need to change this when we support images without screenshots as each series will have a different image
var resolvedImage *ngModels.Image
var resolvedStates []StateTransition
allStates := st.GetStatesForRuleUID(alertRule.OrgID, alertRule.UID)
toDelete := make([]ngModels.AlertInstanceKey, 0)
for _, s := range allStates {
// Is the cached state in our recently processed results? If not, is it stale?
if _, ok := states[s.CacheID]; !ok && stateIsStale(evaluatedAt, s.LastEvaluationTime, alertRule.IntervalSeconds) {
logger.Info("Removing stale state entry", "cacheID", s.CacheID, "state", s.State, "reason", s.StateReason)
st.cache.deleteEntry(s.OrgID, s.AlertRuleUID, s.CacheID)
ilbs := ngModels.InstanceLabels(s.Labels)
_, labelsHash, err := ilbs.StringAndHash()
if err != nil {
logger.Error("Unable to get labelsHash", "error", err.Error(), s.AlertRuleUID)
}
toDelete = append(toDelete, ngModels.AlertInstanceKey{RuleOrgID: s.OrgID, RuleUID: s.AlertRuleUID, LabelsHash: labelsHash})
if s.State == eval.Alerting {
oldState := s.State
oldReason := s.StateReason
s.State = eval.Normal
s.StateReason = ngModels.StateReasonMissingSeries
s.EndsAt = evaluatedAt
s.Resolved = true
s.LastEvaluationTime = evaluatedAt
record := StateTransition{
State: s,
PreviousState: oldState,
PreviousStateReason: oldReason,
}
// If there is no resolved image for this rule then take one
if resolvedImage == nil {
image, err := takeImage(ctx, st.imageService, alertRule)
if err != nil {
logger.Warn("Failed to take an image",
"dashboard", alertRule.DashboardUID,
"panel", alertRule.PanelID,
"error", err)
} else if image != nil {
resolvedImage = image
}
}
s.Image = resolvedImage
resolvedStates = append(resolvedStates, record)
}
}
}
if st.historian != nil {
st.historian.RecordStates(ctx, alertRule, resolvedStates)
}
if st.instanceStore != nil {
if err := st.instanceStore.DeleteAlertInstances(ctx, toDelete...); err != nil {
logger.Error("Unable to delete stale instances from database", "error", err, "count", len(toDelete))
}
}
return resolvedStates
}
func stateIsStale(evaluatedAt time.Time, lastEval time.Time, intervalSeconds int64) bool {
return !lastEval.Add(2 * time.Duration(intervalSeconds) * time.Second).After(evaluatedAt)
}
| pkg/services/ngalert/state/manager.go | 1 | https://github.com/grafana/grafana/commit/623de12e354c8f92fd49802a04bafe5970fba0e9 | [
0.9982618689537048,
0.2630840837955475,
0.00016194941417779773,
0.0028584469109773636,
0.40947800874710083
] |
{
"id": 0,
"code_window": [
"\n",
"\tlogger.Debug(\"Saving alert states\", \"count\", len(states))\n",
"\tinstances := make([]ngModels.AlertInstance, 0, len(states))\n",
"\n",
"\tfor _, s := range states {\n",
"\t\tlabels := ngModels.InstanceLabels(s.Labels)\n",
"\t\t_, hash, err := labels.StringAndHash()\n",
"\t\tif err != nil {\n",
"\t\t\tlogger.Error(\"Failed to create a key for alert state to save it to database. The state will be ignored \", \"cacheID\", s.CacheID, \"error\", err)\n",
"\t\t\tcontinue\n",
"\t\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tkey, err := s.GetAlertInstanceKey()\n"
],
"file_path": "pkg/services/ngalert/state/manager.go",
"type": "replace",
"edit_start_line_idx": 293
} | import { render, screen, within } from '@testing-library/react';
import React from 'react';
import { ConfirmModal } from './ConfirmModal';
describe('ConfirmModal', () => {
it('should render correct title, body, dismiss-, alternative- and confirm-text', () => {
render(
<ConfirmModal
title="Some Title"
body="Some Body"
confirmText="Please Confirm"
alternativeText="Alternative Text"
dismissText="Dismiss Text"
isOpen={true}
onConfirm={() => {}}
onDismiss={() => {}}
onAlternative={() => {}}
/>
);
expect(screen.getByRole('heading', { name: 'Some Title' })).toBeInTheDocument();
expect(screen.getByText('Some Body')).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Dismiss Text' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Alternative Text' })).toBeInTheDocument();
const button = screen.getByRole('button', { name: 'Confirm Modal Danger Button' });
expect(within(button).getByText('Please Confirm')).toBeInTheDocument();
});
it('should render nothing when isOpen is false', () => {
render(
<ConfirmModal
title="Some Title"
body="Some Body"
confirmText="Confirm"
isOpen={false}
onConfirm={() => {}}
onDismiss={() => {}}
/>
);
expect(screen.queryByRole('heading', { name: 'Some Title' })).not.toBeInTheDocument();
expect(screen.queryByText('Some Body')).not.toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'Dismiss Text' })).not.toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'Alternative Text' })).not.toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'Confirm Modal Danger Button' })).not.toBeInTheDocument();
});
});
| packages/grafana-ui/src/components/ConfirmModal/ConfirmModal.test.tsx | 0 | https://github.com/grafana/grafana/commit/623de12e354c8f92fd49802a04bafe5970fba0e9 | [
0.00017871208547148854,
0.0001779336016625166,
0.00017653476970735937,
0.00017807117546908557,
7.635948691131489e-7
] |
{
"id": 0,
"code_window": [
"\n",
"\tlogger.Debug(\"Saving alert states\", \"count\", len(states))\n",
"\tinstances := make([]ngModels.AlertInstance, 0, len(states))\n",
"\n",
"\tfor _, s := range states {\n",
"\t\tlabels := ngModels.InstanceLabels(s.Labels)\n",
"\t\t_, hash, err := labels.StringAndHash()\n",
"\t\tif err != nil {\n",
"\t\t\tlogger.Error(\"Failed to create a key for alert state to save it to database. The state will be ignored \", \"cacheID\", s.CacheID, \"error\", err)\n",
"\t\t\tcontinue\n",
"\t\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tkey, err := s.GetAlertInstanceKey()\n"
],
"file_path": "pkg/services/ngalert/state/manager.go",
"type": "replace",
"edit_start_line_idx": 293
} | {
"tables": [
{
"name": "PrimaryResult",
"columns": [
{
"name": "TimeGenerated",
"type": "datetime"
},
{
"name": "avg_CounterValue",
"type": "int"
}
],
"rows": [
[
"2020-04-19T19:16:06.5Z",
1
],
[
"2020-04-19T19:16:16.5Z",
2
],
[
"2020-04-19T19:16:26.5Z",
3
]
]
}
]
}
| pkg/tsdb/azuremonitor/testdata/loganalytics/3-log-analytics-response-metrics-no-metric-column.json | 0 | https://github.com/grafana/grafana/commit/623de12e354c8f92fd49802a04bafe5970fba0e9 | [
0.00017655565170571208,
0.00017557349929120392,
0.00017514901992399246,
0.00017529464093968272,
5.724683092012128e-7
] |
{
"id": 0,
"code_window": [
"\n",
"\tlogger.Debug(\"Saving alert states\", \"count\", len(states))\n",
"\tinstances := make([]ngModels.AlertInstance, 0, len(states))\n",
"\n",
"\tfor _, s := range states {\n",
"\t\tlabels := ngModels.InstanceLabels(s.Labels)\n",
"\t\t_, hash, err := labels.StringAndHash()\n",
"\t\tif err != nil {\n",
"\t\t\tlogger.Error(\"Failed to create a key for alert state to save it to database. The state will be ignored \", \"cacheID\", s.CacheID, \"error\", err)\n",
"\t\t\tcontinue\n",
"\t\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tkey, err := s.GetAlertInstanceKey()\n"
],
"file_path": "pkg/services/ngalert/state/manager.go",
"type": "replace",
"edit_start_line_idx": 293
} | import { e2e } from '@grafana/e2e';
const dataSourceName = 'LokiSlate';
const addDataSource = () => {
e2e.flows.addDataSource({
type: 'Loki',
expectedAlertMessage:
'Unable to fetch labels from Loki (Failed to call resource), please check the server logs for more details',
name: dataSourceName,
form: () => {
e2e.components.DataSource.DataSourceHttpSettings.urlInput().type('http://loki-url:3100');
},
});
};
describe('Loki slate editor', () => {
beforeEach(() => {
e2e.flows.login('admin', 'admin');
e2e()
.request({ url: `${e2e.env('BASE_URL')}/api/datasources/name/${dataSourceName}`, failOnStatusCode: false })
.then((response) => {
if (response.isOkStatusCode) {
return;
}
addDataSource();
});
});
it('Braces plugin should insert closing brace', () => {
e2e().intercept(/labels?/, (req) => {
req.reply({ status: 'success', data: ['instance', 'job', 'source'] });
});
e2e().intercept(/series?/, (req) => {
req.reply({ status: 'success', data: [{ instance: 'instance1' }] });
});
// Go to Explore and choose Loki data source
e2e.pages.Explore.visit();
e2e.components.DataSourcePicker.container().should('be.visible').click();
e2e().contains(dataSourceName).scrollIntoView().should('be.visible').click();
// adds closing braces around empty value
e2e().contains('Code').click();
const queryField = e2e().get('.slate-query-field');
queryField.type('time(');
queryField.should(($el) => {
expect($el.text().replace(/\uFEFF/g, '')).to.eq('time()');
});
// removes closing brace when opening brace is removed
queryField.type('{backspace}');
queryField.should(($el) => {
expect($el.text().replace(/\uFEFF/g, '')).to.eq('time');
});
// keeps closing brace when opening brace is removed and inner values exist
queryField.clear();
queryField.type('time(test{leftArrow}{leftArrow}{leftArrow}{leftArrow}{backspace}');
queryField.should(($el) => {
expect($el.text().replace(/\uFEFF/g, '')).to.eq('timetest)');
});
// overrides an automatically inserted brace
queryField.clear();
queryField.type('time()');
queryField.should(($el) => {
expect($el.text().replace(/\uFEFF/g, '')).to.eq('time()');
});
// does not override manually inserted braces
queryField.clear();
queryField.type('))');
queryField.should(($el) => {
expect($el.text().replace(/\uFEFF/g, '')).to.eq('))');
});
/** Clear Plugin */
//does not change the empty value
queryField.clear();
queryField.type('{ctrl+k}');
queryField.should(($el) => {
expect($el.text().replace(/\uFEFF/g, '')).to.match(/Enter a Loki query/);
});
// clears to the end of the line
queryField.clear();
queryField.type('foo{leftArrow}{leftArrow}{leftArrow}{ctrl+k}');
queryField.should(($el) => {
expect($el.text().replace(/\uFEFF/g, '')).to.match(/Enter a Loki query/);
});
// clears from the middle to the end of the line
queryField.clear();
queryField.type('foo bar{leftArrow}{leftArrow}{leftArrow}{leftArrow}{ctrl+k}');
queryField.should(($el) => {
expect($el.text().replace(/\uFEFF/g, '')).to.eq('foo');
});
/** Runner plugin */
//should execute query when enter with shift is pressed
queryField.clear();
queryField.type('{shift+enter}');
e2e().get('[data-testid="explore-no-data"]').should('be.visible');
/** Suggestions plugin */
e2e().get('.slate-query-field').type(`{selectall}av`);
e2e().get('.slate-typeahead').should('be.visible').contains('avg_over_time');
});
});
| e2e/various-suite/slate.spec.ts | 0 | https://github.com/grafana/grafana/commit/623de12e354c8f92fd49802a04bafe5970fba0e9 | [
0.00017963275604415685,
0.0001772550749592483,
0.0001742476742947474,
0.00017758432659320533,
0.0000016379925682485919
] |
{
"id": 1,
"code_window": [
"\t\t\tlogger.Error(\"Failed to create a key for alert state to save it to database. The state will be ignored \", \"cacheID\", s.CacheID, \"error\", err)\n",
"\t\t\tcontinue\n",
"\t\t}\n",
"\t\tfields := ngModels.AlertInstance{\n",
"\t\t\tAlertInstanceKey: ngModels.AlertInstanceKey{\n",
"\t\t\t\tRuleOrgID: s.OrgID,\n",
"\t\t\t\tRuleUID: s.AlertRuleUID,\n",
"\t\t\t\tLabelsHash: hash,\n",
"\t\t\t},\n",
"\t\t\tLabels: ngModels.InstanceLabels(s.Labels),\n",
"\t\t\tCurrentState: ngModels.InstanceStateType(s.State.State.String()),\n",
"\t\t\tCurrentReason: s.StateReason,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tAlertInstanceKey: key,\n"
],
"file_path": "pkg/services/ngalert/state/manager.go",
"type": "replace",
"edit_start_line_idx": 300
} | package state
import (
"context"
"errors"
"fmt"
"math"
"strings"
"time"
"github.com/grafana/grafana-plugin-sdk-go/data"
"github.com/grafana/grafana/pkg/expr"
"github.com/grafana/grafana/pkg/services/ngalert/eval"
"github.com/grafana/grafana/pkg/services/ngalert/image"
"github.com/grafana/grafana/pkg/services/ngalert/models"
"github.com/grafana/grafana/pkg/services/screenshot"
)
type State struct {
OrgID int64
AlertRuleUID string
// CacheID is a unique, opaque identifier for the state, and is used to find the state
// in the state cache. It tends to be derived from the state's labels.
CacheID string
// State represents the current state.
State eval.State
// StateReason is a textual description to explain why the state has its current state.
StateReason string
// Results contains the result of the current and previous evaluations.
Results []Evaluation
// Error is set if the current evaluation returned an error. If error is non-nil results
// can still contain the results of previous evaluations.
Error error
// Resolved is set to true if this state is the transitional state between Firing and Normal.
// All subsequent states will be false until the next transition from Firing to Normal.
Resolved bool
// Image contains an optional image for the state. It tends to be included in notifications
// as a visualization to show why the alert fired.
Image *models.Image
// Annotations contains the annotations from the alert rule. If an annotation is templated
// then the template is first evaluated to derive the final annotation.
Annotations map[string]string
// Labels contain the labels from the query and any custom labels from the alert rule.
// If a label is templated then the template is first evaluated to derive the final label.
Labels data.Labels
// Values contains the values of any instant vectors, reduce and math expressions, or classic
// conditions.
Values map[string]float64
StartsAt time.Time
EndsAt time.Time
LastSentAt time.Time
LastEvaluationString string
LastEvaluationTime time.Time
EvaluationDuration time.Duration
}
func (a *State) GetRuleKey() models.AlertRuleKey {
return models.AlertRuleKey{
OrgID: a.OrgID,
UID: a.AlertRuleUID,
}
}
// StateTransition describes the transition from one state to another.
type StateTransition struct {
*State
PreviousState eval.State
PreviousStateReason string
}
func (c StateTransition) Formatted() string {
return FormatStateAndReason(c.State.State, c.State.StateReason)
}
func (c StateTransition) PreviousFormatted() string {
return FormatStateAndReason(c.PreviousState, c.PreviousStateReason)
}
func (c StateTransition) changed() bool {
return c.PreviousState != c.State.State || c.PreviousStateReason != c.State.StateReason
}
type Evaluation struct {
EvaluationTime time.Time
EvaluationState eval.State
// Values contains the RefID and value of reduce and math expressions.
// Classic conditions can have different values for the same RefID as they can include multiple conditions.
// For these, we use the index of the condition in addition RefID as the key e.g. "A0, A1, A2, etc.".
Values map[string]*float64
// Condition is the refID specified as the condition in the alerting rule at the time of the evaluation.
Condition string
}
// NewEvaluationValues returns the labels and values for each RefID in the capture.
func NewEvaluationValues(m map[string]eval.NumberValueCapture) map[string]*float64 {
result := make(map[string]*float64, len(m))
for k, v := range m {
result[k] = v.Value
}
return result
}
func (a *State) resultNormal(_ *models.AlertRule, result eval.Result) {
a.Error = nil // should be nil since state is not error
if a.State != eval.Normal {
a.EndsAt = result.EvaluatedAt
a.StartsAt = result.EvaluatedAt
}
a.State = eval.Normal
}
func (a *State) resultAlerting(alertRule *models.AlertRule, result eval.Result) {
a.Error = result.Error // should be nil since the state is not an error
switch a.State {
case eval.Alerting:
a.setEndsAt(alertRule, result)
case eval.Pending:
if result.EvaluatedAt.Sub(a.StartsAt) >= alertRule.For {
a.State = eval.Alerting
a.StartsAt = result.EvaluatedAt
a.setEndsAt(alertRule, result)
}
default:
a.StartsAt = result.EvaluatedAt
a.setEndsAt(alertRule, result)
if !(alertRule.For > 0) {
// If For is 0, immediately set Alerting
a.State = eval.Alerting
} else {
a.State = eval.Pending
}
}
}
func (a *State) resultError(alertRule *models.AlertRule, result eval.Result) {
a.Error = result.Error
execErrState := eval.Error
switch alertRule.ExecErrState {
case models.AlertingErrState:
execErrState = eval.Alerting
case models.ErrorErrState:
// If the evaluation failed because a query returned an error then
// update the state with the Datasource UID as a label and the error
// message as an annotation so other code can use this metadata to
// add context to alerts
var queryError expr.QueryError
if errors.As(a.Error, &queryError) {
for _, next := range alertRule.Data {
if next.RefID == queryError.RefID {
a.Labels["ref_id"] = next.RefID
a.Labels["datasource_uid"] = next.DatasourceUID
break
}
}
a.Annotations["Error"] = queryError.Error()
}
execErrState = eval.Error
case models.OkErrState:
a.resultNormal(alertRule, result)
return
default:
a.Error = fmt.Errorf("cannot map error to a state because option [%s] is not supported. evaluation error: %w", alertRule.ExecErrState, a.Error)
}
switch a.State {
case eval.Alerting, eval.Error:
// We must set the state here as the state can change both from Alerting
// to Error and from Error to Alerting. This can happen when the datasource
// is unavailable or queries against the datasource returns errors, and is
// then resolved as soon as the datasource is available and queries return
// without error
a.State = execErrState
a.setEndsAt(alertRule, result)
case eval.Pending:
if result.EvaluatedAt.Sub(a.StartsAt) >= alertRule.For {
a.State = execErrState
a.StartsAt = result.EvaluatedAt
a.setEndsAt(alertRule, result)
}
default:
// For is observed when Alerting is chosen for the alert state
// if execution error or timeout.
if execErrState == eval.Alerting && alertRule.For > 0 {
a.State = eval.Pending
} else {
a.State = execErrState
}
a.StartsAt = result.EvaluatedAt
a.setEndsAt(alertRule, result)
}
}
func (a *State) resultNoData(alertRule *models.AlertRule, result eval.Result) {
a.Error = result.Error
if a.StartsAt.IsZero() {
a.StartsAt = result.EvaluatedAt
}
a.setEndsAt(alertRule, result)
switch alertRule.NoDataState {
case models.Alerting:
a.State = eval.Alerting
case models.NoData:
a.State = eval.NoData
case models.OK:
a.State = eval.Normal
}
}
func (a *State) NeedsSending(resendDelay time.Duration) bool {
switch a.State {
case eval.Pending:
// We do not send notifications for pending states
return false
case eval.Normal:
// We should send a notification if the state is Normal because it was resolved
return a.Resolved
default:
// We should send, and re-send notifications, each time LastSentAt is <= LastEvaluationTime + resendDelay
nextSent := a.LastSentAt.Add(resendDelay)
return nextSent.Before(a.LastEvaluationTime) || nextSent.Equal(a.LastEvaluationTime)
}
}
func (a *State) Equals(b *State) bool {
return a.AlertRuleUID == b.AlertRuleUID &&
a.OrgID == b.OrgID &&
a.CacheID == b.CacheID &&
a.Labels.String() == b.Labels.String() &&
a.State.String() == b.State.String() &&
a.StartsAt == b.StartsAt &&
a.EndsAt == b.EndsAt &&
a.LastEvaluationTime == b.LastEvaluationTime &&
data.Labels(a.Annotations).String() == data.Labels(b.Annotations).String()
}
func (a *State) TrimResults(alertRule *models.AlertRule) {
numBuckets := int64(alertRule.For.Seconds()) / alertRule.IntervalSeconds
if numBuckets == 0 {
numBuckets = 10 // keep at least 10 evaluations in the event For is set to 0
}
if len(a.Results) < int(numBuckets) {
return
}
newResults := make([]Evaluation, numBuckets)
copy(newResults, a.Results[len(a.Results)-int(numBuckets):])
a.Results = newResults
}
// setEndsAt sets the ending timestamp of the alert.
// The internal Alertmanager will use this time to know when it should automatically resolve the alert
// in case it hasn't received additional alerts. Under regular operations the scheduler will continue to send the
// alert with an updated EndsAt, if the alert is resolved then a last alert is sent with EndsAt = last evaluation time.
func (a *State) setEndsAt(alertRule *models.AlertRule, result eval.Result) {
ends := ResendDelay
if alertRule.IntervalSeconds > int64(ResendDelay.Seconds()) {
ends = time.Second * time.Duration(alertRule.IntervalSeconds)
}
a.EndsAt = result.EvaluatedAt.Add(ends * 3)
}
func (a *State) GetLabels(opts ...models.LabelOption) map[string]string {
labels := a.Labels.Copy()
for _, opt := range opts {
opt(labels)
}
return labels
}
func (a *State) GetLastEvaluationValuesForCondition() map[string]float64 {
if len(a.Results) <= 0 {
return nil
}
lastResult := a.Results[len(a.Results)-1]
r := make(map[string]float64, len(lastResult.Values))
for refID, value := range lastResult.Values {
if strings.Contains(refID, lastResult.Condition) {
if value != nil {
r[refID] = *value
continue
}
r[refID] = math.NaN()
}
}
return r
}
// shouldTakeImage returns true if the state just has transitioned to alerting from another state,
// transitioned to alerting in a previous evaluation but does not have a screenshot, or has just
// been resolved.
func shouldTakeImage(state, previousState eval.State, previousImage *models.Image, resolved bool) bool {
return resolved ||
state == eval.Alerting && previousState != eval.Alerting ||
state == eval.Alerting && previousImage == nil
}
// takeImage takes an image for the alert rule. It returns nil if screenshots are disabled or
// the rule is not associated with a dashboard panel.
func takeImage(ctx context.Context, s image.ImageService, r *models.AlertRule) (*models.Image, error) {
img, err := s.NewImage(ctx, r)
if err != nil {
if errors.Is(err, screenshot.ErrScreenshotsUnavailable) ||
errors.Is(err, image.ErrNoDashboard) ||
errors.Is(err, image.ErrNoPanel) {
return nil, nil
}
return nil, err
}
return img, nil
}
func FormatStateAndReason(state eval.State, reason string) string {
s := fmt.Sprintf("%v", state)
if len(reason) > 0 {
s += fmt.Sprintf(" (%v)", reason)
}
return s
}
| pkg/services/ngalert/state/state.go | 1 | https://github.com/grafana/grafana/commit/623de12e354c8f92fd49802a04bafe5970fba0e9 | [
0.0026190842036157846,
0.0004907551337964833,
0.00016143832181114703,
0.00018965393246617168,
0.0006510833627544343
] |
{
"id": 1,
"code_window": [
"\t\t\tlogger.Error(\"Failed to create a key for alert state to save it to database. The state will be ignored \", \"cacheID\", s.CacheID, \"error\", err)\n",
"\t\t\tcontinue\n",
"\t\t}\n",
"\t\tfields := ngModels.AlertInstance{\n",
"\t\t\tAlertInstanceKey: ngModels.AlertInstanceKey{\n",
"\t\t\t\tRuleOrgID: s.OrgID,\n",
"\t\t\t\tRuleUID: s.AlertRuleUID,\n",
"\t\t\t\tLabelsHash: hash,\n",
"\t\t\t},\n",
"\t\t\tLabels: ngModels.InstanceLabels(s.Labels),\n",
"\t\t\tCurrentState: ngModels.InstanceStateType(s.State.State.String()),\n",
"\t\t\tCurrentReason: s.StateReason,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tAlertInstanceKey: key,\n"
],
"file_path": "pkg/services/ngalert/state/manager.go",
"type": "replace",
"edit_start_line_idx": 300
} | import { action } from '@storybook/addon-actions';
import { ComponentMeta } from '@storybook/react';
import React from 'react';
import { ToolbarButton, VerticalGroup } from '@grafana/ui';
import { StoryExample } from '../../utils/storybook/StoryExample';
import { withCenteredStory } from '../../utils/storybook/withCenteredStory';
import { IconButton } from '../IconButton/IconButton';
import { PageToolbar } from './PageToolbar';
const meta: ComponentMeta<typeof PageToolbar> = {
title: 'Layout/PageToolbar',
component: PageToolbar,
decorators: [withCenteredStory],
parameters: {},
};
export const Examples = () => {
return (
<VerticalGroup>
<StoryExample name="With non clickable title">
<PageToolbar pageIcon="bell" title="Dashboard">
<ToolbarButton icon="panel-add" />
<ToolbarButton icon="sync">Sync</ToolbarButton>
</PageToolbar>
</StoryExample>
<StoryExample name="With clickable title and parent">
<PageToolbar
pageIcon="apps"
title="A very long dashboard name"
parent="A long folder name"
titleHref=""
parentHref=""
leftItems={[
<IconButton name="share-alt" size="lg" key="share" />,
<IconButton name="favorite" iconType="mono" size="lg" key="favorite" />,
]}
>
<ToolbarButton icon="panel-add" />
<ToolbarButton icon="share-alt" />
<ToolbarButton icon="sync">Sync</ToolbarButton>
<ToolbarButton icon="cog">Settings </ToolbarButton>
</PageToolbar>
</StoryExample>
<StoryExample name="Go back version">
<PageToolbar title="Service overview / Edit panel" onGoBack={() => action('Go back')}>
<ToolbarButton icon="cog" />
<ToolbarButton icon="save" />
<ToolbarButton>Discard</ToolbarButton>
<ToolbarButton>Apply</ToolbarButton>
</PageToolbar>
</StoryExample>
</VerticalGroup>
);
};
export default meta;
| packages/grafana-ui/src/components/PageLayout/PageToolbar.story.tsx | 0 | https://github.com/grafana/grafana/commit/623de12e354c8f92fd49802a04bafe5970fba0e9 | [
0.00017779531481210142,
0.0001767961512086913,
0.00017566750466357917,
0.0001770039671100676,
7.485265882678505e-7
] |
{
"id": 1,
"code_window": [
"\t\t\tlogger.Error(\"Failed to create a key for alert state to save it to database. The state will be ignored \", \"cacheID\", s.CacheID, \"error\", err)\n",
"\t\t\tcontinue\n",
"\t\t}\n",
"\t\tfields := ngModels.AlertInstance{\n",
"\t\t\tAlertInstanceKey: ngModels.AlertInstanceKey{\n",
"\t\t\t\tRuleOrgID: s.OrgID,\n",
"\t\t\t\tRuleUID: s.AlertRuleUID,\n",
"\t\t\t\tLabelsHash: hash,\n",
"\t\t\t},\n",
"\t\t\tLabels: ngModels.InstanceLabels(s.Labels),\n",
"\t\t\tCurrentState: ngModels.InstanceStateType(s.State.State.String()),\n",
"\t\t\tCurrentReason: s.StateReason,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tAlertInstanceKey: key,\n"
],
"file_path": "pkg/services/ngalert/state/manager.go",
"type": "replace",
"edit_start_line_idx": 300
} | import { DataQuery, DataSourceApi, DataSourceJsonData, DataSourcePlugin } from '@grafana/data';
export type GenericDataSourcePlugin = DataSourcePlugin<DataSourceApi<DataQuery, DataSourceJsonData>>;
export type DataSourceRights = {
readOnly: boolean;
hasWriteRights: boolean;
hasDeleteRights: boolean;
};
export type DataSourcesRoutes = {
New: string;
Edit: string;
List: string;
Dashboards: string;
};
| public/app/features/datasources/types.ts | 0 | https://github.com/grafana/grafana/commit/623de12e354c8f92fd49802a04bafe5970fba0e9 | [
0.0001708195050014183,
0.00017019706137944013,
0.00016957461775746197,
0.00017019706137944013,
6.224436219781637e-7
] |
{
"id": 1,
"code_window": [
"\t\t\tlogger.Error(\"Failed to create a key for alert state to save it to database. The state will be ignored \", \"cacheID\", s.CacheID, \"error\", err)\n",
"\t\t\tcontinue\n",
"\t\t}\n",
"\t\tfields := ngModels.AlertInstance{\n",
"\t\t\tAlertInstanceKey: ngModels.AlertInstanceKey{\n",
"\t\t\t\tRuleOrgID: s.OrgID,\n",
"\t\t\t\tRuleUID: s.AlertRuleUID,\n",
"\t\t\t\tLabelsHash: hash,\n",
"\t\t\t},\n",
"\t\t\tLabels: ngModels.InstanceLabels(s.Labels),\n",
"\t\t\tCurrentState: ngModels.InstanceStateType(s.State.State.String()),\n",
"\t\t\tCurrentReason: s.StateReason,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tAlertInstanceKey: key,\n"
],
"file_path": "pkg/services/ngalert/state/manager.go",
"type": "replace",
"edit_start_line_idx": 300
} | // Code generated by MockGen. DO NOT EDIT.
// Source: github.com/grafana/grafana/pkg/services/screenshot (interfaces: CacheService)
// Package screenshot is a generated GoMock package.
package screenshot
import (
context "context"
reflect "reflect"
gomock "github.com/golang/mock/gomock"
)
// MockCacheService is a mock of CacheService interface.
type MockCacheService struct {
ctrl *gomock.Controller
recorder *MockCacheServiceMockRecorder
}
// MockCacheServiceMockRecorder is the mock recorder for MockCacheService.
type MockCacheServiceMockRecorder struct {
mock *MockCacheService
}
// NewMockCacheService creates a new mock instance.
func NewMockCacheService(ctrl *gomock.Controller) *MockCacheService {
mock := &MockCacheService{ctrl: ctrl}
mock.recorder = &MockCacheServiceMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockCacheService) EXPECT() *MockCacheServiceMockRecorder {
return m.recorder
}
// Get mocks base method.
func (m *MockCacheService) Get(arg0 context.Context, arg1 ScreenshotOptions) (*Screenshot, bool) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Get", arg0, arg1)
ret0, _ := ret[0].(*Screenshot)
ret1, _ := ret[1].(bool)
return ret0, ret1
}
// Get indicates an expected call of Get.
func (mr *MockCacheServiceMockRecorder) Get(arg0, arg1 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Get", reflect.TypeOf((*MockCacheService)(nil).Get), arg0, arg1)
}
// Set mocks base method.
func (m *MockCacheService) Set(arg0 context.Context, arg1 ScreenshotOptions, arg2 *Screenshot) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Set", arg0, arg1, arg2)
ret0, _ := ret[0].(error)
return ret0
}
// Set indicates an expected call of Set.
func (mr *MockCacheServiceMockRecorder) Set(arg0, arg1, arg2 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Set", reflect.TypeOf((*MockCacheService)(nil).Set), arg0, arg1, arg2)
}
| pkg/services/screenshot/cache_mock.go | 0 | https://github.com/grafana/grafana/commit/623de12e354c8f92fd49802a04bafe5970fba0e9 | [
0.00017442021635361016,
0.00017033675976563245,
0.0001655824889894575,
0.00017033529002219439,
0.000003429933713050559
] |
{
"id": 2,
"code_window": [
"\t\t// Is the cached state in our recently processed results? If not, is it stale?\n",
"\t\tif _, ok := states[s.CacheID]; !ok && stateIsStale(evaluatedAt, s.LastEvaluationTime, alertRule.IntervalSeconds) {\n",
"\t\t\tlogger.Info(\"Removing stale state entry\", \"cacheID\", s.CacheID, \"state\", s.State, \"reason\", s.StateReason)\n",
"\t\t\tst.cache.deleteEntry(s.OrgID, s.AlertRuleUID, s.CacheID)\n",
"\t\t\tilbs := ngModels.InstanceLabels(s.Labels)\n",
"\t\t\t_, labelsHash, err := ilbs.StringAndHash()\n",
"\t\t\tif err != nil {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep"
],
"after_edit": [
"\n",
"\t\t\tkey, err := s.GetAlertInstanceKey()\n"
],
"file_path": "pkg/services/ngalert/state/manager.go",
"type": "replace",
"edit_start_line_idx": 354
} | package state
import (
"context"
"net/url"
"time"
"github.com/benbjohnson/clock"
"github.com/grafana/grafana-plugin-sdk-go/data"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/services/ngalert/eval"
"github.com/grafana/grafana/pkg/services/ngalert/image"
"github.com/grafana/grafana/pkg/services/ngalert/metrics"
ngModels "github.com/grafana/grafana/pkg/services/ngalert/models"
)
var (
ResendDelay = 30 * time.Second
MetricsScrapeInterval = 15 * time.Second // TODO: parameterize? // Setting to a reasonable default scrape interval for Prometheus.
)
// AlertInstanceManager defines the interface for querying the current alert instances.
type AlertInstanceManager interface {
GetAll(orgID int64) []*State
GetStatesForRuleUID(orgID int64, alertRuleUID string) []*State
}
type Manager struct {
log log.Logger
metrics *metrics.State
clock clock.Clock
cache *cache
ResendDelay time.Duration
instanceStore InstanceStore
imageService image.ImageService
historian Historian
externalURL *url.URL
}
func NewManager(metrics *metrics.State, externalURL *url.URL, instanceStore InstanceStore, imageService image.ImageService, clock clock.Clock, historian Historian) *Manager {
return &Manager{
cache: newCache(),
ResendDelay: ResendDelay, // TODO: make this configurable
log: log.New("ngalert.state.manager"),
metrics: metrics,
instanceStore: instanceStore,
imageService: imageService,
historian: historian,
clock: clock,
externalURL: externalURL,
}
}
func (st *Manager) Run(ctx context.Context) error {
ticker := st.clock.Ticker(MetricsScrapeInterval)
for {
select {
case <-ticker.C:
st.log.Debug("Recording state cache metrics", "now", st.clock.Now())
st.cache.recordMetrics(st.metrics)
case <-ctx.Done():
st.log.Debug("Stopping")
ticker.Stop()
return ctx.Err()
}
}
}
func (st *Manager) Warm(ctx context.Context, rulesReader RuleReader) {
if st.instanceStore == nil {
st.log.Info("Skip warming the state because instance store is not configured")
return
}
startTime := time.Now()
st.log.Info("Warming state cache for startup")
orgIds, err := st.instanceStore.FetchOrgIds(ctx)
if err != nil {
st.log.Error("Unable to fetch orgIds", "error", err)
}
statesCount := 0
states := make(map[int64]map[string]*ruleStates, len(orgIds))
for _, orgId := range orgIds {
// Get Rules
ruleCmd := ngModels.ListAlertRulesQuery{
OrgID: orgId,
}
if err := rulesReader.ListAlertRules(ctx, &ruleCmd); err != nil {
st.log.Error("Unable to fetch previous state", "error", err)
}
ruleByUID := make(map[string]*ngModels.AlertRule, len(ruleCmd.Result))
for _, rule := range ruleCmd.Result {
ruleByUID[rule.UID] = rule
}
orgStates := make(map[string]*ruleStates, len(ruleByUID))
states[orgId] = orgStates
// Get Instances
cmd := ngModels.ListAlertInstancesQuery{
RuleOrgID: orgId,
}
if err := st.instanceStore.ListAlertInstances(ctx, &cmd); err != nil {
st.log.Error("Unable to fetch previous state", "error", err)
}
for _, entry := range cmd.Result {
ruleForEntry, ok := ruleByUID[entry.RuleUID]
if !ok {
// TODO Should we delete the orphaned state from the db?
continue
}
rulesStates, ok := orgStates[entry.RuleUID]
if !ok {
rulesStates = &ruleStates{states: make(map[string]*State)}
orgStates[entry.RuleUID] = rulesStates
}
lbs := map[string]string(entry.Labels)
cacheID, err := entry.Labels.StringKey()
if err != nil {
st.log.Error("Error getting cacheId for entry", "error", err)
}
rulesStates.states[cacheID] = &State{
AlertRuleUID: entry.RuleUID,
OrgID: entry.RuleOrgID,
CacheID: cacheID,
Labels: lbs,
State: translateInstanceState(entry.CurrentState),
StateReason: entry.CurrentReason,
LastEvaluationString: "",
StartsAt: entry.CurrentStateSince,
EndsAt: entry.CurrentStateEnd,
LastEvaluationTime: entry.LastEvalTime,
Annotations: ruleForEntry.Annotations,
}
statesCount++
}
}
st.cache.setAllStates(states)
st.log.Info("State cache has been initialized", "states", statesCount, "duration", time.Since(startTime))
}
func (st *Manager) Get(orgID int64, alertRuleUID, stateId string) *State {
return st.cache.get(orgID, alertRuleUID, stateId)
}
// ResetStateByRuleUID deletes all entries in the state manager that match the given rule UID.
func (st *Manager) ResetStateByRuleUID(ctx context.Context, ruleKey ngModels.AlertRuleKey) []*State {
logger := st.log.New(ruleKey.LogContext()...)
logger.Debug("Resetting state of the rule")
states := st.cache.removeByRuleUID(ruleKey.OrgID, ruleKey.UID)
if len(states) > 0 && st.instanceStore != nil {
err := st.instanceStore.DeleteAlertInstancesByRule(ctx, ruleKey)
if err != nil {
logger.Error("Failed to delete states that belong to a rule from database", "error", err)
}
}
logger.Info("Rules state was reset", "states", len(states))
return states
}
// ProcessEvalResults updates the current states that belong to a rule with the evaluation results.
// if extraLabels is not empty, those labels will be added to every state. The extraLabels take precedence over rule labels and result labels
func (st *Manager) ProcessEvalResults(ctx context.Context, evaluatedAt time.Time, alertRule *ngModels.AlertRule, results eval.Results, extraLabels data.Labels) []*State {
logger := st.log.FromContext(ctx)
logger.Debug("State manager processing evaluation results", "resultCount", len(results))
var states []StateTransition
processedResults := make(map[string]*State, len(results))
for _, result := range results {
s := st.setNextState(ctx, alertRule, result, extraLabels, logger)
states = append(states, s)
processedResults[s.State.CacheID] = s.State
}
resolvedStates := st.staleResultsHandler(ctx, evaluatedAt, alertRule, processedResults, logger)
st.saveAlertStates(ctx, logger, states...)
changedStates := make([]StateTransition, 0, len(states))
for _, s := range states {
if s.changed() {
changedStates = append(changedStates, s)
}
}
if st.historian != nil {
st.historian.RecordStates(ctx, alertRule, changedStates)
}
deltas := append(states, resolvedStates...)
nextStates := make([]*State, 0, len(states))
for _, s := range deltas {
nextStates = append(nextStates, s.State)
}
return nextStates
}
// Set the current state based on evaluation results
func (st *Manager) setNextState(ctx context.Context, alertRule *ngModels.AlertRule, result eval.Result, extraLabels data.Labels, logger log.Logger) StateTransition {
currentState := st.cache.getOrCreate(ctx, st.log, alertRule, result, extraLabels, st.externalURL)
currentState.LastEvaluationTime = result.EvaluatedAt
currentState.EvaluationDuration = result.EvaluationDuration
currentState.Results = append(currentState.Results, Evaluation{
EvaluationTime: result.EvaluatedAt,
EvaluationState: result.State,
Values: NewEvaluationValues(result.Values),
Condition: alertRule.Condition,
})
currentState.LastEvaluationString = result.EvaluationString
currentState.TrimResults(alertRule)
oldState := currentState.State
oldReason := currentState.StateReason
logger.Debug("Setting alert state")
switch result.State {
case eval.Normal:
currentState.resultNormal(alertRule, result)
case eval.Alerting:
currentState.resultAlerting(alertRule, result)
case eval.Error:
currentState.resultError(alertRule, result)
case eval.NoData:
currentState.resultNoData(alertRule, result)
case eval.Pending: // we do not emit results with this state
}
// Set reason iff: result is different than state, reason is not Alerting or Normal
currentState.StateReason = ""
if currentState.State != result.State &&
result.State != eval.Normal &&
result.State != eval.Alerting {
currentState.StateReason = result.State.String()
}
// Set Resolved property so the scheduler knows to send a postable alert
// to Alertmanager.
currentState.Resolved = oldState == eval.Alerting && currentState.State == eval.Normal
if shouldTakeImage(currentState.State, oldState, currentState.Image, currentState.Resolved) {
image, err := takeImage(ctx, st.imageService, alertRule)
if err != nil {
logger.Warn("Failed to take an image",
"dashboard", alertRule.DashboardUID,
"panel", alertRule.PanelID,
"error", err)
} else if image != nil {
currentState.Image = image
}
}
st.cache.set(currentState)
nextState := StateTransition{
State: currentState,
PreviousState: oldState,
PreviousStateReason: oldReason,
}
return nextState
}
func (st *Manager) GetAll(orgID int64) []*State {
return st.cache.getAll(orgID)
}
func (st *Manager) GetStatesForRuleUID(orgID int64, alertRuleUID string) []*State {
return st.cache.getStatesForRuleUID(orgID, alertRuleUID)
}
func (st *Manager) Put(states []*State) {
for _, s := range states {
st.cache.set(s)
}
}
// TODO: Is the `State` type necessary? Should it embed the instance?
func (st *Manager) saveAlertStates(ctx context.Context, logger log.Logger, states ...StateTransition) {
if st.instanceStore == nil {
return
}
logger.Debug("Saving alert states", "count", len(states))
instances := make([]ngModels.AlertInstance, 0, len(states))
for _, s := range states {
labels := ngModels.InstanceLabels(s.Labels)
_, hash, err := labels.StringAndHash()
if err != nil {
logger.Error("Failed to create a key for alert state to save it to database. The state will be ignored ", "cacheID", s.CacheID, "error", err)
continue
}
fields := ngModels.AlertInstance{
AlertInstanceKey: ngModels.AlertInstanceKey{
RuleOrgID: s.OrgID,
RuleUID: s.AlertRuleUID,
LabelsHash: hash,
},
Labels: ngModels.InstanceLabels(s.Labels),
CurrentState: ngModels.InstanceStateType(s.State.State.String()),
CurrentReason: s.StateReason,
LastEvalTime: s.LastEvaluationTime,
CurrentStateSince: s.StartsAt,
CurrentStateEnd: s.EndsAt,
}
instances = append(instances, fields)
}
if err := st.instanceStore.SaveAlertInstances(ctx, instances...); err != nil {
type debugInfo struct {
State string
Labels string
}
debug := make([]debugInfo, 0)
for _, inst := range instances {
debug = append(debug, debugInfo{string(inst.CurrentState), data.Labels(inst.Labels).String()})
}
logger.Error("Failed to save alert states", "states", debug, "error", err)
}
}
// TODO: why wouldn't you allow other types like NoData or Error?
func translateInstanceState(state ngModels.InstanceStateType) eval.State {
switch {
case state == ngModels.InstanceStateFiring:
return eval.Alerting
case state == ngModels.InstanceStateNormal:
return eval.Normal
default:
return eval.Error
}
}
func (st *Manager) staleResultsHandler(ctx context.Context, evaluatedAt time.Time, alertRule *ngModels.AlertRule, states map[string]*State, logger log.Logger) []StateTransition {
// If we are removing two or more stale series it makes sense to share the resolved image as the alert rule is the same.
// TODO: We will need to change this when we support images without screenshots as each series will have a different image
var resolvedImage *ngModels.Image
var resolvedStates []StateTransition
allStates := st.GetStatesForRuleUID(alertRule.OrgID, alertRule.UID)
toDelete := make([]ngModels.AlertInstanceKey, 0)
for _, s := range allStates {
// Is the cached state in our recently processed results? If not, is it stale?
if _, ok := states[s.CacheID]; !ok && stateIsStale(evaluatedAt, s.LastEvaluationTime, alertRule.IntervalSeconds) {
logger.Info("Removing stale state entry", "cacheID", s.CacheID, "state", s.State, "reason", s.StateReason)
st.cache.deleteEntry(s.OrgID, s.AlertRuleUID, s.CacheID)
ilbs := ngModels.InstanceLabels(s.Labels)
_, labelsHash, err := ilbs.StringAndHash()
if err != nil {
logger.Error("Unable to get labelsHash", "error", err.Error(), s.AlertRuleUID)
}
toDelete = append(toDelete, ngModels.AlertInstanceKey{RuleOrgID: s.OrgID, RuleUID: s.AlertRuleUID, LabelsHash: labelsHash})
if s.State == eval.Alerting {
oldState := s.State
oldReason := s.StateReason
s.State = eval.Normal
s.StateReason = ngModels.StateReasonMissingSeries
s.EndsAt = evaluatedAt
s.Resolved = true
s.LastEvaluationTime = evaluatedAt
record := StateTransition{
State: s,
PreviousState: oldState,
PreviousStateReason: oldReason,
}
// If there is no resolved image for this rule then take one
if resolvedImage == nil {
image, err := takeImage(ctx, st.imageService, alertRule)
if err != nil {
logger.Warn("Failed to take an image",
"dashboard", alertRule.DashboardUID,
"panel", alertRule.PanelID,
"error", err)
} else if image != nil {
resolvedImage = image
}
}
s.Image = resolvedImage
resolvedStates = append(resolvedStates, record)
}
}
}
if st.historian != nil {
st.historian.RecordStates(ctx, alertRule, resolvedStates)
}
if st.instanceStore != nil {
if err := st.instanceStore.DeleteAlertInstances(ctx, toDelete...); err != nil {
logger.Error("Unable to delete stale instances from database", "error", err, "count", len(toDelete))
}
}
return resolvedStates
}
func stateIsStale(evaluatedAt time.Time, lastEval time.Time, intervalSeconds int64) bool {
return !lastEval.Add(2 * time.Duration(intervalSeconds) * time.Second).After(evaluatedAt)
}
| pkg/services/ngalert/state/manager.go | 1 | https://github.com/grafana/grafana/commit/623de12e354c8f92fd49802a04bafe5970fba0e9 | [
0.9982902407646179,
0.04987768828868866,
0.00016516336472705007,
0.0014818977797403932,
0.21198181807994843
] |
{
"id": 2,
"code_window": [
"\t\t// Is the cached state in our recently processed results? If not, is it stale?\n",
"\t\tif _, ok := states[s.CacheID]; !ok && stateIsStale(evaluatedAt, s.LastEvaluationTime, alertRule.IntervalSeconds) {\n",
"\t\t\tlogger.Info(\"Removing stale state entry\", \"cacheID\", s.CacheID, \"state\", s.State, \"reason\", s.StateReason)\n",
"\t\t\tst.cache.deleteEntry(s.OrgID, s.AlertRuleUID, s.CacheID)\n",
"\t\t\tilbs := ngModels.InstanceLabels(s.Labels)\n",
"\t\t\t_, labelsHash, err := ilbs.StringAndHash()\n",
"\t\t\tif err != nil {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep"
],
"after_edit": [
"\n",
"\t\t\tkey, err := s.GetAlertInstanceKey()\n"
],
"file_path": "pkg/services/ngalert/state/manager.go",
"type": "replace",
"edit_start_line_idx": 354
} | package cloudmonitoring
import (
"strings"
"github.com/grafana/grafana-plugin-sdk-go/data"
"github.com/grafana/grafana/pkg/tsdb/intervalv2"
)
func reverse(s string) string {
chars := []rune(s)
for i, j := 0, len(chars)-1; i < j; i, j = i+1, j-1 {
chars[i], chars[j] = chars[j], chars[i]
}
return string(chars)
}
func toSnakeCase(str string) string {
return strings.ToLower(matchAllCap.ReplaceAllString(str, "${1}_${2}"))
}
func containsLabel(labels []string, newLabel string) bool {
for _, val := range labels {
if val == newLabel {
return true
}
}
return false
}
func addInterval(period string, field *data.Field) error {
period = strings.TrimPrefix(period, "+")
p, err := intervalv2.ParseIntervalStringToTimeDuration(period)
if err != nil {
return err
}
if err == nil {
if field.Config != nil {
field.Config.Interval = float64(p.Milliseconds())
} else {
field.SetConfig(&data.FieldConfig{
Interval: float64(p.Milliseconds()),
})
}
}
return nil
}
| pkg/tsdb/cloudmonitoring/utils.go | 0 | https://github.com/grafana/grafana/commit/623de12e354c8f92fd49802a04bafe5970fba0e9 | [
0.00044342316687107086,
0.0002269154356326908,
0.0001683929149294272,
0.0001699801505310461,
0.00010839320020750165
] |
{
"id": 2,
"code_window": [
"\t\t// Is the cached state in our recently processed results? If not, is it stale?\n",
"\t\tif _, ok := states[s.CacheID]; !ok && stateIsStale(evaluatedAt, s.LastEvaluationTime, alertRule.IntervalSeconds) {\n",
"\t\t\tlogger.Info(\"Removing stale state entry\", \"cacheID\", s.CacheID, \"state\", s.State, \"reason\", s.StateReason)\n",
"\t\t\tst.cache.deleteEntry(s.OrgID, s.AlertRuleUID, s.CacheID)\n",
"\t\t\tilbs := ngModels.InstanceLabels(s.Labels)\n",
"\t\t\t_, labelsHash, err := ilbs.StringAndHash()\n",
"\t\t\tif err != nil {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep"
],
"after_edit": [
"\n",
"\t\t\tkey, err := s.GetAlertInstanceKey()\n"
],
"file_path": "pkg/services/ngalert/state/manager.go",
"type": "replace",
"edit_start_line_idx": 354
} | import { of } from 'rxjs';
import {
DataSourceInstanceSettings,
DataSourcePluginMeta,
PluginMetaInfo,
PluginType,
VariableHide,
} from '@grafana/data';
import { getBackendSrv, setBackendSrv } from '@grafana/runtime';
import { getTimeSrv } from 'app/features/dashboard/services/TimeSrv';
import { TemplateSrv } from 'app/features/templating/template_srv';
import { initialCustomVariableModelState } from 'app/features/variables/custom/reducer';
import { CustomVariableModel } from 'app/features/variables/types';
import { CloudWatchDatasource } from '../datasource';
import { CloudWatchJsonData } from '../types';
export function setupMockedTemplateService(variables: CustomVariableModel[]) {
const templateService = new TemplateSrv();
templateService.init(variables);
templateService.getVariables = jest.fn().mockReturnValue(variables);
return templateService;
}
const info: PluginMetaInfo = {
author: {
name: '',
},
description: '',
links: [],
logos: {
large: '',
small: '',
},
screenshots: [],
updated: '',
version: '',
};
export const meta: DataSourcePluginMeta<CloudWatchJsonData> = {
id: '',
name: '',
type: PluginType.datasource,
info,
module: '',
baseUrl: '',
};
export const CloudWatchSettings: DataSourceInstanceSettings<CloudWatchJsonData> = {
jsonData: { defaultRegion: 'us-west-1', tracingDatasourceUid: 'xray' },
id: 0,
uid: '',
type: '',
name: 'CloudWatch Test Datasource',
meta,
readOnly: false,
access: 'direct',
};
export function setupMockedDataSource({
variables,
mockGetVariableName = true,
getMock = jest.fn(),
}: {
getMock?: jest.Func;
variables?: CustomVariableModel[];
mockGetVariableName?: boolean;
} = {}) {
let templateService = new TemplateSrv();
if (variables) {
templateService = setupMockedTemplateService(variables);
if (mockGetVariableName) {
templateService.getVariableName = (name: string) => name;
}
}
const timeSrv = getTimeSrv();
const datasource = new CloudWatchDatasource(CloudWatchSettings, templateService, timeSrv);
datasource.getVariables = () => ['test'];
datasource.api.describeLogGroups = jest.fn().mockResolvedValue([]);
datasource.api.getNamespaces = jest.fn().mockResolvedValue([]);
datasource.api.getRegions = jest.fn().mockResolvedValue([]);
datasource.api.getDimensionKeys = jest.fn().mockResolvedValue([]);
datasource.api.getMetrics = jest.fn().mockResolvedValue([]);
datasource.logsQueryRunner.defaultLogGroups = [];
const fetchMock = jest.fn().mockReturnValue(of({}));
setBackendSrv({
...getBackendSrv(),
fetch: fetchMock,
get: getMock,
});
return { datasource, fetchMock, templateService, timeSrv };
}
export const metricVariable: CustomVariableModel = {
...initialCustomVariableModelState,
id: 'metric',
name: 'metric',
current: { value: 'CPUUtilization', text: 'CPUUtilizationEC2', selected: true },
options: [
{ value: 'DroppedBytes', text: 'DroppedBytes', selected: false },
{ value: 'CPUUtilization', text: 'CPUUtilization', selected: false },
],
multi: false,
};
export const namespaceVariable: CustomVariableModel = {
...initialCustomVariableModelState,
id: 'namespace',
name: 'namespace',
query: 'namespaces()',
current: { value: 'AWS/EC2', text: 'AWS/EC2', selected: true },
options: [
{ value: 'AWS/Redshift', text: 'AWS/Redshift', selected: false },
{ value: 'AWS/EC2', text: 'AWS/EC2', selected: false },
{ value: 'AWS/MQ', text: 'AWS/MQ', selected: false },
],
multi: false,
};
export const labelsVariable: CustomVariableModel = {
...initialCustomVariableModelState,
id: 'labels',
name: 'labels',
current: {
value: ['InstanceId', 'InstanceType'],
text: ['InstanceId', 'InstanceType'].toString(),
selected: true,
},
options: [
{ value: 'InstanceId', text: 'InstanceId', selected: false },
{ value: 'InstanceType', text: 'InstanceType', selected: false },
],
multi: true,
};
export const limitVariable: CustomVariableModel = {
...initialCustomVariableModelState,
id: 'limit',
name: 'limit',
current: {
value: '100',
text: '100',
selected: true,
},
options: [
{ value: '10', text: '10', selected: false },
{ value: '100', text: '100', selected: false },
{ value: '1000', text: '1000', selected: false },
],
multi: false,
};
export const aggregationvariable: CustomVariableModel = {
...initialCustomVariableModelState,
id: 'aggregation',
name: 'aggregation',
current: {
value: 'AVG',
text: 'AVG',
selected: true,
},
options: [
{ value: 'AVG', text: 'AVG', selected: false },
{ value: 'SUM', text: 'SUM', selected: false },
{ value: 'MIN', text: 'MIN', selected: false },
],
multi: false,
};
export const dimensionVariable: CustomVariableModel = {
...initialCustomVariableModelState,
id: 'dimension',
name: 'dimension',
current: {
value: 'env',
text: 'env',
selected: true,
},
options: [
{ value: 'env', text: 'env', selected: false },
{ value: 'tag', text: 'tag', selected: false },
],
multi: false,
};
export const logGroupNamesVariable: CustomVariableModel = {
...initialCustomVariableModelState,
id: 'groups',
name: 'groups',
current: {
value: ['templatedGroup-1', 'templatedGroup-2'],
text: ['templatedGroup-1', 'templatedGroup-2'],
selected: true,
},
options: [
{ value: 'templatedGroup-1', text: 'templatedGroup-1', selected: true },
{ value: 'templatedGroup-2', text: 'templatedGroup-2', selected: true },
],
multi: true,
};
export const regionVariable: CustomVariableModel = {
...initialCustomVariableModelState,
id: 'region',
name: 'region',
current: {
value: 'templatedRegion',
text: 'templatedRegion',
selected: true,
},
options: [{ value: 'templatedRegion', text: 'templatedRegion', selected: true }],
multi: false,
};
export const fieldsVariable: CustomVariableModel = {
...initialCustomVariableModelState,
id: 'fields',
name: 'fields',
current: {
value: 'templatedField',
text: 'templatedField',
selected: true,
},
options: [{ value: 'templatedField', text: 'templatedField', selected: true }],
multi: false,
};
export const periodIntervalVariable: CustomVariableModel = {
...initialCustomVariableModelState,
id: 'period',
name: 'period',
index: 0,
current: { value: '10m', text: '10m', selected: true },
options: [{ value: '10m', text: '10m', selected: true }],
multi: false,
includeAll: false,
query: '',
hide: VariableHide.dontHide,
type: 'custom',
};
| public/app/plugins/datasource/cloudwatch/__mocks__/CloudWatchDataSource.ts | 0 | https://github.com/grafana/grafana/commit/623de12e354c8f92fd49802a04bafe5970fba0e9 | [
0.00017961478442884982,
0.0001761934399837628,
0.0001688107440713793,
0.00017690497043076903,
0.0000025516926598356804
] |
{
"id": 2,
"code_window": [
"\t\t// Is the cached state in our recently processed results? If not, is it stale?\n",
"\t\tif _, ok := states[s.CacheID]; !ok && stateIsStale(evaluatedAt, s.LastEvaluationTime, alertRule.IntervalSeconds) {\n",
"\t\t\tlogger.Info(\"Removing stale state entry\", \"cacheID\", s.CacheID, \"state\", s.State, \"reason\", s.StateReason)\n",
"\t\t\tst.cache.deleteEntry(s.OrgID, s.AlertRuleUID, s.CacheID)\n",
"\t\t\tilbs := ngModels.InstanceLabels(s.Labels)\n",
"\t\t\t_, labelsHash, err := ilbs.StringAndHash()\n",
"\t\t\tif err != nil {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep"
],
"after_edit": [
"\n",
"\t\t\tkey, err := s.GetAlertInstanceKey()\n"
],
"file_path": "pkg/services/ngalert/state/manager.go",
"type": "replace",
"edit_start_line_idx": 354
} | package correlations
import (
"github.com/grafana/grafana/pkg/services/accesscontrol"
"github.com/grafana/grafana/pkg/services/datasources"
)
var (
// ConfigurationPageAccess is used to protect the "Configure > correlations" tab access
ConfigurationPageAccess = accesscontrol.EvalPermission(datasources.ActionRead)
)
| pkg/services/correlations/accesscontrol.go | 0 | https://github.com/grafana/grafana/commit/623de12e354c8f92fd49802a04bafe5970fba0e9 | [
0.00017570654745213687,
0.00017533406207803637,
0.00017496157670393586,
0.00017533406207803637,
3.724853741005063e-7
] |
{
"id": 3,
"code_window": [
"\t\t\tif err != nil {\n",
"\t\t\t\tlogger.Error(\"Unable to get labelsHash\", \"error\", err.Error(), s.AlertRuleUID)\n",
"\t\t\t}\n",
"\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\tlogger.Error(\"Unable to get alert instance key to delete it from database. Ignoring\", \"error\", err.Error())\n",
"\t\t\t} else {\n",
"\t\t\t\ttoDelete = append(toDelete, key)\n"
],
"file_path": "pkg/services/ngalert/state/manager.go",
"type": "replace",
"edit_start_line_idx": 357
} | package state
import (
"context"
"net/url"
"time"
"github.com/benbjohnson/clock"
"github.com/grafana/grafana-plugin-sdk-go/data"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/services/ngalert/eval"
"github.com/grafana/grafana/pkg/services/ngalert/image"
"github.com/grafana/grafana/pkg/services/ngalert/metrics"
ngModels "github.com/grafana/grafana/pkg/services/ngalert/models"
)
var (
ResendDelay = 30 * time.Second
MetricsScrapeInterval = 15 * time.Second // TODO: parameterize? // Setting to a reasonable default scrape interval for Prometheus.
)
// AlertInstanceManager defines the interface for querying the current alert instances.
type AlertInstanceManager interface {
GetAll(orgID int64) []*State
GetStatesForRuleUID(orgID int64, alertRuleUID string) []*State
}
type Manager struct {
log log.Logger
metrics *metrics.State
clock clock.Clock
cache *cache
ResendDelay time.Duration
instanceStore InstanceStore
imageService image.ImageService
historian Historian
externalURL *url.URL
}
func NewManager(metrics *metrics.State, externalURL *url.URL, instanceStore InstanceStore, imageService image.ImageService, clock clock.Clock, historian Historian) *Manager {
return &Manager{
cache: newCache(),
ResendDelay: ResendDelay, // TODO: make this configurable
log: log.New("ngalert.state.manager"),
metrics: metrics,
instanceStore: instanceStore,
imageService: imageService,
historian: historian,
clock: clock,
externalURL: externalURL,
}
}
func (st *Manager) Run(ctx context.Context) error {
ticker := st.clock.Ticker(MetricsScrapeInterval)
for {
select {
case <-ticker.C:
st.log.Debug("Recording state cache metrics", "now", st.clock.Now())
st.cache.recordMetrics(st.metrics)
case <-ctx.Done():
st.log.Debug("Stopping")
ticker.Stop()
return ctx.Err()
}
}
}
func (st *Manager) Warm(ctx context.Context, rulesReader RuleReader) {
if st.instanceStore == nil {
st.log.Info("Skip warming the state because instance store is not configured")
return
}
startTime := time.Now()
st.log.Info("Warming state cache for startup")
orgIds, err := st.instanceStore.FetchOrgIds(ctx)
if err != nil {
st.log.Error("Unable to fetch orgIds", "error", err)
}
statesCount := 0
states := make(map[int64]map[string]*ruleStates, len(orgIds))
for _, orgId := range orgIds {
// Get Rules
ruleCmd := ngModels.ListAlertRulesQuery{
OrgID: orgId,
}
if err := rulesReader.ListAlertRules(ctx, &ruleCmd); err != nil {
st.log.Error("Unable to fetch previous state", "error", err)
}
ruleByUID := make(map[string]*ngModels.AlertRule, len(ruleCmd.Result))
for _, rule := range ruleCmd.Result {
ruleByUID[rule.UID] = rule
}
orgStates := make(map[string]*ruleStates, len(ruleByUID))
states[orgId] = orgStates
// Get Instances
cmd := ngModels.ListAlertInstancesQuery{
RuleOrgID: orgId,
}
if err := st.instanceStore.ListAlertInstances(ctx, &cmd); err != nil {
st.log.Error("Unable to fetch previous state", "error", err)
}
for _, entry := range cmd.Result {
ruleForEntry, ok := ruleByUID[entry.RuleUID]
if !ok {
// TODO Should we delete the orphaned state from the db?
continue
}
rulesStates, ok := orgStates[entry.RuleUID]
if !ok {
rulesStates = &ruleStates{states: make(map[string]*State)}
orgStates[entry.RuleUID] = rulesStates
}
lbs := map[string]string(entry.Labels)
cacheID, err := entry.Labels.StringKey()
if err != nil {
st.log.Error("Error getting cacheId for entry", "error", err)
}
rulesStates.states[cacheID] = &State{
AlertRuleUID: entry.RuleUID,
OrgID: entry.RuleOrgID,
CacheID: cacheID,
Labels: lbs,
State: translateInstanceState(entry.CurrentState),
StateReason: entry.CurrentReason,
LastEvaluationString: "",
StartsAt: entry.CurrentStateSince,
EndsAt: entry.CurrentStateEnd,
LastEvaluationTime: entry.LastEvalTime,
Annotations: ruleForEntry.Annotations,
}
statesCount++
}
}
st.cache.setAllStates(states)
st.log.Info("State cache has been initialized", "states", statesCount, "duration", time.Since(startTime))
}
func (st *Manager) Get(orgID int64, alertRuleUID, stateId string) *State {
return st.cache.get(orgID, alertRuleUID, stateId)
}
// ResetStateByRuleUID deletes all entries in the state manager that match the given rule UID.
func (st *Manager) ResetStateByRuleUID(ctx context.Context, ruleKey ngModels.AlertRuleKey) []*State {
logger := st.log.New(ruleKey.LogContext()...)
logger.Debug("Resetting state of the rule")
states := st.cache.removeByRuleUID(ruleKey.OrgID, ruleKey.UID)
if len(states) > 0 && st.instanceStore != nil {
err := st.instanceStore.DeleteAlertInstancesByRule(ctx, ruleKey)
if err != nil {
logger.Error("Failed to delete states that belong to a rule from database", "error", err)
}
}
logger.Info("Rules state was reset", "states", len(states))
return states
}
// ProcessEvalResults updates the current states that belong to a rule with the evaluation results.
// if extraLabels is not empty, those labels will be added to every state. The extraLabels take precedence over rule labels and result labels
func (st *Manager) ProcessEvalResults(ctx context.Context, evaluatedAt time.Time, alertRule *ngModels.AlertRule, results eval.Results, extraLabels data.Labels) []*State {
logger := st.log.FromContext(ctx)
logger.Debug("State manager processing evaluation results", "resultCount", len(results))
var states []StateTransition
processedResults := make(map[string]*State, len(results))
for _, result := range results {
s := st.setNextState(ctx, alertRule, result, extraLabels, logger)
states = append(states, s)
processedResults[s.State.CacheID] = s.State
}
resolvedStates := st.staleResultsHandler(ctx, evaluatedAt, alertRule, processedResults, logger)
st.saveAlertStates(ctx, logger, states...)
changedStates := make([]StateTransition, 0, len(states))
for _, s := range states {
if s.changed() {
changedStates = append(changedStates, s)
}
}
if st.historian != nil {
st.historian.RecordStates(ctx, alertRule, changedStates)
}
deltas := append(states, resolvedStates...)
nextStates := make([]*State, 0, len(states))
for _, s := range deltas {
nextStates = append(nextStates, s.State)
}
return nextStates
}
// Set the current state based on evaluation results
func (st *Manager) setNextState(ctx context.Context, alertRule *ngModels.AlertRule, result eval.Result, extraLabels data.Labels, logger log.Logger) StateTransition {
currentState := st.cache.getOrCreate(ctx, st.log, alertRule, result, extraLabels, st.externalURL)
currentState.LastEvaluationTime = result.EvaluatedAt
currentState.EvaluationDuration = result.EvaluationDuration
currentState.Results = append(currentState.Results, Evaluation{
EvaluationTime: result.EvaluatedAt,
EvaluationState: result.State,
Values: NewEvaluationValues(result.Values),
Condition: alertRule.Condition,
})
currentState.LastEvaluationString = result.EvaluationString
currentState.TrimResults(alertRule)
oldState := currentState.State
oldReason := currentState.StateReason
logger.Debug("Setting alert state")
switch result.State {
case eval.Normal:
currentState.resultNormal(alertRule, result)
case eval.Alerting:
currentState.resultAlerting(alertRule, result)
case eval.Error:
currentState.resultError(alertRule, result)
case eval.NoData:
currentState.resultNoData(alertRule, result)
case eval.Pending: // we do not emit results with this state
}
// Set reason iff: result is different than state, reason is not Alerting or Normal
currentState.StateReason = ""
if currentState.State != result.State &&
result.State != eval.Normal &&
result.State != eval.Alerting {
currentState.StateReason = result.State.String()
}
// Set Resolved property so the scheduler knows to send a postable alert
// to Alertmanager.
currentState.Resolved = oldState == eval.Alerting && currentState.State == eval.Normal
if shouldTakeImage(currentState.State, oldState, currentState.Image, currentState.Resolved) {
image, err := takeImage(ctx, st.imageService, alertRule)
if err != nil {
logger.Warn("Failed to take an image",
"dashboard", alertRule.DashboardUID,
"panel", alertRule.PanelID,
"error", err)
} else if image != nil {
currentState.Image = image
}
}
st.cache.set(currentState)
nextState := StateTransition{
State: currentState,
PreviousState: oldState,
PreviousStateReason: oldReason,
}
return nextState
}
func (st *Manager) GetAll(orgID int64) []*State {
return st.cache.getAll(orgID)
}
func (st *Manager) GetStatesForRuleUID(orgID int64, alertRuleUID string) []*State {
return st.cache.getStatesForRuleUID(orgID, alertRuleUID)
}
func (st *Manager) Put(states []*State) {
for _, s := range states {
st.cache.set(s)
}
}
// TODO: Is the `State` type necessary? Should it embed the instance?
func (st *Manager) saveAlertStates(ctx context.Context, logger log.Logger, states ...StateTransition) {
if st.instanceStore == nil {
return
}
logger.Debug("Saving alert states", "count", len(states))
instances := make([]ngModels.AlertInstance, 0, len(states))
for _, s := range states {
labels := ngModels.InstanceLabels(s.Labels)
_, hash, err := labels.StringAndHash()
if err != nil {
logger.Error("Failed to create a key for alert state to save it to database. The state will be ignored ", "cacheID", s.CacheID, "error", err)
continue
}
fields := ngModels.AlertInstance{
AlertInstanceKey: ngModels.AlertInstanceKey{
RuleOrgID: s.OrgID,
RuleUID: s.AlertRuleUID,
LabelsHash: hash,
},
Labels: ngModels.InstanceLabels(s.Labels),
CurrentState: ngModels.InstanceStateType(s.State.State.String()),
CurrentReason: s.StateReason,
LastEvalTime: s.LastEvaluationTime,
CurrentStateSince: s.StartsAt,
CurrentStateEnd: s.EndsAt,
}
instances = append(instances, fields)
}
if err := st.instanceStore.SaveAlertInstances(ctx, instances...); err != nil {
type debugInfo struct {
State string
Labels string
}
debug := make([]debugInfo, 0)
for _, inst := range instances {
debug = append(debug, debugInfo{string(inst.CurrentState), data.Labels(inst.Labels).String()})
}
logger.Error("Failed to save alert states", "states", debug, "error", err)
}
}
// TODO: why wouldn't you allow other types like NoData or Error?
func translateInstanceState(state ngModels.InstanceStateType) eval.State {
switch {
case state == ngModels.InstanceStateFiring:
return eval.Alerting
case state == ngModels.InstanceStateNormal:
return eval.Normal
default:
return eval.Error
}
}
func (st *Manager) staleResultsHandler(ctx context.Context, evaluatedAt time.Time, alertRule *ngModels.AlertRule, states map[string]*State, logger log.Logger) []StateTransition {
// If we are removing two or more stale series it makes sense to share the resolved image as the alert rule is the same.
// TODO: We will need to change this when we support images without screenshots as each series will have a different image
var resolvedImage *ngModels.Image
var resolvedStates []StateTransition
allStates := st.GetStatesForRuleUID(alertRule.OrgID, alertRule.UID)
toDelete := make([]ngModels.AlertInstanceKey, 0)
for _, s := range allStates {
// Is the cached state in our recently processed results? If not, is it stale?
if _, ok := states[s.CacheID]; !ok && stateIsStale(evaluatedAt, s.LastEvaluationTime, alertRule.IntervalSeconds) {
logger.Info("Removing stale state entry", "cacheID", s.CacheID, "state", s.State, "reason", s.StateReason)
st.cache.deleteEntry(s.OrgID, s.AlertRuleUID, s.CacheID)
ilbs := ngModels.InstanceLabels(s.Labels)
_, labelsHash, err := ilbs.StringAndHash()
if err != nil {
logger.Error("Unable to get labelsHash", "error", err.Error(), s.AlertRuleUID)
}
toDelete = append(toDelete, ngModels.AlertInstanceKey{RuleOrgID: s.OrgID, RuleUID: s.AlertRuleUID, LabelsHash: labelsHash})
if s.State == eval.Alerting {
oldState := s.State
oldReason := s.StateReason
s.State = eval.Normal
s.StateReason = ngModels.StateReasonMissingSeries
s.EndsAt = evaluatedAt
s.Resolved = true
s.LastEvaluationTime = evaluatedAt
record := StateTransition{
State: s,
PreviousState: oldState,
PreviousStateReason: oldReason,
}
// If there is no resolved image for this rule then take one
if resolvedImage == nil {
image, err := takeImage(ctx, st.imageService, alertRule)
if err != nil {
logger.Warn("Failed to take an image",
"dashboard", alertRule.DashboardUID,
"panel", alertRule.PanelID,
"error", err)
} else if image != nil {
resolvedImage = image
}
}
s.Image = resolvedImage
resolvedStates = append(resolvedStates, record)
}
}
}
if st.historian != nil {
st.historian.RecordStates(ctx, alertRule, resolvedStates)
}
if st.instanceStore != nil {
if err := st.instanceStore.DeleteAlertInstances(ctx, toDelete...); err != nil {
logger.Error("Unable to delete stale instances from database", "error", err, "count", len(toDelete))
}
}
return resolvedStates
}
func stateIsStale(evaluatedAt time.Time, lastEval time.Time, intervalSeconds int64) bool {
return !lastEval.Add(2 * time.Duration(intervalSeconds) * time.Second).After(evaluatedAt)
}
| pkg/services/ngalert/state/manager.go | 1 | https://github.com/grafana/grafana/commit/623de12e354c8f92fd49802a04bafe5970fba0e9 | [
0.9792400598526001,
0.02568921633064747,
0.00016394047997891903,
0.0008768328698351979,
0.14896485209465027
] |
{
"id": 3,
"code_window": [
"\t\t\tif err != nil {\n",
"\t\t\t\tlogger.Error(\"Unable to get labelsHash\", \"error\", err.Error(), s.AlertRuleUID)\n",
"\t\t\t}\n",
"\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\tlogger.Error(\"Unable to get alert instance key to delete it from database. Ignoring\", \"error\", err.Error())\n",
"\t\t\t} else {\n",
"\t\t\t\ttoDelete = append(toDelete, key)\n"
],
"file_path": "pkg/services/ngalert/state/manager.go",
"type": "replace",
"edit_start_line_idx": 357
} | ---
aliases:
- /docs/grafana/latest/best-practices/
- /docs/grafana/latest/best-practices/common-observability-strategies/
- /docs/grafana/latest/getting-started/strategies/
- /docs/grafana/latest/best-practices/dashboard-management-maturity-levels/
- /docs/grafana/latest/best-practices/best-practices-for-creating-dashboards/
- /docs/grafana/latest/best-practices/best-practices-for-managing-dashboards/
- /docs/grafana/latest/dashboards/build-dashboards/best-practices/
description: Best practices for working with Grafana
title: Grafana dashboard best practices
menuTitle: Best practices
weight: 100
---
# Grafana dashboard best practices
This section provides information about best practices for intermediate Grafana administrators and users about how to build and maintain Grafana dashboards.
For more information about the different kinds of dashboards you can create, refer to [Grafana dashboards: A complete guide to all the different types you can build](https://grafana.com/blog/2022/06/06/grafana-dashboards-a-complete-guide-to-all-the-different-types-you-can-build/?pg=webinar-getting-started-with-grafana-dashboard-design-amer&plcmt=related-content-1).
## Common observability strategies
When you have a lot to monitor, like a server farm, you need a strategy to decide what is important enough to monitor. This page describes several common methods for choosing what to monitor.
A logical strategy allows you to make uniform dashboards and scale your observability platform more easily.
### Guidelines for usage
- The USE method tells you how happy your machines are, the RED method tells you how happy your users are.
- USE reports on causes of issues.
- RED reports on user experience and is more likely to report symptoms of problems.
- The best practice of alerting is to alert on symptoms rather than causes, so alerting should be done on RED dashboards.
### USE method
USE stands for:
- **Utilization -** Percent time the resource is busy, such as node CPU usage
- **Saturation -** Amount of work a resource has to do, often queue length or node load
- **Errors -** Count of error events
This method is best for hardware resources in infrastructure, such as CPU, memory, and network devices. For more information, refer to [The USE Method](http://www.brendangregg.com/usemethod.html).
### RED method
RED stands for:
- **Rate -** Requests per second
- **Errors -** Number of requests that are failing
- **Duration -** Amount of time these requests take, distribution of latency measurements
This method is most applicable to services, especially a microservices environment. For each of your services, instrument the code to expose these metrics for each component. RED dashboards are good for alerting and SLAs. A well-designed RED dashboard is a proxy for user experience.
For more information, refer to Tom Wilkie's blog post [The RED method: How to instrument your services](https://grafana.com/blog/2018/08/02/the-red-method-how-to-instrument-your-services).
### The Four Golden Signals
According to the [Google SRE handbook](https://landing.google.com/sre/sre-book/chapters/monitoring-distributed-systems/#xref_monitoring_golden-signals), if you can only measure four metrics of your user-facing system, focus on these four.
This method is similar to the RED method, but it includes saturation.
- **Latency -** Time taken to serve a request
- **Traffic -** How much demand is placed on your system
- **Errors -** Rate of requests that are failing
- **Saturation -** How "full" your system is
[Here's an example from Grafana Play](https://play.grafana.org/d/000000109/the-four-golden-signals?orgId=1).
## Dashboard management maturity model
_Dashboard management maturity_ refers to how well-designed and efficient your dashboard ecosystem is. We recommend periodically reviewing your dashboard setup to gauge where you are and how you can improve.
Broadly speaking, dashboard maturity can be defined as low, medium, or high.
Much of the content for this topic was taken from the KubeCon 2019 talk [Fool-Proof Kubernetes Dashboards for Sleep-Deprived Oncalls](https://www.youtube.com/watch?v=YE2aQFiMGfY).
### Low - default state
At this stage, you have no coherent dashboard management strategy. Almost everyone starts here.
How can you tell you are here?
- Everyone can modify your dashboards.
- Lots of copied dashboards, little to no dashboard reuse.
- One-off dashboards that hang around forever.
- No version control (dashboard JSON in version control).
- Lots of browsing for dashboards, searching for the right dashboard. This means lots of wasted time trying to find the dashboard you need.
- Not having any alerts to direct you to the right dashboard.
### Medium - methodical dashboards
At this stage, you are starting to manage your dashboard use with methodical dashboards. You might have laid out a strategy, but there are some things you could improve.
How can you tell you are here?
- Prevent sprawl by using template variables. For example, you don't need a separate dashboard for each node, you can use query variables. Even better, you can make the data source a template variable too, so you can reuse the same dashboard across different clusters and monitoring backends.
Refer to the list of [Variable examples]({{< relref "../../variables/#examples-of-templates-and-variables" >}}) if you want some ideas.
- Methodical dashboards according to an [observability strategy]({{< relref "#common-observability-strategies" >}}).
- Hierarchical dashboards with drill-downs to the next level.
{{< figure class="float-right" max-width="100%" src="/static/img/docs/best-practices/drill-down-example.png" caption="Example of using drill-down" >}}
- Dashboard design reflects service hierarchies. The example shown below uses the RED method (request and error rate on the left, latency duration on the right) with one row per service. The row order reflects the data flow.
{{< figure class="float-right" max-width="100%" src="/static/img/docs/best-practices/service-hierarchy-example.png" caption="Example of a service hierarchy" >}}
- Compare like to like: split service dashboards when the magnitude differs. Make sure aggregated metrics don't drown out important information.
- Expressive charts with meaningful use of color and normalizing axes where you can.
- Example of meaningful color: Blue means it's good, red means it's bad. [Thresholds]({{< relref "../../../panels-visualizations/configure-thresholds/" >}}) can help with that.
- Example of normalizing axes: When comparing CPU usage, measure by percentage rather than raw number, because machines can have a different number of cores. Normalizing CPU usage by the number of cores reduces cognitive load because the viewer can trust that at 100% all cores are being used, without having to know the number of CPUs.
- Directed browsing cuts down on "guessing."
- Template variables make it harder to “just browse” randomly or aimlessly.
- Most dashboards should be linked to by alerts.
- Browsing is directed with links. For more information, refer to [Manage dashboard links]({{< relref "../manage-dashboard-links" >}}).
- Version-controlled dashboard JSON.
### High - optimized use
At this stage, you have optimized your dashboard management use with a consistent and thoughtful strategy. It requires maintenance, but the results are worth it.
- Actively reducing sprawl.
- Regularly review existing dashboards to make sure they are still relevant.
- Only approved dashboards added to master dashboard list.
- Tracking dashboard use. If you're an Enterprise user, you can take advantage of [Usage insights]({{< relref "../../assess-dashboard-usage/" >}}).
- Consistency by design.
- Use scripting libraries to generate dashboards, ensure consistency in pattern and style.
- grafonnet (Jsonnet)
- grafanalib (Python)
- No editing in the browser. Dashboard viewers change views with variables.
- Browsing for dashboards is the exception, not the rule.
- Perform experimentation and testing in a separate Grafana instance dedicated to that purpose, not your production instance. When a dashboard in the test environment is proven useful, then add that dashboard to your main Grafana instance.
## Best practices for creating dashboards
This page outlines some best practices to follow when creating Grafana dashboards.
### Before you begin
Here are some principles to consider before you create a dashboard.
#### A dashboard should tell a story or answer a question
What story are you trying to tell with your dashboard? Try to create a logical progression of data, such as large to small or general to specific. What is the goal for this dashboard? (Hint: If the dashboard doesn't have a goal, then ask yourself if you really need the dashboard.)
Keep your graphs simple and focused on answering the question that you are asking. For example, if your question is "which servers are in trouble?", then maybe you don't need to show all the server data. Just show data for the ones in trouble.
#### Dashboards should reduce cognitive load, not add to it
_Cognitive load_ is basically how hard you need to think about something in order to figure it out. Make your dashboard easy to interpret. Other users and future you (when you're trying to figure out what broke at 2AM) will appreciate it.
Ask yourself:
- Can I tell what exactly each graph represents? Is it obvious, or do I have to think about it?
- If I show this to someone else, how long will it take them to figure it out? Will they get lost?
#### Have a monitoring strategy
It's easy to make new dashboards. It's harder to optimize dashboard creation and adhere to a plan, but it's worth it. This strategy should govern both your overall dashboard scheme and enforce consistency in individual dashboard design.
Refer to [Common observability strategies]({{< relref "#common-observability-strategies" >}}) and [Dashboard management maturity levels]({{< relref "#dashboard-management-maturity-model" >}}) for more information.
#### Write it down
Once you have a strategy or design guidelines, write them down to help maintain consistency over time. Check out this [Wikimedia runbook example](https://wikitech.wikimedia.org/wiki/Performance/Runbook/Grafana_best_practices).
### Best practices to follow
- When creating a new dashboard, make sure it has a meaningful name.
- If you are creating a dashboard to play or experiment, then put the word `TEST` or `TMP` in the name.
- Consider including your name or initials in the dashboard name or as a tag so that people know who owns the dashboard.
- Remove temporary experiment dashboards when you are done with them.
- If you create many related dashboards, think about how to cross-reference them for easy navigation. Refer to [Best practices for managing dashboards]({{< relref "#best-practices-for-managing-dashboards" >}}) for more information.
- Grafana retrieves data from a data source. A basic understanding of [data sources]({{< relref "../../../datasources/" >}}) in general and your specific is important.
- Avoid unnecessary dashboard refreshing to reduce the load on the network or backend. For example, if your data changes every hour, then you don't need to set the dashboard refresh rate to 30 seconds.
- Use the left and right Y-axes when displaying time series with different units or ranges.
- Add documentation to dashboards and panels.
- To add documentation to a dashboard, add a [Text panel visualization]({{< relref "../../../panels-visualizations/visualizations/text/" >}}) to the dashboard. Record things like the purpose of the dashboard, useful resource links, and any instructions users might need to interact with the dashboard. Check out this [Wikimedia example](https://grafana.wikimedia.org/d/000000066/resourceloader?orgId=1).
- To add documentation to a panel, edit the panel settings and add a description. Any text you add will appear if you hover your cursor over the small `i` in the top left corner of the panel.
- Reuse your dashboards and enforce consistency by using [templates and variables]({{< relref "../../variables" >}}).
- Be careful with stacking graph data. The visualizations can be misleading, and hide important data. We recommend turning it off in most cases.
## Best practices for managing dashboards
This page outlines some best practices to follow when managing Grafana dashboards.
### Before you begin
Here are some principles to consider before you start managing dashboards.
#### Strategic observability
There are several [common observability strategies]({{< relref "#common-observability-strategies" >}}). You should research them and decide whether one of them works for you or if you want to come up with your own. Either way, have a plan, write it down, and stick to it.
Adapt your strategy to changing needs as necessary.
#### Maturity level
What is your dashboard maturity level? Analyze your current dashboard setup and compare it to the [Dashboard management maturity model]({{< relref "#dashboard-management-maturity-model" >}}). Understanding where you are can help you decide how to get to where you want to be.
### Best practices to follow
- Avoid dashboard sprawl, meaning the uncontrolled growth of dashboards. Dashboard sprawl negatively affects time to find the right dashboard. Duplicating dashboards and changing “one thing” (worse: keeping original tags) is the easiest kind of sprawl.
- Periodically review the dashboards and remove unnecessary ones.
- If you create a temporary dashboard, perhaps to test something, prefix the name with `TEST: `. Delete the dashboard when you are finished.
- Copying dashboards with no significant changes is not a good idea.
- You miss out on updates to the original dashboard, such as documentation changes, bug fixes, or additions to metrics.
- In many cases copies are being made to simply customize the view by setting template parameters. This should instead be done by maintaining a link to the master dashboard and customizing the view with [URL parameters]({{< relref "../../../panels-visualizations/configure-data-links/#data-link-variables" >}}).
- When you must copy a dashboard, clearly rename it and _do not_ copy the dashboard tags. Tags are important metadata for dashboards that are used during search. Copying tags can result in false matches.
- Maintain a dashboard of dashboards or cross-reference dashboards. This can be done in several ways:
- Create dashboard links, panel, or data links. Links can go to other dashboards or to external systems. For more information, refer to [Manage dashboard links]({{< relref "../manage-dashboard-links/" >}}).
- Add a [Dashboard list panel]({{< relref "../../../panels-visualizations/visualizations/dashboard-list/" >}}). You can then customize what you see by doing tag or folder searches.
- Add a [Text panel]({{< relref "../../../panels-visualizations/visualizations/text/" >}}) and use markdown to customize the display.
| docs/sources/dashboards/build-dashboards/best-practices/index.md | 0 | https://github.com/grafana/grafana/commit/623de12e354c8f92fd49802a04bafe5970fba0e9 | [
0.00017681812460068613,
0.00016753179079387337,
0.00016310815408360213,
0.00016781983140390366,
0.0000033674925816740142
] |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.