hunk
dict
file
stringlengths
0
11.8M
file_path
stringlengths
2
234
label
int64
0
1
commit_url
stringlengths
74
103
dependency_score
listlengths
5
5
{ "id": 7, "code_window": [ " return {\n", " 'import': (target: string) => {\n", " expect(target).toBe(module);\n", " return Promise.resolve(contents);\n", " }\n", " };\n", "}\n" ], "labels": [ "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " expect(modules[target]).not.toBe(undefined);\n", " return Promise.resolve(modules[target]);\n" ], "file_path": "modules/@angular/core/test/linker/system_ng_module_factory_loader_spec.ts", "type": "replace", "edit_start_line_idx": 15 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {CompileTokenMetadata} from './compile_metadata'; import {StringMapWrapper} from './facade/collection'; import {StringWrapper, isArray, isBlank, isPresent, isPrimitive, isStrictStringMap} from './facade/lang'; import * as o from './output/output_ast'; export const MODULE_SUFFIX = ''; var CAMEL_CASE_REGEXP = /([A-Z])/g; export function camelCaseToDashCase(input: string): string { return StringWrapper.replaceAllMapped( input, CAMEL_CASE_REGEXP, (m: string[]) => { return '-' + m[1].toLowerCase(); }); } export function splitAtColon(input: string, defaultValues: string[]): string[] { const colonIndex = input.indexOf(':'); if (colonIndex == -1) return defaultValues; return [input.slice(0, colonIndex).trim(), input.slice(colonIndex + 1).trim()]; } export function sanitizeIdentifier(name: string): string { return StringWrapper.replaceAll(name, /\W/g, '_'); } export function visitValue(value: any, visitor: ValueVisitor, context: any): any { if (isArray(value)) { return visitor.visitArray(<any[]>value, context); } else if (isStrictStringMap(value)) { return visitor.visitStringMap(<{[key: string]: any}>value, context); } else if (isBlank(value) || isPrimitive(value)) { return visitor.visitPrimitive(value, context); } else { return visitor.visitOther(value, context); } } export interface ValueVisitor { visitArray(arr: any[], context: any): any; visitStringMap(map: {[key: string]: any}, context: any): any; visitPrimitive(value: any, context: any): any; visitOther(value: any, context: any): any; } export class ValueTransformer implements ValueVisitor { visitArray(arr: any[], context: any): any { return arr.map(value => visitValue(value, this, context)); } visitStringMap(map: {[key: string]: any}, context: any): any { var result = {}; StringMapWrapper.forEach(map, (value: any /** TODO #9100 */, key: any /** TODO #9100 */) => { (result as any /** TODO #9100 */)[key] = visitValue(value, this, context); }); return result; } visitPrimitive(value: any, context: any): any { return value; } visitOther(value: any, context: any): any { return value; } } export function assetUrl(pkg: string, path: string = null, type: string = 'src'): string { if (path == null) { return `asset:@angular/lib/${pkg}/index`; } else { return `asset:@angular/lib/${pkg}/src/${path}`; } } export function createDiTokenExpression(token: CompileTokenMetadata): o.Expression { if (isPresent(token.value)) { return o.literal(token.value); } else if (token.identifierIsInstance) { return o.importExpr(token.identifier) .instantiate([], o.importType(token.identifier, [], [o.TypeModifier.Const])); } else { return o.importExpr(token.identifier); } } export class SyncAsyncResult<T> { constructor(public syncResult: T, public asyncResult: Promise<T> = null) { if (!asyncResult) { this.asyncResult = Promise.resolve(syncResult); } } }
modules/@angular/compiler/src/util.ts
0
https://github.com/angular/angular/commit/d26a82749473803fbcbd735da46736779367521c
[ 0.000177246707607992, 0.0001702526060398668, 0.00016535466420464218, 0.00017025986744556576, 0.000003719847882166505 ]
{ "id": 7, "code_window": [ " return {\n", " 'import': (target: string) => {\n", " expect(target).toBe(module);\n", " return Promise.resolve(contents);\n", " }\n", " };\n", "}\n" ], "labels": [ "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " expect(modules[target]).not.toBe(undefined);\n", " return Promise.resolve(modules[target]);\n" ], "file_path": "modules/@angular/core/test/linker/system_ng_module_factory_loader_spec.ts", "type": "replace", "edit_start_line_idx": 15 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {__core_private__ as _} from '../../core/index'; export type ViewMetadata = typeof _._ViewMetadata; export const ViewMetadata: typeof _.ViewMetadata = _.ViewMetadata; export const FILL_STYLE_FLAG = _.FILL_STYLE_FLAG; export const flattenStyles: typeof _.flattenStyles = _.flattenStyles;
modules/@angular/compiler/test/private_import_core.ts
0
https://github.com/angular/angular/commit/d26a82749473803fbcbd735da46736779367521c
[ 0.00017718250455800444, 0.00017558783292770386, 0.00017399316129740328, 0.00017558783292770386, 0.0000015946716303005815 ]
{ "id": 8, "code_window": [ "}\n", "\n", "export function main() {\n", " describe('SystemJsNgModuleLoader', () => {\n", " it('loads a default factory by appending the factory suffix', async(() => {\n", " let loader = new SystemJsNgModuleLoader(new Compiler());\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep" ], "after_edit": [ " let oldSystem: any = null;\n", " beforeEach(() => {\n", " oldSystem = (global as any).System;\n", " (global as any).System = mockSystem({\n", " 'test.ngfactory':\n", " {'default': 'test module factory', 'NamedNgFactory': 'test NamedNgFactory'},\n", " 'prefixed/test/suffixed': {'NamedNgFactory': 'test module factory'}\n", " });\n", " });\n", " afterEach(() => { (global as any).System = oldSystem; });\n", "\n" ], "file_path": "modules/@angular/core/test/linker/system_ng_module_factory_loader_spec.ts", "type": "add", "edit_start_line_idx": 23 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {Compiler, SystemJsNgModuleLoader} from '@angular/core'; import {async, tick} from '@angular/core/testing'; import {beforeEach, ddescribe, describe, expect, iit, it, xit} from '@angular/core/testing/testing_internal'; function mockSystem(module: string, contents: any) { return { 'import': (target: string) => { expect(target).toBe(module); return Promise.resolve(contents); } }; } export function main() { describe('SystemJsNgModuleLoader', () => { it('loads a default factory by appending the factory suffix', async(() => { let loader = new SystemJsNgModuleLoader(new Compiler()); loader._system = () => mockSystem('test.ngfactory', {'default': 'test module factory'}); loader.load('test').then(contents => { expect(contents).toBe('test module factory'); }); })); it('loads a named factory by appending the factory suffix', async(() => { let loader = new SystemJsNgModuleLoader(new Compiler()); loader._system = () => mockSystem('test.ngfactory', {'NamedNgFactory': 'test module factory'}); loader.load('test#Named').then(contents => { expect(contents).toBe('test module factory'); }); })); it('loads a named factory with a configured prefix and suffix', async(() => { let loader = new SystemJsNgModuleLoader(new Compiler(), { factoryPathPrefix: 'prefixed/', factoryPathSuffix: '/suffixed', }); loader._system = () => mockSystem('prefixed/test/suffixed', {'NamedNgFactory': 'test module factory'}); loader.load('test#Named').then(contents => { expect(contents).toBe('test module factory'); }); })); }); };
modules/@angular/core/test/linker/system_ng_module_factory_loader_spec.ts
1
https://github.com/angular/angular/commit/d26a82749473803fbcbd735da46736779367521c
[ 0.9979744553565979, 0.5982810258865356, 0.00017202612070832402, 0.9951045513153076, 0.4883235692977905 ]
{ "id": 8, "code_window": [ "}\n", "\n", "export function main() {\n", " describe('SystemJsNgModuleLoader', () => {\n", " it('loads a default factory by appending the factory suffix', async(() => {\n", " let loader = new SystemJsNgModuleLoader(new Compiler());\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep" ], "after_edit": [ " let oldSystem: any = null;\n", " beforeEach(() => {\n", " oldSystem = (global as any).System;\n", " (global as any).System = mockSystem({\n", " 'test.ngfactory':\n", " {'default': 'test module factory', 'NamedNgFactory': 'test NamedNgFactory'},\n", " 'prefixed/test/suffixed': {'NamedNgFactory': 'test module factory'}\n", " });\n", " });\n", " afterEach(() => { (global as any).System = oldSystem; });\n", "\n" ], "file_path": "modules/@angular/core/test/linker/system_ng_module_factory_loader_spec.ts", "type": "add", "edit_start_line_idx": 23 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {AnimationMetadata, animate, group, sequence, style, transition, trigger} from '@angular/core'; import {AsyncTestCompleter, beforeEach, beforeEachProviders, ddescribe, describe, expect, iit, inject, it, xdescribe, xit} from '@angular/core/testing/testing_internal'; import {StringMapWrapper} from '../../../platform-browser-dynamic/src/facade/collection'; import {AnimationCompiler, CompiledAnimationTriggerResult} from '../../src/animation/animation_compiler'; import {CompileAnimationEntryMetadata, CompileDirectiveMetadata, CompileTemplateMetadata, CompileTypeMetadata} from '../../src/compile_metadata'; import {CompileMetadataResolver} from '../../src/metadata_resolver'; export function main() { describe('RuntimeAnimationCompiler', () => { var resolver: any /** TODO #9100 */; beforeEach( inject([CompileMetadataResolver], (res: CompileMetadataResolver) => { resolver = res; })); var compiler = new AnimationCompiler(); var compileAnimations = (component: CompileDirectiveMetadata): CompiledAnimationTriggerResult => { var result = compiler.compileComponent(component, []); return result.triggers[0]; }; var compileTriggers = (input: any[]) => { var entries: CompileAnimationEntryMetadata[] = input.map(entry => { var animationTriggerData = trigger(entry[0], entry[1]); return resolver.getAnimationEntryMetadata(animationTriggerData); }); var component = CompileDirectiveMetadata.create({ type: new CompileTypeMetadata({name: 'myCmp'}), template: new CompileTemplateMetadata({animations: entries}) }); return compileAnimations(component); }; var compileSequence = (seq: AnimationMetadata) => { return compileTriggers([['myAnimation', [transition('state1 => state2', seq)]]]); }; it('should throw an exception containing all the inner animation parser errors', () => { var animation = sequence([ style({'color': 'red'}), animate(1000, style({'font-size': '100px'})), style({'color': 'blue'}), animate(1000, style(':missing_state')), style({'color': 'gold'}), animate(1000, style('broken_state')) ]); var capturedErrorMessage: string; try { compileSequence(animation); } catch (e) { capturedErrorMessage = e.message; } expect(capturedErrorMessage) .toMatch(/Unable to apply styles due to missing a state: "missing_state"/g); expect(capturedErrorMessage) .toMatch(/Animation states via styles must be prefixed with a ":"/); }); it('should throw an error when two or more animation triggers contain the same name', () => { var t1Data: any[] = []; var t2Data: any[] = []; expect(() => { compileTriggers([['myTrigger', t1Data], ['myTrigger', t2Data]]); }).toThrowError(/The animation trigger "myTrigger" has already been registered on "myCmp"/); }); }); }
modules/@angular/compiler/test/animation/animation_compiler_spec.ts
0
https://github.com/angular/angular/commit/d26a82749473803fbcbd735da46736779367521c
[ 0.0006872869562357664, 0.00023637844424229115, 0.00016582659736741334, 0.0001735455880407244, 0.00017045503773260862 ]
{ "id": 8, "code_window": [ "}\n", "\n", "export function main() {\n", " describe('SystemJsNgModuleLoader', () => {\n", " it('loads a default factory by appending the factory suffix', async(() => {\n", " let loader = new SystemJsNgModuleLoader(new Compiler());\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep" ], "after_edit": [ " let oldSystem: any = null;\n", " beforeEach(() => {\n", " oldSystem = (global as any).System;\n", " (global as any).System = mockSystem({\n", " 'test.ngfactory':\n", " {'default': 'test module factory', 'NamedNgFactory': 'test NamedNgFactory'},\n", " 'prefixed/test/suffixed': {'NamedNgFactory': 'test module factory'}\n", " });\n", " });\n", " afterEach(() => { (global as any).System = oldSystem; });\n", "\n" ], "file_path": "modules/@angular/core/test/linker/system_ng_module_factory_loader_spec.ts", "type": "add", "edit_start_line_idx": 23 }
<!doctype html> <html> <head> <link rel="import" href="binary_tree.html"> </head> <body> <h2>Params</h2> <form> Depth: <input type="number" name="depth" placeholder="depth" value="9"> <br> <button>Apply</button> </form> <h2>Polymer tree benchmark</h2> <p> <button id="destroyDom">destroyDom</button> <button id="createDom">createDom</button> </p> <div> <binary-tree id="root"></binary-tree> </div> <script src="../../bootstrap_plain.js"></script> </body> </html>
modules/benchmarks/src/tree/polymer/index.html
0
https://github.com/angular/angular/commit/d26a82749473803fbcbd735da46736779367521c
[ 0.00017384838429279625, 0.00017220932932104915, 0.0001695118990028277, 0.00017326767556369305, 0.0000019220412923459662 ]
{ "id": 8, "code_window": [ "}\n", "\n", "export function main() {\n", " describe('SystemJsNgModuleLoader', () => {\n", " it('loads a default factory by appending the factory suffix', async(() => {\n", " let loader = new SystemJsNgModuleLoader(new Compiler());\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep" ], "after_edit": [ " let oldSystem: any = null;\n", " beforeEach(() => {\n", " oldSystem = (global as any).System;\n", " (global as any).System = mockSystem({\n", " 'test.ngfactory':\n", " {'default': 'test module factory', 'NamedNgFactory': 'test NamedNgFactory'},\n", " 'prefixed/test/suffixed': {'NamedNgFactory': 'test module factory'}\n", " });\n", " });\n", " afterEach(() => { (global as any).System = oldSystem; });\n", "\n" ], "file_path": "modules/@angular/core/test/linker/system_ng_module_factory_loader_spec.ts", "type": "add", "edit_start_line_idx": 23 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {beforeEach, ddescribe, describe, expect, iit, inject, it, xit} from '@angular/core/testing/testing_internal'; import {URLSearchParams} from '../src/url_search_params'; export function main() { describe('URLSearchParams', () => { it('should conform to spec', () => { var paramsString = 'q=URLUtils.searchParams&topic=api'; var searchParams = new URLSearchParams(paramsString); // Tests borrowed from example at // https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams // Compliant with spec described at https://url.spec.whatwg.org/#urlsearchparams expect(searchParams.has('topic')).toBe(true); expect(searchParams.has('foo')).toBe(false); expect(searchParams.get('topic')).toEqual('api'); expect(searchParams.getAll('topic')).toEqual(['api']); expect(searchParams.get('foo')).toBe(null); searchParams.append('topic', 'webdev'); expect(searchParams.getAll('topic')).toEqual(['api', 'webdev']); expect(searchParams.toString()).toEqual('q=URLUtils.searchParams&topic=api&topic=webdev'); searchParams.delete('topic'); expect(searchParams.toString()).toEqual('q=URLUtils.searchParams'); // Test default constructor expect(new URLSearchParams().toString()).toBe(''); }); it('should optionally accept a custom parser', () => { let fooEveryThingParser = { encodeKey() { return 'I AM KEY'; }, encodeValue() { return 'I AM VALUE'; } }; let params = new URLSearchParams('', fooEveryThingParser); params.set('myKey', 'myValue'); expect(params.toString()).toBe('I AM KEY=I AM VALUE'); }); it('should encode special characters in params', () => { var searchParams = new URLSearchParams(); searchParams.append('a', '1+1'); searchParams.append('b c', '2'); searchParams.append('d%', '3$'); expect(searchParams.toString()).toEqual('a=1+1&b%20c=2&d%25=3$'); }); it('should not encode allowed characters', () => { /* * https://tools.ietf.org/html/rfc3986#section-3.4 * Allowed: ( pchar / "/" / "?" ) * pchar: unreserved / pct-encoded / sub-delims / ":" / "@" * unreserved: ALPHA / DIGIT / "-" / "." / "_" / "~" * pct-encoded: "%" HEXDIG HEXDIG * sub-delims: "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "=" * * & and = are excluded and should be encoded inside keys and values * because URLSearchParams is responsible for inserting this. **/ let params = new URLSearchParams(); '! $ \' ( ) * + , ; A 9 - . _ ~ ? / ='.split(' ').forEach( (char, idx) => { params.set(`a${idx}`, char); }); expect(params.toString()) .toBe( `a0=!&a1=$&a2=\'&a3=(&a4=)&a5=*&a6=+&a7=,&a8=;&a9=A&a10=9&a11=-&a12=.&a13=_&a14=~&a15=?&a16=/&a17==` .replace(/\s/g, '')); // Original example from https://github.com/angular/angular/issues/9348 for posterity params = new URLSearchParams(); params.set('q', 'repo:janbaer/howcani+type:issue'); params.set('sort', 'created'); params.set('order', 'desc'); params.set('page', '1'); expect(params.toString()) .toBe('q=repo:janbaer/howcani+type:issue&sort=created&order=desc&page=1'); }); it('should support map-like merging operation via setAll()', () => { var mapA = new URLSearchParams('a=1&a=2&a=3&c=8'); var mapB = new URLSearchParams('a=4&a=5&a=6&b=7'); mapA.setAll(mapB); expect(mapA.has('a')).toBe(true); expect(mapA.has('b')).toBe(true); expect(mapA.has('c')).toBe(true); expect(mapA.getAll('a')).toEqual(['4']); expect(mapA.getAll('b')).toEqual(['7']); expect(mapA.getAll('c')).toEqual(['8']); expect(mapA.toString()).toEqual('a=4&c=8&b=7'); }); it('should support multimap-like merging operation via appendAll()', () => { var mapA = new URLSearchParams('a=1&a=2&a=3&c=8'); var mapB = new URLSearchParams('a=4&a=5&a=6&b=7'); mapA.appendAll(mapB); expect(mapA.has('a')).toBe(true); expect(mapA.has('b')).toBe(true); expect(mapA.has('c')).toBe(true); expect(mapA.getAll('a')).toEqual(['1', '2', '3', '4', '5', '6']); expect(mapA.getAll('b')).toEqual(['7']); expect(mapA.getAll('c')).toEqual(['8']); expect(mapA.toString()).toEqual('a=1&a=2&a=3&a=4&a=5&a=6&c=8&b=7'); }); it('should support multimap-like merging operation via replaceAll()', () => { var mapA = new URLSearchParams('a=1&a=2&a=3&c=8'); var mapB = new URLSearchParams('a=4&a=5&a=6&b=7'); mapA.replaceAll(mapB); expect(mapA.has('a')).toBe(true); expect(mapA.has('b')).toBe(true); expect(mapA.has('c')).toBe(true); expect(mapA.getAll('a')).toEqual(['4', '5', '6']); expect(mapA.getAll('b')).toEqual(['7']); expect(mapA.getAll('c')).toEqual(['8']); expect(mapA.toString()).toEqual('a=4&a=5&a=6&c=8&b=7'); }); it('should support a clone operation via clone()', () => { var fooQueryEncoder = { encodeKey(k: string) { return encodeURIComponent(k); }, encodeValue(v: string) { return encodeURIComponent(v); } }; var paramsA = new URLSearchParams('', fooQueryEncoder); paramsA.set('a', '2'); paramsA.set('q', '4+'); paramsA.set('c', '8'); var paramsB = new URLSearchParams(); paramsB.set('a', '2'); paramsB.set('q', '4+'); paramsB.set('c', '8'); expect(paramsB.toString()).toEqual('a=2&q=4+&c=8'); var paramsC = paramsA.clone(); expect(paramsC.has('a')).toBe(true); expect(paramsC.has('b')).toBe(false); expect(paramsC.has('c')).toBe(true); expect(paramsC.toString()).toEqual('a=2&q=4%2B&c=8'); }); }); }
modules/@angular/http/test/url_search_params_spec.ts
0
https://github.com/angular/angular/commit/d26a82749473803fbcbd735da46736779367521c
[ 0.0003348648315295577, 0.00018287787679582834, 0.0001610868057468906, 0.00017391395522281528, 0.00003950176323996857 ]
{ "id": 9, "code_window": [ " it('loads a default factory by appending the factory suffix', async(() => {\n", " let loader = new SystemJsNgModuleLoader(new Compiler());\n", " loader._system = () => mockSystem('test.ngfactory', {'default': 'test module factory'});\n", " loader.load('test').then(contents => { expect(contents).toBe('test module factory'); });\n", " }));\n", " it('loads a named factory by appending the factory suffix', async(() => {\n", " let loader = new SystemJsNgModuleLoader(new Compiler());\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "modules/@angular/core/test/linker/system_ng_module_factory_loader_spec.ts", "type": "replace", "edit_start_line_idx": 25 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {Compiler, SystemJsNgModuleLoader} from '@angular/core'; import {async, tick} from '@angular/core/testing'; import {beforeEach, ddescribe, describe, expect, iit, it, xit} from '@angular/core/testing/testing_internal'; function mockSystem(module: string, contents: any) { return { 'import': (target: string) => { expect(target).toBe(module); return Promise.resolve(contents); } }; } export function main() { describe('SystemJsNgModuleLoader', () => { it('loads a default factory by appending the factory suffix', async(() => { let loader = new SystemJsNgModuleLoader(new Compiler()); loader._system = () => mockSystem('test.ngfactory', {'default': 'test module factory'}); loader.load('test').then(contents => { expect(contents).toBe('test module factory'); }); })); it('loads a named factory by appending the factory suffix', async(() => { let loader = new SystemJsNgModuleLoader(new Compiler()); loader._system = () => mockSystem('test.ngfactory', {'NamedNgFactory': 'test module factory'}); loader.load('test#Named').then(contents => { expect(contents).toBe('test module factory'); }); })); it('loads a named factory with a configured prefix and suffix', async(() => { let loader = new SystemJsNgModuleLoader(new Compiler(), { factoryPathPrefix: 'prefixed/', factoryPathSuffix: '/suffixed', }); loader._system = () => mockSystem('prefixed/test/suffixed', {'NamedNgFactory': 'test module factory'}); loader.load('test#Named').then(contents => { expect(contents).toBe('test module factory'); }); })); }); };
modules/@angular/core/test/linker/system_ng_module_factory_loader_spec.ts
1
https://github.com/angular/angular/commit/d26a82749473803fbcbd735da46736779367521c
[ 0.9984357953071594, 0.5817214250564575, 0.00016518683696631342, 0.9119361639022827, 0.4755355715751648 ]
{ "id": 9, "code_window": [ " it('loads a default factory by appending the factory suffix', async(() => {\n", " let loader = new SystemJsNgModuleLoader(new Compiler());\n", " loader._system = () => mockSystem('test.ngfactory', {'default': 'test module factory'});\n", " loader.load('test').then(contents => { expect(contents).toBe('test module factory'); });\n", " }));\n", " it('loads a named factory by appending the factory suffix', async(() => {\n", " let loader = new SystemJsNgModuleLoader(new Compiler());\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "modules/@angular/core/test/linker/system_ng_module_factory_loader_spec.ts", "type": "replace", "edit_start_line_idx": 25 }
5.4.1
.nvmrc
0
https://github.com/angular/angular/commit/d26a82749473803fbcbd735da46736779367521c
[ 0.00016800992307253182, 0.00016800992307253182, 0.00016800992307253182, 0.00016800992307253182, 0 ]
{ "id": 9, "code_window": [ " it('loads a default factory by appending the factory suffix', async(() => {\n", " let loader = new SystemJsNgModuleLoader(new Compiler());\n", " loader._system = () => mockSystem('test.ngfactory', {'default': 'test module factory'});\n", " loader.load('test').then(contents => { expect(contents).toBe('test module factory'); });\n", " }));\n", " it('loads a named factory by appending the factory suffix', async(() => {\n", " let loader = new SystemJsNgModuleLoader(new Compiler());\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "modules/@angular/core/test/linker/system_ng_module_factory_loader_spec.ts", "type": "replace", "edit_start_line_idx": 25 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {APP_INITIALIZER, CUSTOM_ELEMENTS_SCHEMA, Compiler, Component, Directive, ErrorHandler, Inject, Input, NgModule, OnDestroy, PLATFORM_INITIALIZER, Pipe, Provider, createPlatformFactory} from '@angular/core'; import {ApplicationRef, destroyPlatform} from '@angular/core/src/application_ref'; import {Console} from '@angular/core/src/console'; import {ComponentRef} from '@angular/core/src/linker/component_factory'; import {Testability, TestabilityRegistry} from '@angular/core/src/testability/testability'; import {AsyncTestCompleter, Log, afterEach, beforeEach, beforeEachProviders, ddescribe, describe, iit, inject, it} from '@angular/core/testing/testing_internal'; import {BrowserModule} from '@angular/platform-browser'; import {platformBrowserDynamic} from '@angular/platform-browser-dynamic'; import {getDOM} from '@angular/platform-browser/src/dom/dom_adapter'; import {DOCUMENT} from '@angular/platform-browser/src/dom/dom_tokens'; import {expect} from '@angular/platform-browser/testing/matchers'; import {stringify} from '../../src/facade/lang'; @Component({selector: 'hello-app', template: '{{greeting}} world!'}) class HelloRootCmp { greeting: string; constructor() { this.greeting = 'hello'; } } @Component({selector: 'hello-app', template: 'before: <ng-content></ng-content> after: done'}) class HelloRootCmpContent { constructor() {} } @Component({selector: 'hello-app-2', template: '{{greeting}} world, again!'}) class HelloRootCmp2 { greeting: string; constructor() { this.greeting = 'hello'; } } @Component({selector: 'hello-app', template: ''}) class HelloRootCmp3 { appBinding: any /** TODO #9100 */; constructor(@Inject('appBinding') appBinding: any /** TODO #9100 */) { this.appBinding = appBinding; } } @Component({selector: 'hello-app', template: ''}) class HelloRootCmp4 { appRef: any /** TODO #9100 */; constructor(@Inject(ApplicationRef) appRef: ApplicationRef) { this.appRef = appRef; } } @Component({selector: 'hello-app'}) class HelloRootMissingTemplate { } @Directive({selector: 'hello-app'}) class HelloRootDirectiveIsNotCmp { } @Component({selector: 'hello-app', template: ''}) class HelloOnDestroyTickCmp implements OnDestroy { appRef: ApplicationRef; constructor(@Inject(ApplicationRef) appRef: ApplicationRef) { this.appRef = appRef; } ngOnDestroy(): void { this.appRef.tick(); } } @Component({selector: 'hello-app', templateUrl: './sometemplate.html'}) class HelloUrlCmp { greeting = 'hello'; } @Directive({selector: '[someDir]', host: {'[title]': 'someDir'}}) class SomeDirective { @Input() someDir: string; } @Pipe({name: 'somePipe'}) class SomePipe { transform(value: string): any { return `transformed ${value}`; } } @Component({selector: 'hello-app', template: `<div [someDir]="'someValue' | somePipe"></div>`}) class HelloCmpUsingPlatformDirectiveAndPipe { show: boolean = false; } @Component({selector: 'hello-app', template: '<some-el [someProp]="true">hello world!</some-el>'}) class HelloCmpUsingCustomElement { } class MockConsole { res: any[] = []; error(s: any): void { this.res.push(s); } } class DummyConsole implements Console { public warnings: string[] = []; log(message: string) {} warn(message: string) { this.warnings.push(message); } } class TestModule {} function bootstrap(cmpType: any, providers: Provider[] = []): Promise<any> { @NgModule({ imports: [BrowserModule], declarations: [cmpType], bootstrap: [cmpType], providers: providers, schemas: [CUSTOM_ELEMENTS_SCHEMA] }) class TestModule { } return platformBrowserDynamic().bootstrapModule(TestModule); } export function main() { var fakeDoc: any /** TODO #9100 */, el: any /** TODO #9100 */, el2: any /** TODO #9100 */, testProviders: Provider[], lightDom: any /** TODO #9100 */; describe('bootstrap factory method', () => { let compilerConsole: DummyConsole; beforeEachProviders(() => { return [Log]; }); beforeEach(() => { destroyPlatform(); fakeDoc = getDOM().createHtmlDocument(); el = getDOM().createElement('hello-app', fakeDoc); el2 = getDOM().createElement('hello-app-2', fakeDoc); lightDom = getDOM().createElement('light-dom-el', fakeDoc); getDOM().appendChild(fakeDoc.body, el); getDOM().appendChild(fakeDoc.body, el2); getDOM().appendChild(el, lightDom); getDOM().setText(lightDom, 'loading'); compilerConsole = new DummyConsole(); testProviders = [{provide: DOCUMENT, useValue: fakeDoc}, {provide: Console, useValue: compilerConsole}]; }); afterEach(destroyPlatform); it('should throw if bootstrapped Directive is not a Component', () => { expect(() => bootstrap(HelloRootDirectiveIsNotCmp)) .toThrowError( `Could not compile '${stringify(HelloRootDirectiveIsNotCmp)}' because it is not a component.`); }); it('should throw if no element is found', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { var logger = new MockConsole(); var errorHandler = new ErrorHandler(false); errorHandler._console = logger as any; bootstrap(HelloRootCmp, [ {provide: ErrorHandler, useValue: errorHandler} ]).then(null, (reason) => { expect(reason.message).toContain('The selector "hello-app" did not match any elements'); async.done(); return null; }); })); if (getDOM().supportsDOMEvents()) { it('should forward the error to promise when bootstrap fails', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { var logger = new MockConsole(); var errorHandler = new ErrorHandler(false); errorHandler._console = logger as any; var refPromise = bootstrap(HelloRootCmp, [{provide: ErrorHandler, useValue: errorHandler}]); refPromise.then(null, (reason: any) => { expect(reason.message) .toContain('The selector "hello-app" did not match any elements'); async.done(); }); })); it('should invoke the default exception handler when bootstrap fails', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { var logger = new MockConsole(); var errorHandler = new ErrorHandler(false); errorHandler._console = logger as any; var refPromise = bootstrap(HelloRootCmp, [{provide: ErrorHandler, useValue: errorHandler}]); refPromise.then(null, (reason) => { expect(logger.res.join('')) .toContain('The selector "hello-app" did not match any elements'); async.done(); return null; }); })); } it('should create an injector promise', () => { var refPromise = bootstrap(HelloRootCmp, testProviders); expect(refPromise).not.toBe(null); }); it('should display hello world', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { var refPromise = bootstrap(HelloRootCmp, testProviders); refPromise.then((ref) => { expect(el).toHaveText('hello world!'); async.done(); }); })); it('should throw a descriptive error if BrowserModule is installed again via a lazily loaded module', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { @NgModule({imports: [BrowserModule]}) class AsyncModule { } bootstrap(HelloRootCmp, testProviders) .then((ref: ComponentRef<HelloRootCmp>) => { let compiler: Compiler = ref.injector.get(Compiler); return compiler.compileModuleAsync(AsyncModule).then(factory => { expect(() => factory.create(ref.injector)) .toThrowError( `BrowserModule has already been loaded. If you need access to common directives such as NgIf and NgFor from a lazy loaded module, import CommonModule instead.`); }); }) .then(() => async.done(), err => async.fail(err)); })); it('should support multiple calls to bootstrap', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { var refPromise1 = bootstrap(HelloRootCmp, testProviders); var refPromise2 = bootstrap(HelloRootCmp2, testProviders); Promise.all([refPromise1, refPromise2]).then((refs) => { expect(el).toHaveText('hello world!'); expect(el2).toHaveText('hello world, again!'); async.done(); }); })); it('should not crash if change detection is invoked when the root component is disposed', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { bootstrap(HelloOnDestroyTickCmp, testProviders).then((ref) => { expect(() => ref.destroy()).not.toThrow(); async.done(); }); })); it('should unregister change detectors when components are disposed', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { bootstrap(HelloRootCmp, testProviders).then((ref) => { const appRef = ref.injector.get(ApplicationRef); ref.destroy(); expect(() => appRef.tick()).not.toThrow(); async.done(); }); })); it('should make the provided bindings available to the application component', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { var refPromise = bootstrap( HelloRootCmp3, [testProviders, {provide: 'appBinding', useValue: 'BoundValue'}]); refPromise.then((ref) => { expect(ref.injector.get('appBinding')).toEqual('BoundValue'); async.done(); }); })); it('should avoid cyclic dependencies when root component requires Lifecycle through DI', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { var refPromise = bootstrap(HelloRootCmp4, testProviders); refPromise.then((ref) => { const appRef = ref.injector.get(ApplicationRef); expect(appRef).toBeDefined(); async.done(); }); })); it('should run platform initializers', inject([Log, AsyncTestCompleter], (log: Log, async: AsyncTestCompleter) => { let p = createPlatformFactory(platformBrowserDynamic, 'someName', [ {provide: PLATFORM_INITIALIZER, useValue: log.fn('platform_init1'), multi: true}, {provide: PLATFORM_INITIALIZER, useValue: log.fn('platform_init2'), multi: true} ])(); @NgModule({ imports: [BrowserModule], providers: [ {provide: APP_INITIALIZER, useValue: log.fn('app_init1'), multi: true}, {provide: APP_INITIALIZER, useValue: log.fn('app_init2'), multi: true} ] }) class SomeModule { ngDoBootstrap() {} } expect(log.result()).toEqual('platform_init1; platform_init2'); log.clear(); p.bootstrapModule(SomeModule).then(() => { expect(log.result()).toEqual('app_init1; app_init2'); async.done(); }); })); it('should register each application with the testability registry', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { var refPromise1: Promise<ComponentRef<any>> = bootstrap(HelloRootCmp, testProviders); var refPromise2: Promise<ComponentRef<any>> = bootstrap(HelloRootCmp2, testProviders); Promise.all([refPromise1, refPromise2]).then((refs: ComponentRef<any>[]) => { var registry = refs[0].injector.get(TestabilityRegistry); var testabilities = [refs[0].injector.get(Testability), refs[1].injector.get(Testability)]; Promise.all(testabilities).then((testabilities: Testability[]) => { expect(registry.findTestabilityInTree(el)).toEqual(testabilities[0]); expect(registry.findTestabilityInTree(el2)).toEqual(testabilities[1]); async.done(); }); }); })); it('should allow to pass schemas', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { bootstrap(HelloCmpUsingCustomElement, testProviders).then((compRef) => { expect(el).toHaveText('hello world!'); async.done(); }); })); }); }
modules/@angular/platform-browser/test/browser/bootstrap_spec.ts
0
https://github.com/angular/angular/commit/d26a82749473803fbcbd735da46736779367521c
[ 0.00028421945171430707, 0.0001733635872369632, 0.000166328129125759, 0.000170316721778363, 0.0000194010826817248 ]
{ "id": 9, "code_window": [ " it('loads a default factory by appending the factory suffix', async(() => {\n", " let loader = new SystemJsNgModuleLoader(new Compiler());\n", " loader._system = () => mockSystem('test.ngfactory', {'default': 'test module factory'});\n", " loader.load('test').then(contents => { expect(contents).toBe('test module factory'); });\n", " }));\n", " it('loads a named factory by appending the factory suffix', async(() => {\n", " let loader = new SystemJsNgModuleLoader(new Compiler());\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "modules/@angular/core/test/linker/system_ng_module_factory_loader_spec.ts", "type": "replace", "edit_start_line_idx": 25 }
/** @experimental */ export declare const platformWorkerAppDynamic: (extraProviders?: Provider[]) => PlatformRef;
tools/public_api_guard/platform-webworker-dynamic/index.d.ts
0
https://github.com/angular/angular/commit/d26a82749473803fbcbd735da46736779367521c
[ 0.00016729440540075302, 0.00016729440540075302, 0.00016729440540075302, 0.00016729440540075302, 0 ]
{ "id": 10, "code_window": [ " loader.load('test').then(contents => { expect(contents).toBe('test module factory'); });\n", " }));\n", " it('loads a named factory by appending the factory suffix', async(() => {\n", " let loader = new SystemJsNgModuleLoader(new Compiler());\n", " loader._system = () =>\n", " mockSystem('test.ngfactory', {'NamedNgFactory': 'test module factory'});\n", " loader.load('test#Named').then(contents => {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep" ], "after_edit": [], "file_path": "modules/@angular/core/test/linker/system_ng_module_factory_loader_spec.ts", "type": "replace", "edit_start_line_idx": 30 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {Compiler, SystemJsNgModuleLoader} from '@angular/core'; import {async, tick} from '@angular/core/testing'; import {beforeEach, ddescribe, describe, expect, iit, it, xit} from '@angular/core/testing/testing_internal'; function mockSystem(module: string, contents: any) { return { 'import': (target: string) => { expect(target).toBe(module); return Promise.resolve(contents); } }; } export function main() { describe('SystemJsNgModuleLoader', () => { it('loads a default factory by appending the factory suffix', async(() => { let loader = new SystemJsNgModuleLoader(new Compiler()); loader._system = () => mockSystem('test.ngfactory', {'default': 'test module factory'}); loader.load('test').then(contents => { expect(contents).toBe('test module factory'); }); })); it('loads a named factory by appending the factory suffix', async(() => { let loader = new SystemJsNgModuleLoader(new Compiler()); loader._system = () => mockSystem('test.ngfactory', {'NamedNgFactory': 'test module factory'}); loader.load('test#Named').then(contents => { expect(contents).toBe('test module factory'); }); })); it('loads a named factory with a configured prefix and suffix', async(() => { let loader = new SystemJsNgModuleLoader(new Compiler(), { factoryPathPrefix: 'prefixed/', factoryPathSuffix: '/suffixed', }); loader._system = () => mockSystem('prefixed/test/suffixed', {'NamedNgFactory': 'test module factory'}); loader.load('test#Named').then(contents => { expect(contents).toBe('test module factory'); }); })); }); };
modules/@angular/core/test/linker/system_ng_module_factory_loader_spec.ts
1
https://github.com/angular/angular/commit/d26a82749473803fbcbd735da46736779367521c
[ 0.9978475570678711, 0.5976465940475464, 0.00016370507364626974, 0.9936478734016418, 0.48755398392677307 ]
{ "id": 10, "code_window": [ " loader.load('test').then(contents => { expect(contents).toBe('test module factory'); });\n", " }));\n", " it('loads a named factory by appending the factory suffix', async(() => {\n", " let loader = new SystemJsNgModuleLoader(new Compiler());\n", " loader._system = () =>\n", " mockSystem('test.ngfactory', {'NamedNgFactory': 'test module factory'});\n", " loader.load('test#Named').then(contents => {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep" ], "after_edit": [], "file_path": "modules/@angular/core/test/linker/system_ng_module_factory_loader_spec.ts", "type": "replace", "edit_start_line_idx": 30 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {Subject} from 'rxjs/Subject'; export {Observable} from 'rxjs/Observable'; export {Subject} from 'rxjs/Subject'; /** * Use by directives and components to emit custom Events. * * ### Examples * * In the following example, `Zippy` alternatively emits `open` and `close` events when its * title gets clicked: * * ``` * @Component({ * selector: 'zippy', * template: ` * <div class="zippy"> * <div (click)="toggle()">Toggle</div> * <div [hidden]="!visible"> * <ng-content></ng-content> * </div> * </div>`}) * export class Zippy { * visible: boolean = true; * @Output() open: EventEmitter<any> = new EventEmitter(); * @Output() close: EventEmitter<any> = new EventEmitter(); * * toggle() { * this.visible = !this.visible; * if (this.visible) { * this.open.emit(null); * } else { * this.close.emit(null); * } * } * } * ``` * * The events payload can be accessed by the parameter `$event` on the components output event * handler: * * ``` * <zippy (open)="onOpen($event)" (close)="onClose($event)"></zippy> * ``` * * Uses Rx.Observable but provides an adapter to make it work as specified here: * https://github.com/jhusain/observable-spec * * Once a reference implementation of the spec is available, switch to it. * @stable */ export class EventEmitter<T> extends Subject<T> { // TODO: mark this as internal once all the facades are gone // we can't mark it as internal now because EventEmitter exported via @angular/core would not // contain this property making it incompatible with all the code that uses EventEmitter via // facades, which are local to the code and do not have this property stripped. // tslint:disable-next-line __isAsync: boolean; /** * Creates an instance of [EventEmitter], which depending on [isAsync], * delivers events synchronously or asynchronously. */ constructor(isAsync: boolean = false) { super(); this.__isAsync = isAsync; } emit(value?: T) { super.next(value); } subscribe(generatorOrNext?: any, error?: any, complete?: any): any { let schedulerFn: any /** TODO #9100 */; let errorFn = (err: any): any /** TODO #9100 */ => null; let completeFn = (): any /** TODO #9100 */ => null; if (generatorOrNext && typeof generatorOrNext === 'object') { schedulerFn = this.__isAsync ? (value: any /** TODO #9100 */) => { setTimeout(() => generatorOrNext.next(value)); } : (value: any /** TODO #9100 */) => { generatorOrNext.next(value); }; if (generatorOrNext.error) { errorFn = this.__isAsync ? (err) => { setTimeout(() => generatorOrNext.error(err)); } : (err) => { generatorOrNext.error(err); }; } if (generatorOrNext.complete) { completeFn = this.__isAsync ? () => { setTimeout(() => generatorOrNext.complete()); } : () => { generatorOrNext.complete(); }; } } else { schedulerFn = this.__isAsync ? (value: any /** TODO #9100 */) => { setTimeout(() => generatorOrNext(value)); } : (value: any /** TODO #9100 */) => { generatorOrNext(value); }; if (error) { errorFn = this.__isAsync ? (err) => { setTimeout(() => error(err)); } : (err) => { error(err); }; } if (complete) { completeFn = this.__isAsync ? () => { setTimeout(() => complete()); } : () => { complete(); }; } } return super.subscribe(schedulerFn, errorFn, completeFn); } }
modules/@angular/facade/src/async.ts
0
https://github.com/angular/angular/commit/d26a82749473803fbcbd735da46736779367521c
[ 0.00017480598762631416, 0.00016907055396586657, 0.00016270275227725506, 0.000169674982316792, 0.0000040453815017826855 ]
{ "id": 10, "code_window": [ " loader.load('test').then(contents => { expect(contents).toBe('test module factory'); });\n", " }));\n", " it('loads a named factory by appending the factory suffix', async(() => {\n", " let loader = new SystemJsNgModuleLoader(new Compiler());\n", " loader._system = () =>\n", " mockSystem('test.ngfactory', {'NamedNgFactory': 'test module factory'});\n", " loader.load('test#Named').then(contents => {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep" ], "after_edit": [], "file_path": "modules/@angular/core/test/linker/system_ng_module_factory_loader_spec.ts", "type": "replace", "edit_start_line_idx": 30 }
#!/bin/bash # This script prepares build artifacts for upload to NPM. # # Usage: # # scripts/publish/npm_prepare.sh PACKAGE_NAME set -ex shopt -s extglob NAME=$1 ROOT_DIR=$(cd $(dirname $0)/../..; pwd) cd $ROOT_DIR NPM_DIR=$ROOT_DIR/dist/npm FILES='!(test|e2e_test|docs)' PUBLISH_DIR=$NPM_DIR/$NAME rm -fr $PUBLISH_DIR mkdir -p $PUBLISH_DIR mkdir -p $PUBLISH_DIR/es6/dev cp -r $ROOT_DIR/dist/js/dev/es6/$NAME/$FILES $PUBLISH_DIR/es6/dev mkdir -p $PUBLISH_DIR/es6/prod cp -r $ROOT_DIR/dist/js/prod/es6/$NAME/$FILES $PUBLISH_DIR/es6/prod mkdir -p $PUBLISH_DIR/ts cp -r $ROOT_DIR/modules/$NAME/$FILES $PUBLISH_DIR/ts if [ $NAME = "angular2" ]; then # Copy Bundles mkdir -p $PUBLISH_DIR/bundles cp -r $ROOT_DIR/dist/js/bundle/$FILES $PUBLISH_DIR/bundles fi if [ $NAME = "benchpress" ]; then cp -r $ROOT_DIR/dist/build/benchpress_bundle/$FILES $PUBLISH_DIR cp -r $ROOT_DIR/dist/js/cjs/benchpress/README.md $PUBLISH_DIR cp -r $ROOT_DIR/dist/js/cjs/benchpress/LICENSE $PUBLISH_DIR cp -r $ROOT_DIR/dist/js/cjs/benchpress/docs $PUBLISH_DIR else cp -r $ROOT_DIR/dist/js/cjs/$NAME/$FILES $PUBLISH_DIR fi # Remove all dart related files rm -f $PUBLISH_DIR/{,**/}{*.dart,*.dart.md}
scripts/publish/npm_prepare.sh
0
https://github.com/angular/angular/commit/d26a82749473803fbcbd735da46736779367521c
[ 0.00017488251614850014, 0.00017075898358598351, 0.0001671725622145459, 0.00017009899602271616, 0.0000025987797016568948 ]
{ "id": 10, "code_window": [ " loader.load('test').then(contents => { expect(contents).toBe('test module factory'); });\n", " }));\n", " it('loads a named factory by appending the factory suffix', async(() => {\n", " let loader = new SystemJsNgModuleLoader(new Compiler());\n", " loader._system = () =>\n", " mockSystem('test.ngfactory', {'NamedNgFactory': 'test module factory'});\n", " loader.load('test#Named').then(contents => {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep" ], "after_edit": [], "file_path": "modules/@angular/core/test/linker/system_ng_module_factory_loader_spec.ts", "type": "replace", "edit_start_line_idx": 30 }
# Triage Process and Github Labels for Angular 2 This document describes how the Angular team uses labels and milestones to triage issues on github. # Issues and PRs ## Triaged vs Untriaged Issues Every triaged issue must have four attributes assigned to it: * `priority` -- P0 through P4. P0 issues are "drop everything and do this now". P4 are nice to have. * `component` -- Which area of Angular knowledge this relates to. * `effort` -- Rough assessment of how much work this issue is. E.g. `effort: easy` means "probably a few hours of work". * `type` -- Whether this issue is a bug, feature, or other kind of task. Untriaged issues are any issues in the queue that don't yet have these four attributes. You can view a report of untriaged issues here, in our [Angular Triage Dashboard](http://mhevery.github.io/github_issues/). Issues should also have a clear action to complete that can be addressed or resolved within the scope of Angular 2. We'll close issues that don't meet these criteria. ### Assigning Issues to Milestones Any issue that is being worked on must have: * An `assignee`: The person doing the work. * A `Milestone`: When we expect to complete this work. We aim to only have at most three milestones open at a time: * Closing Milestone: A milestone with a very small number of issues, about to release. * Current Milestone: Work that we plan to complete within one week. * Next Milestone: Work that is > 1 week but current for the team. The [backlog](https://github.com/angular/angular/issues?q=is%3Aopen+is%3Aissue+no%3Amilestone) consists of all issues that have been triaged but do not have an assignee or milestone. ## Triaged vs Untriaged PRs Because of the cumulative pain associated with rebasing PRs, we triage PRs daily, and closing or reviewing PRs is a top priority ahead of other ongoing work. Every triaged PR must have a `pr_action` label assigned to it and an assignee: * `pr_action: review` -- work is complete and comment is needed from the assignee. * `pr_action: cleanup` -- more work is needed from the current assignee. * `pr_action: discuss` -- discussion is needed, to be led by the current assignee. * `pr_action: merge` -- the PR should be merged. Add this to a PR when you would like to trigger automatic merging following a successful build. This is described in [COMMITTER.md](COMMITTER.md). In addition, PRs can have the following states: * `pr_state: LGTM` -- PR may have outstanding changes but does not require further review. * `pr_state: WIP` -- PR is experimental or rapidly changing. Not ready for review or triage. * `pr_state: blocked` -- PR is blocked on an issue or other PR. Not ready for review or triage. Note that an LGTM state does not mean a PR is ready to merge: for example, a reviewer might set the LGTM state but request a minor tweak that doesn't need further review, e.g., a rebase or small uncontroversial change. PRs do not need to be assigned to milestones, unless a milestone release should be held for that PR to land. Victor (`vsavkin`) and Tobias (`tbosch`) are owners of the PR queue. Here is a list of [current untriaged PRs](https://github.com/angular/angular/pulls?utf8=%E2%9C%93&q=is%3Aopen+no%3Amilestone+is%3Apr+-label%3A%22pr_action%3A+cleanup%22+-label%3A%22pr_action%3A+merge%22+-label%3A%22pr_action%3A+review%22+-label%3A%22pr_action%3A+discuss%22+-label%3A%22pr_state%3A+blocked%22+-label%3A%22pr_state%3A+WIP%22+). # Prioritization of Work What should you be working on? 1. Any PRs that are assigned to you that don't have `pr_state: WIP` or `pr_state: blocked` 1. Any issues that are assigned to you in the lowest-numbered Milestone 1. Any issues that are assigned to you in any Milestone If there are no issues assigned to you in any Milestone, pick an issue, self-assign it, and add it to the most appropriate Milestone based on effort. Here are some suggestions for what to work on next: * Filter for issues in a component that you are knowledgeable about, and pick something that has a high priority. * Filter for any small effort task that has the special `cust: GT` or `cust:Ionic` tags, and priority > P3. * Add a new task that's really important, add `component`, `priority`, `effort`, `type` and assign it to yourself and the most appropriate milestone. # Labels Used in Triage ## Priority How urgent is this issue? We use priority to determine what should be worked on in each new milestone. * `P0: critical` -- drop everything to work on this * `P1: urgent` -- resolve quickly in the current milestone. people are blocked * `P2: required` -- needed for development but not urgent yet. workaround exists, or e.g. new API * `P3: important` -- must complete before Angular 2 is ready for release * `P4: nice to have` -- a good idea, but maybe not until after release ## Effort Rough, non-binding estimate of how much work this issue represents. Please change this assessment for anything you're working on to better reflect reality. * `effort: easy` -- straightforward issue that can be resolved in a few hours, e.g. < 1 day of work. * `effort: medium` -- issue that will be a few days of work. Can be completed within a single milestone. * `effort: tough` -- issue that will likely take more than 1 milestone to complete. <!-- We don't like these label names as they're not absolute (what is one developer-hour, really?) but decided it wasn't worth arguing over terms. --> ## Component Which area of Angular knowledge is this issue most closely related to? Helpful when deciding what to work on next. * `comp: benchpress` -- benchmarks and performance testing &rarr; *tbosch*, *crossj* * `comp: build/dev-productivity` -- build process, e.g. CLI and related tasks &rarr; *iminar*, *caitp* * `comp: build/pipeline` -- build pipeline, e.g. ts2dart &rarr; *mprobst*, *alexeagle* * `comp: core` -- general core Angular issues, not related to a sub-category (see below) &rarr; *mhevery* * `comp: core/animations` -- animations framework &rarr; *matsko* * `comp: core/change_detection` -- change detection &rarr; *vsavkin* * `comp: core/di` -- dependency injection &rarr; *vicb*, *rkirov* * `comp: core/directives` -- directives * `comp: core/forms` -- forms &rarr; *vsavkin* * `comp: core/pipes` -- pipes * `comp: core/view` -- runtime processing of the `View`s * `comp: core/view/compiler` -- static analysis of the templates which generate `ProtoView`s. * `comp: core/testbed` -- e2e tests and support for them * `comp: core/webworker` -- core web worker infrastructure * `comp: dart-transformer` -- Dart transforms &rarr; *kegluneq*, *jakemac* * `comp: data-access` -- &rarr; *jeffbcross* * `comp: docs` -- API docs and doc generation &rarr; *naomiblack*, *petebacondarwin* * `comp: material-components` -- Angular Material components built in Angular 2 &rarr; *jelbourn* * `comp: router` -- Component Router &rarr; *btford*, *igorminar*, *matsko* * `comp: wrenchjs` ## Type What kind of problem is this? * `type RFC / discussion / question` * `type bug` * `type chore` * `type feature` * `type performance` * `type refactor` ## Special Labels ### action:design More active discussion is needed before the issue can be worked on further. Typically used for `type: feature` or `type: RFC/discussion/question` [See all issues that need discussion](https://github.com/angular/angular/labels/action:%20Design) ### cla Managed by googlebot. Indicates whether a PR has a CLA on file for its author(s). Only issues with `cla:yes` should be merged into master. ### cust This is an issue causing user pain for early adopter customers `cust: GT` or `cust: Ionic`. ### WORKS_AS_INTENDED Only used on closed issues, to indicate to the reporter why we closed it.
TRIAGE_AND_LABELS.md
0
https://github.com/angular/angular/commit/d26a82749473803fbcbd735da46736779367521c
[ 0.00017616483091842383, 0.00017284555360674858, 0.0001696766703389585, 0.00017283075430896133, 0.0000017384728607794386 ]
{ "id": 11, "code_window": [ " loader.load('test#Named').then(contents => {\n", " expect(contents).toBe('test module factory');\n", " });\n", " }));\n", " it('loads a named factory with a configured prefix and suffix', async(() => {\n", " let loader = new SystemJsNgModuleLoader(new Compiler(), {\n", " factoryPathPrefix: 'prefixed/',\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " expect(contents).toBe('test NamedNgFactory');\n" ], "file_path": "modules/@angular/core/test/linker/system_ng_module_factory_loader_spec.ts", "type": "replace", "edit_start_line_idx": 33 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {Compiler, SystemJsNgModuleLoader} from '@angular/core'; import {async, tick} from '@angular/core/testing'; import {beforeEach, ddescribe, describe, expect, iit, it, xit} from '@angular/core/testing/testing_internal'; function mockSystem(module: string, contents: any) { return { 'import': (target: string) => { expect(target).toBe(module); return Promise.resolve(contents); } }; } export function main() { describe('SystemJsNgModuleLoader', () => { it('loads a default factory by appending the factory suffix', async(() => { let loader = new SystemJsNgModuleLoader(new Compiler()); loader._system = () => mockSystem('test.ngfactory', {'default': 'test module factory'}); loader.load('test').then(contents => { expect(contents).toBe('test module factory'); }); })); it('loads a named factory by appending the factory suffix', async(() => { let loader = new SystemJsNgModuleLoader(new Compiler()); loader._system = () => mockSystem('test.ngfactory', {'NamedNgFactory': 'test module factory'}); loader.load('test#Named').then(contents => { expect(contents).toBe('test module factory'); }); })); it('loads a named factory with a configured prefix and suffix', async(() => { let loader = new SystemJsNgModuleLoader(new Compiler(), { factoryPathPrefix: 'prefixed/', factoryPathSuffix: '/suffixed', }); loader._system = () => mockSystem('prefixed/test/suffixed', {'NamedNgFactory': 'test module factory'}); loader.load('test#Named').then(contents => { expect(contents).toBe('test module factory'); }); })); }); };
modules/@angular/core/test/linker/system_ng_module_factory_loader_spec.ts
1
https://github.com/angular/angular/commit/d26a82749473803fbcbd735da46736779367521c
[ 0.9984226226806641, 0.401496022939682, 0.0001652304781600833, 0.010626832023262978, 0.48724666237831116 ]
{ "id": 11, "code_window": [ " loader.load('test#Named').then(contents => {\n", " expect(contents).toBe('test module factory');\n", " });\n", " }));\n", " it('loads a named factory with a configured prefix and suffix', async(() => {\n", " let loader = new SystemJsNgModuleLoader(new Compiler(), {\n", " factoryPathPrefix: 'prefixed/',\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " expect(contents).toBe('test NamedNgFactory');\n" ], "file_path": "modules/@angular/core/test/linker/system_ng_module_factory_loader_spec.ts", "type": "replace", "edit_start_line_idx": 33 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {NgFor, NgIf} from '@angular/common'; import {Component, Directive, EventEmitter, Input, Output, forwardRef} from '@angular/core'; import {ComponentFixture, TestBed, fakeAsync, tick} from '@angular/core/testing'; import {ControlValueAccessor, FormArray, FormControl, FormGroup, FormGroupDirective, FormsModule, NG_ASYNC_VALIDATORS, NG_VALIDATORS, NgControl, ReactiveFormsModule, Validator, Validators} from '@angular/forms'; import {By} from '@angular/platform-browser/src/dom/debug/by'; import {getDOM} from '@angular/platform-browser/src/dom/dom_adapter'; import {dispatchEvent} from '@angular/platform-browser/testing/browser_util'; import {ListWrapper} from '../src/facade/collection'; import {AbstractControl} from '../src/model'; export function main() { describe('reactive forms integration tests', () => { beforeEach(() => { TestBed.configureTestingModule({ imports: [FormsModule, ReactiveFormsModule], declarations: [ FormControlComp, FormGroupComp, FormArrayComp, FormArrayNestedGroup, FormControlNameSelect, FormControlNumberInput, FormControlRadioButtons, WrappedValue, WrappedValueForm, MyInput, MyInputForm, FormGroupNgModel, FormControlNgModel, LoginIsEmptyValidator, LoginIsEmptyWrapper, ValidationBindingsForm, UniqLoginValidator, UniqLoginWrapper, NestedFormGroupComp ] }); }); describe('basic functionality', () => { it('should work with single controls', () => { const fixture = TestBed.createComponent(FormControlComp); const control = new FormControl('old value'); fixture.debugElement.componentInstance.control = control; fixture.detectChanges(); // model -> view const input = fixture.debugElement.query(By.css('input')); expect(input.nativeElement.value).toEqual('old value'); input.nativeElement.value = 'updated value'; dispatchEvent(input.nativeElement, 'input'); // view -> model expect(control.value).toEqual('updated value'); }); it('should work with formGroups (model -> view)', () => { const fixture = TestBed.createComponent(FormGroupComp); fixture.debugElement.componentInstance.form = new FormGroup({'login': new FormControl('loginValue')}); fixture.detectChanges(); const input = fixture.debugElement.query(By.css('input')); expect(input.nativeElement.value).toEqual('loginValue'); }); it('work with formGroups (view -> model)', () => { const fixture = TestBed.createComponent(FormGroupComp); const form = new FormGroup({'login': new FormControl('oldValue')}); fixture.debugElement.componentInstance.form = form; fixture.detectChanges(); const input = fixture.debugElement.query(By.css('input')); input.nativeElement.value = 'updatedValue'; dispatchEvent(input.nativeElement, 'input'); expect(form.value).toEqual({'login': 'updatedValue'}); }); }); describe('rebound form groups', () => { it('should update DOM elements initially', () => { const fixture = TestBed.createComponent(FormGroupComp); fixture.debugElement.componentInstance.form = new FormGroup({'login': new FormControl('oldValue')}); fixture.detectChanges(); fixture.debugElement.componentInstance.form = new FormGroup({'login': new FormControl('newValue')}); fixture.detectChanges(); const input = fixture.debugElement.query(By.css('input')); expect(input.nativeElement.value).toEqual('newValue'); }); it('should update model when UI changes', () => { const fixture = TestBed.createComponent(FormGroupComp); fixture.debugElement.componentInstance.form = new FormGroup({'login': new FormControl('oldValue')}); fixture.detectChanges(); const newForm = new FormGroup({'login': new FormControl('newValue')}); fixture.debugElement.componentInstance.form = newForm; fixture.detectChanges(); const input = fixture.debugElement.query(By.css('input')); input.nativeElement.value = 'Nancy'; dispatchEvent(input.nativeElement, 'input'); fixture.detectChanges(); expect(newForm.value).toEqual({login: 'Nancy'}); newForm.setValue({login: 'Carson'}); fixture.detectChanges(); expect(input.nativeElement.value).toEqual('Carson'); }); it('should work with radio buttons when reusing control', () => { const fixture = TestBed.createComponent(FormControlRadioButtons); const food = new FormControl('chicken'); fixture.debugElement.componentInstance.form = new FormGroup({'food': food, 'drink': new FormControl('')}); fixture.detectChanges(); const newForm = new FormGroup({'food': food, 'drink': new FormControl('')}); fixture.debugElement.componentInstance.form = newForm; fixture.detectChanges(); newForm.setValue({food: 'fish', drink: ''}); fixture.detectChanges(); const inputs = fixture.debugElement.queryAll(By.css('input')); expect(inputs[0].nativeElement.checked).toBe(false); expect(inputs[1].nativeElement.checked).toBe(true); }); it('should update nested form group model when UI changes', () => { const fixture = TestBed.createComponent(NestedFormGroupComp); fixture.debugElement.componentInstance.form = new FormGroup( {'signin': new FormGroup({'login': new FormControl(), 'password': new FormControl()})}); fixture.detectChanges(); const newForm = new FormGroup({ 'signin': new FormGroup( {'login': new FormControl('Nancy'), 'password': new FormControl('secret')}) }); fixture.debugElement.componentInstance.form = newForm; fixture.detectChanges(); const inputs = fixture.debugElement.queryAll(By.css('input')); expect(inputs[0].nativeElement.value).toEqual('Nancy'); expect(inputs[1].nativeElement.value).toEqual('secret'); inputs[0].nativeElement.value = 'Carson'; dispatchEvent(inputs[0].nativeElement, 'input'); fixture.detectChanges(); expect(newForm.value).toEqual({signin: {login: 'Carson', password: 'secret'}}); newForm.setValue({signin: {login: 'Bess', password: 'otherpass'}}); fixture.detectChanges(); expect(inputs[0].nativeElement.value).toEqual('Bess'); }); it('should pick up dir validators from form controls', () => { const fixture = TestBed.createComponent(LoginIsEmptyWrapper); const form = new FormGroup({ 'login': new FormControl(''), 'min': new FormControl(''), 'max': new FormControl(''), 'pattern': new FormControl('') }); fixture.debugElement.componentInstance.form = form; fixture.detectChanges(); expect(form.get('login').errors).toEqual({required: true}); const newForm = new FormGroup({ 'login': new FormControl(''), 'min': new FormControl(''), 'max': new FormControl(''), 'pattern': new FormControl('') }); fixture.debugElement.componentInstance.form = newForm; fixture.detectChanges(); expect(newForm.get('login').errors).toEqual({required: true}); }); it('should pick up dir validators from nested form groups', () => { const fixture = TestBed.createComponent(NestedFormGroupComp); const form = new FormGroup({ 'signin': new FormGroup({'login': new FormControl(''), 'password': new FormControl('')}) }); fixture.debugElement.componentInstance.form = form; fixture.detectChanges(); expect(form.get('signin').valid).toBe(false); const newForm = new FormGroup({ 'signin': new FormGroup({'login': new FormControl(''), 'password': new FormControl('')}) }); fixture.debugElement.componentInstance.form = newForm; fixture.detectChanges(); expect(form.get('signin').valid).toBe(false); }); it('should strip named controls that are not found', () => { const fixture = TestBed.createComponent(NestedFormGroupComp); const form = new FormGroup({ 'signin': new FormGroup({'login': new FormControl(''), 'password': new FormControl('')}) }); fixture.debugElement.componentInstance.form = form; fixture.detectChanges(); form.addControl('email', new FormControl('email')); fixture.detectChanges(); let emailInput = fixture.debugElement.query(By.css('[formControlName="email"]')); expect(emailInput.nativeElement.value).toEqual('email'); const newForm = new FormGroup({ 'signin': new FormGroup({'login': new FormControl(''), 'password': new FormControl('')}) }); fixture.debugElement.componentInstance.form = newForm; fixture.detectChanges(); emailInput = fixture.debugElement.query(By.css('[formControlName="email"]')); expect(emailInput).toBe(null); }); it('should strip array controls that are not found', () => { const fixture = TestBed.createComponent(FormArrayComp); const cityArray = new FormArray([new FormControl('SF'), new FormControl('NY')]); const form = new FormGroup({cities: cityArray}); fixture.debugElement.componentInstance.form = form; fixture.debugElement.componentInstance.cityArray = cityArray; fixture.detectChanges(); let inputs = fixture.debugElement.queryAll(By.css('input')); expect(inputs[2]).not.toBeDefined(); cityArray.push(new FormControl('LA')); fixture.detectChanges(); inputs = fixture.debugElement.queryAll(By.css('input')); expect(inputs[2]).toBeDefined(); const newArr = new FormArray([new FormControl('SF'), new FormControl('NY')]); const newForm = new FormGroup({cities: newArr}); fixture.debugElement.componentInstance.form = newForm; fixture.debugElement.componentInstance.cityArray = newArr; fixture.detectChanges(); inputs = fixture.debugElement.queryAll(By.css('input')); expect(inputs[2]).not.toBeDefined(); }); describe('nested control rebinding', () => { it('should attach dir to control when leaf control changes', () => { const form = new FormGroup({'login': new FormControl('oldValue')}); const fixture = TestBed.createComponent(FormGroupComp); fixture.debugElement.componentInstance.form = form; fixture.detectChanges(); form.removeControl('login'); form.addControl('login', new FormControl('newValue')); fixture.detectChanges(); const input = fixture.debugElement.query(By.css('input')); expect(input.nativeElement.value).toEqual('newValue'); input.nativeElement.value = 'user input'; dispatchEvent(input.nativeElement, 'input'); fixture.detectChanges(); expect(form.value).toEqual({login: 'user input'}); form.setValue({login: 'Carson'}); fixture.detectChanges(); expect(input.nativeElement.value).toEqual('Carson'); }); it('should attach dirs to all child controls when group control changes', () => { const fixture = TestBed.createComponent(NestedFormGroupComp); const form = new FormGroup({ signin: new FormGroup( {login: new FormControl('oldLogin'), password: new FormControl('oldPassword')}) }); fixture.debugElement.componentInstance.form = form; fixture.detectChanges(); form.removeControl('signin'); form.addControl( 'signin', new FormGroup( {login: new FormControl('newLogin'), password: new FormControl('newPassword')})); fixture.detectChanges(); const inputs = fixture.debugElement.queryAll(By.css('input')); expect(inputs[0].nativeElement.value).toEqual('newLogin'); expect(inputs[1].nativeElement.value).toEqual('newPassword'); inputs[0].nativeElement.value = 'user input'; dispatchEvent(inputs[0].nativeElement, 'input'); fixture.detectChanges(); expect(form.value).toEqual({signin: {login: 'user input', password: 'newPassword'}}); form.setValue({signin: {login: 'Carson', password: 'Drew'}}); fixture.detectChanges(); expect(inputs[0].nativeElement.value).toEqual('Carson'); expect(inputs[1].nativeElement.value).toEqual('Drew'); }); it('should attach dirs to all present child controls when array control changes', () => { const fixture = TestBed.createComponent(FormArrayComp); const cityArray = new FormArray([new FormControl('SF'), new FormControl('NY')]); const form = new FormGroup({cities: cityArray}); fixture.debugElement.componentInstance.form = form; fixture.debugElement.componentInstance.cityArray = cityArray; fixture.detectChanges(); form.removeControl('cities'); form.addControl('cities', new FormArray([new FormControl('LA')])); fixture.detectChanges(); const input = fixture.debugElement.query(By.css('input')); expect(input.nativeElement.value).toEqual('LA'); input.nativeElement.value = 'MTV'; dispatchEvent(input.nativeElement, 'input'); fixture.detectChanges(); expect(form.value).toEqual({cities: ['MTV']}); form.setValue({cities: ['LA']}); fixture.detectChanges(); expect(input.nativeElement.value).toEqual('LA'); }); }); }); describe('form arrays', () => { it('should support form arrays', () => { const fixture = TestBed.createComponent(FormArrayComp); const cityArray = new FormArray([new FormControl('SF'), new FormControl('NY')]); const form = new FormGroup({cities: cityArray}); fixture.debugElement.componentInstance.form = form; fixture.debugElement.componentInstance.cityArray = cityArray; fixture.detectChanges(); const inputs = fixture.debugElement.queryAll(By.css('input')); // model -> view expect(inputs[0].nativeElement.value).toEqual('SF'); expect(inputs[1].nativeElement.value).toEqual('NY'); expect(form.value).toEqual({cities: ['SF', 'NY']}); inputs[0].nativeElement.value = 'LA'; dispatchEvent(inputs[0].nativeElement, 'input'); fixture.detectChanges(); // view -> model expect(form.value).toEqual({cities: ['LA', 'NY']}); }); it('should support pushing new controls to form arrays', () => { const fixture = TestBed.createComponent(FormArrayComp); const cityArray = new FormArray([new FormControl('SF'), new FormControl('NY')]); const form = new FormGroup({cities: cityArray}); fixture.debugElement.componentInstance.form = form; fixture.debugElement.componentInstance.cityArray = cityArray; fixture.detectChanges(); cityArray.push(new FormControl('LA')); fixture.detectChanges(); const inputs = fixture.debugElement.queryAll(By.css('input')); expect(inputs[2].nativeElement.value).toEqual('LA'); expect(form.value).toEqual({cities: ['SF', 'NY', 'LA']}); }); it('should support form groups nested in form arrays', () => { const fixture = TestBed.createComponent(FormArrayNestedGroup); const cityArray = new FormArray([ new FormGroup({town: new FormControl('SF'), state: new FormControl('CA')}), new FormGroup({town: new FormControl('NY'), state: new FormControl('NY')}) ]); const form = new FormGroup({cities: cityArray}); fixture.debugElement.componentInstance.form = form; fixture.debugElement.componentInstance.cityArray = cityArray; fixture.detectChanges(); const inputs = fixture.debugElement.queryAll(By.css('input')); expect(inputs[0].nativeElement.value).toEqual('SF'); expect(inputs[1].nativeElement.value).toEqual('CA'); expect(inputs[2].nativeElement.value).toEqual('NY'); expect(inputs[3].nativeElement.value).toEqual('NY'); expect(form.value).toEqual({ cities: [{town: 'SF', state: 'CA'}, {town: 'NY', state: 'NY'}] }); inputs[0].nativeElement.value = 'LA'; dispatchEvent(inputs[0].nativeElement, 'input'); fixture.detectChanges(); expect(form.value).toEqual({ cities: [{town: 'LA', state: 'CA'}, {town: 'NY', state: 'NY'}] }); }); }); describe('programmatic changes', () => { it('should update the value in the DOM when setValue() is called', () => { const fixture = TestBed.createComponent(FormGroupComp); const login = new FormControl('oldValue'); const form = new FormGroup({'login': login}); fixture.debugElement.componentInstance.form = form; fixture.detectChanges(); login.setValue('newValue'); fixture.detectChanges(); const input = fixture.debugElement.query(By.css('input')); expect(input.nativeElement.value).toEqual('newValue'); }); describe('disabled controls', () => { it('should add disabled attribute to an individual control when instantiated as disabled', () => { const fixture = TestBed.createComponent(FormControlComp); const control = new FormControl({value: 'some value', disabled: true}); fixture.debugElement.componentInstance.control = control; fixture.detectChanges(); const input = fixture.debugElement.query(By.css('input')); expect(input.nativeElement.disabled).toBe(true); control.enable(); fixture.detectChanges(); expect(input.nativeElement.disabled).toBe(false); }); it('should add disabled attribute to formControlName when instantiated as disabled', () => { const fixture = TestBed.createComponent(FormGroupComp); const control = new FormControl({value: 'some value', disabled: true}); fixture.debugElement.componentInstance.form = new FormGroup({login: control}); fixture.debugElement.componentInstance.control = control; fixture.detectChanges(); const input = fixture.debugElement.query(By.css('input')); expect(input.nativeElement.disabled).toBe(true); control.enable(); fixture.detectChanges(); expect(input.nativeElement.disabled).toBe(false); }); it('should add disabled attribute to an individual control when disable() is called', () => { const fixture = TestBed.createComponent(FormControlComp); const control = new FormControl('some value'); fixture.debugElement.componentInstance.control = control; fixture.detectChanges(); control.disable(); fixture.detectChanges(); const input = fixture.debugElement.query(By.css('input')); expect(input.nativeElement.disabled).toBe(true); control.enable(); fixture.detectChanges(); expect(input.nativeElement.disabled).toBe(false); }); it('should add disabled attribute to child controls when disable() is called on group', () => { const fixture = TestBed.createComponent(FormGroupComp); const form = new FormGroup({'login': new FormControl('login')}); fixture.debugElement.componentInstance.form = form; fixture.detectChanges(); form.disable(); fixture.detectChanges(); const inputs = fixture.debugElement.queryAll(By.css('input')); expect(inputs[0].nativeElement.disabled).toBe(true); form.enable(); fixture.detectChanges(); expect(inputs[0].nativeElement.disabled).toBe(false); }); it('should not add disabled attribute to custom controls when disable() is called', () => { const fixture = TestBed.createComponent(MyInputForm); const control = new FormControl('some value'); fixture.debugElement.componentInstance.form = new FormGroup({login: control}); fixture.detectChanges(); control.disable(); fixture.detectChanges(); const input = fixture.debugElement.query(By.css('my-input')); expect(input.nativeElement.getAttribute('disabled')).toBe(null); }); }); }); describe('user input', () => { it('should mark controls as touched after interacting with the DOM control', () => { const fixture = TestBed.createComponent(FormGroupComp); const login = new FormControl('oldValue'); const form = new FormGroup({'login': login}); fixture.debugElement.componentInstance.form = form; fixture.detectChanges(); const loginEl = fixture.debugElement.query(By.css('input')); expect(login.touched).toBe(false); dispatchEvent(loginEl.nativeElement, 'blur'); expect(login.touched).toBe(true); }); }); describe('submit and reset events', () => { it('should emit ngSubmit event on submit', () => { const fixture = TestBed.createComponent(FormGroupComp); fixture.debugElement.componentInstance.form = new FormGroup({'login': new FormControl('loginValue')}); fixture.debugElement.componentInstance.data = 'should be changed'; fixture.detectChanges(); const formEl = fixture.debugElement.query(By.css('form')).nativeElement; dispatchEvent(formEl, 'submit'); fixture.detectChanges(); expect(fixture.debugElement.componentInstance.data).toEqual('submitted'); }); it('should mark formGroup as submitted on submit event', () => { const fixture = TestBed.createComponent(FormGroupComp); fixture.debugElement.componentInstance.form = new FormGroup({'login': new FormControl('loginValue')}); fixture.detectChanges(); const formGroupDir = fixture.debugElement.children[0].injector.get(FormGroupDirective); expect(formGroupDir.submitted).toBe(false); const formEl = fixture.debugElement.query(By.css('form')).nativeElement; dispatchEvent(formEl, 'submit'); fixture.detectChanges(); expect(formGroupDir.submitted).toEqual(true); }); it('should set value in UI when form resets to that value programmatically', () => { const fixture = TestBed.createComponent(FormGroupComp); const login = new FormControl('some value'); const form = new FormGroup({'login': login}); fixture.debugElement.componentInstance.form = form; fixture.detectChanges(); const loginEl = fixture.debugElement.query(By.css('input')).nativeElement; expect(loginEl.value).toBe('some value'); form.reset({'login': 'reset value'}); expect(loginEl.value).toBe('reset value'); }); it('should clear value in UI when form resets programmatically', () => { const fixture = TestBed.createComponent(FormGroupComp); const login = new FormControl('some value'); const form = new FormGroup({'login': login}); fixture.debugElement.componentInstance.form = form; fixture.detectChanges(); const loginEl = fixture.debugElement.query(By.css('input')).nativeElement; expect(loginEl.value).toBe('some value'); form.reset(); expect(loginEl.value).toBe(''); }); }); describe('value changes and status changes', () => { it('should mark controls as dirty before emitting a value change event', () => { const fixture = TestBed.createComponent(FormGroupComp); const login = new FormControl('oldValue'); fixture.debugElement.componentInstance.form = new FormGroup({'login': login}); fixture.detectChanges(); login.valueChanges.subscribe(() => { expect(login.dirty).toBe(true); }); const loginEl = fixture.debugElement.query(By.css('input')).nativeElement; loginEl.value = 'newValue'; dispatchEvent(loginEl, 'input'); }); it('should mark control as pristine before emitting a value change event when resetting ', () => { const fixture = TestBed.createComponent(FormGroupComp); const login = new FormControl('oldValue'); const form = new FormGroup({'login': login}); fixture.debugElement.componentInstance.form = form; fixture.detectChanges(); const loginEl = fixture.debugElement.query(By.css('input')).nativeElement; loginEl.value = 'newValue'; dispatchEvent(loginEl, 'input'); expect(login.pristine).toBe(false); login.valueChanges.subscribe(() => { expect(login.pristine).toBe(true); }); form.reset(); }); }); describe('setting status classes', () => { it('should work with single fields', () => { const fixture = TestBed.createComponent(FormControlComp); const control = new FormControl('', Validators.required); fixture.debugElement.componentInstance.control = control; fixture.detectChanges(); const input = fixture.debugElement.query(By.css('input')).nativeElement; expect(sortedClassList(input)).toEqual(['ng-invalid', 'ng-pristine', 'ng-untouched']); dispatchEvent(input, 'blur'); fixture.detectChanges(); expect(sortedClassList(input)).toEqual(['ng-invalid', 'ng-pristine', 'ng-touched']); input.value = 'updatedValue'; dispatchEvent(input, 'input'); fixture.detectChanges(); expect(sortedClassList(input)).toEqual(['ng-dirty', 'ng-touched', 'ng-valid']); }); it('should work with single fields in parent forms', () => { const fixture = TestBed.createComponent(FormGroupComp); const form = new FormGroup({'login': new FormControl('', Validators.required)}); fixture.debugElement.componentInstance.form = form; fixture.detectChanges(); const input = fixture.debugElement.query(By.css('input')).nativeElement; expect(sortedClassList(input)).toEqual(['ng-invalid', 'ng-pristine', 'ng-untouched']); dispatchEvent(input, 'blur'); fixture.detectChanges(); expect(sortedClassList(input)).toEqual(['ng-invalid', 'ng-pristine', 'ng-touched']); input.value = 'updatedValue'; dispatchEvent(input, 'input'); fixture.detectChanges(); expect(sortedClassList(input)).toEqual(['ng-dirty', 'ng-touched', 'ng-valid']); }); it('should work with formGroup', () => { const fixture = TestBed.createComponent(FormGroupComp); const form = new FormGroup({'login': new FormControl('', Validators.required)}); fixture.debugElement.componentInstance.form = form; fixture.detectChanges(); const input = fixture.debugElement.query(By.css('input')).nativeElement; const formEl = fixture.debugElement.query(By.css('form')).nativeElement; expect(sortedClassList(formEl)).toEqual(['ng-invalid', 'ng-pristine', 'ng-untouched']); dispatchEvent(input, 'blur'); fixture.detectChanges(); expect(sortedClassList(formEl)).toEqual(['ng-invalid', 'ng-pristine', 'ng-touched']); input.value = 'updatedValue'; dispatchEvent(input, 'input'); fixture.detectChanges(); expect(sortedClassList(formEl)).toEqual(['ng-dirty', 'ng-touched', 'ng-valid']); }); }); describe('value accessors', () => { it('should support <input> without type', () => { TestBed.overrideComponent( FormControlComp, {set: {template: `<input [formControl]="control">`}}); const fixture = TestBed.createComponent(FormControlComp); const control = new FormControl('old'); fixture.debugElement.componentInstance.control = control; fixture.detectChanges(); // model -> view const input = fixture.debugElement.query(By.css('input')); expect(input.nativeElement.value).toEqual('old'); input.nativeElement.value = 'new'; dispatchEvent(input.nativeElement, 'input'); // view -> model expect(control.value).toEqual('new'); }); it('should support <input type=text>', () => { const fixture = TestBed.createComponent(FormGroupComp); const form = new FormGroup({'login': new FormControl('old')}); fixture.debugElement.componentInstance.form = form; fixture.detectChanges(); // model -> view const input = fixture.debugElement.query(By.css('input')); expect(input.nativeElement.value).toEqual('old'); input.nativeElement.value = 'new'; dispatchEvent(input.nativeElement, 'input'); // view -> model expect(form.value).toEqual({'login': 'new'}); }); it('should ignore the change event for <input type=text>', () => { const fixture = TestBed.createComponent(FormGroupComp); const form = new FormGroup({'login': new FormControl('oldValue')}); fixture.debugElement.componentInstance.form = form; fixture.detectChanges(); const input = fixture.debugElement.query(By.css('input')); form.valueChanges.subscribe({next: (value) => { throw 'Should not happen'; }}); input.nativeElement.value = 'updatedValue'; dispatchEvent(input.nativeElement, 'change'); }); it('should support <textarea>', () => { TestBed.overrideComponent( FormControlComp, {set: {template: `<textarea [formControl]="control"></textarea>`}}); const fixture = TestBed.createComponent(FormControlComp); const control = new FormControl('old'); fixture.debugElement.componentInstance.control = control; fixture.detectChanges(); // model -> view const textarea = fixture.debugElement.query(By.css('textarea')); expect(textarea.nativeElement.value).toEqual('old'); textarea.nativeElement.value = 'new'; dispatchEvent(textarea.nativeElement, 'input'); // view -> model expect(control.value).toEqual('new'); }); it('should support <type=checkbox>', () => { TestBed.overrideComponent( FormControlComp, {set: {template: `<input type="checkbox" [formControl]="control">`}}); const fixture = TestBed.createComponent(FormControlComp); const control = new FormControl(true); fixture.debugElement.componentInstance.control = control; fixture.detectChanges(); // model -> view const input = fixture.debugElement.query(By.css('input')); expect(input.nativeElement.checked).toBe(true); input.nativeElement.checked = false; dispatchEvent(input.nativeElement, 'change'); // view -> model expect(control.value).toBe(false); }); it('should support <select>', () => { const fixture = TestBed.createComponent(FormControlNameSelect); fixture.detectChanges(); // model -> view const select = fixture.debugElement.query(By.css('select')); const sfOption = fixture.debugElement.query(By.css('option')); expect(select.nativeElement.value).toEqual('SF'); expect(sfOption.nativeElement.selected).toBe(true); select.nativeElement.value = 'NY'; dispatchEvent(select.nativeElement, 'change'); fixture.detectChanges(); // view -> model expect(sfOption.nativeElement.selected).toBe(false); expect(fixture.debugElement.componentInstance.form.value).toEqual({'city': 'NY'}); }); describe('should support <type=number>', () => { it('with basic use case', () => { const fixture = TestBed.createComponent(FormControlNumberInput); const control = new FormControl(10); fixture.debugElement.componentInstance.control = control; fixture.detectChanges(); // model -> view const input = fixture.debugElement.query(By.css('input')); expect(input.nativeElement.value).toEqual('10'); input.nativeElement.value = '20'; dispatchEvent(input.nativeElement, 'input'); // view -> model expect(control.value).toEqual(20); }); it('when value is cleared in the UI', () => { const fixture = TestBed.createComponent(FormControlNumberInput); const control = new FormControl(10, Validators.required); fixture.debugElement.componentInstance.control = control; fixture.detectChanges(); const input = fixture.debugElement.query(By.css('input')); input.nativeElement.value = ''; dispatchEvent(input.nativeElement, 'input'); expect(control.valid).toBe(false); expect(control.value).toEqual(null); input.nativeElement.value = '0'; dispatchEvent(input.nativeElement, 'input'); expect(control.valid).toBe(true); expect(control.value).toEqual(0); }); it('when value is cleared programmatically', () => { const fixture = TestBed.createComponent(FormControlNumberInput); const control = new FormControl(10); fixture.debugElement.componentInstance.control = control; fixture.detectChanges(); control.setValue(null); const input = fixture.debugElement.query(By.css('input')); expect(input.nativeElement.value).toEqual(''); }); }); describe('should support <type=radio>', () => { it('should support <type=radio>', () => { const fixture = TestBed.createComponent(FormControlRadioButtons); const form = new FormGroup({'food': new FormControl('fish'), 'drink': new FormControl('sprite')}); fixture.debugElement.componentInstance.form = form; fixture.detectChanges(); // model -> view const inputs = fixture.debugElement.queryAll(By.css('input')); expect(inputs[0].nativeElement.checked).toEqual(false); expect(inputs[1].nativeElement.checked).toEqual(true); dispatchEvent(inputs[0].nativeElement, 'change'); fixture.detectChanges(); // view -> model expect(form.get('food').value).toEqual('chicken'); expect(inputs[1].nativeElement.checked).toEqual(false); form.get('food').setValue('fish'); fixture.detectChanges(); // programmatic change -> view expect(inputs[0].nativeElement.checked).toEqual(false); expect(inputs[1].nativeElement.checked).toEqual(true); }); it('should use formControlName to group radio buttons when name is absent', () => { const fixture = TestBed.createComponent(FormControlRadioButtons); const foodCtrl = new FormControl('fish'); const drinkCtrl = new FormControl('sprite'); fixture.debugElement.componentInstance.form = new FormGroup({'food': foodCtrl, 'drink': drinkCtrl}); fixture.detectChanges(); const inputs = fixture.debugElement.queryAll(By.css('input')); expect(inputs[0].nativeElement.checked).toEqual(false); expect(inputs[1].nativeElement.checked).toEqual(true); expect(inputs[2].nativeElement.checked).toEqual(false); expect(inputs[3].nativeElement.checked).toEqual(true); dispatchEvent(inputs[0].nativeElement, 'change'); inputs[0].nativeElement.checked = true; fixture.detectChanges(); const value = fixture.debugElement.componentInstance.form.value; expect(value.food).toEqual('chicken'); expect(inputs[1].nativeElement.checked).toEqual(false); expect(inputs[2].nativeElement.checked).toEqual(false); expect(inputs[3].nativeElement.checked).toEqual(true); drinkCtrl.setValue('cola'); fixture.detectChanges(); expect(inputs[0].nativeElement.checked).toEqual(true); expect(inputs[1].nativeElement.checked).toEqual(false); expect(inputs[2].nativeElement.checked).toEqual(true); expect(inputs[3].nativeElement.checked).toEqual(false); }); it('should support removing controls from <type=radio>', () => { const fixture = TestBed.createComponent(FormControlRadioButtons); const showRadio = new FormControl('yes'); const form = new FormGroup({'food': new FormControl('fish'), 'drink': new FormControl('sprite')}); fixture.debugElement.componentInstance.form = form; fixture.debugElement.componentInstance.showRadio = showRadio; showRadio.valueChanges.subscribe((change) => { (change === 'yes') ? form.addControl('food', new FormControl('fish')) : form.removeControl('food'); }); fixture.detectChanges(); const input = fixture.debugElement.query(By.css('[value="no"]')); dispatchEvent(input.nativeElement, 'change'); fixture.detectChanges(); expect(form.value).toEqual({drink: 'sprite'}); }); it('should differentiate controls on different levels with the same name', () => { TestBed.overrideComponent(FormControlRadioButtons, { set: { template: ` <div [formGroup]="form"> <input type="radio" formControlName="food" value="chicken"> <input type="radio" formControlName="food" value="fish"> <div formGroupName="nested"> <input type="radio" formControlName="food" value="chicken"> <input type="radio" formControlName="food" value="fish"> </div> </div> ` } }); const fixture = TestBed.createComponent(FormControlRadioButtons); const form = new FormGroup({ food: new FormControl('fish'), nested: new FormGroup({food: new FormControl('fish')}) }); fixture.debugElement.componentInstance.form = form; fixture.detectChanges(); // model -> view const inputs = fixture.debugElement.queryAll(By.css('input')); expect(inputs[0].nativeElement.checked).toEqual(false); expect(inputs[1].nativeElement.checked).toEqual(true); expect(inputs[2].nativeElement.checked).toEqual(false); expect(inputs[3].nativeElement.checked).toEqual(true); dispatchEvent(inputs[0].nativeElement, 'change'); fixture.detectChanges(); // view -> model expect(form.get('food').value).toEqual('chicken'); expect(form.get('nested.food').value).toEqual('fish'); expect(inputs[1].nativeElement.checked).toEqual(false); expect(inputs[2].nativeElement.checked).toEqual(false); expect(inputs[3].nativeElement.checked).toEqual(true); }); }); describe('custom value accessors', () => { it('should support custom value accessors', () => { const fixture = TestBed.createComponent(WrappedValueForm); fixture.debugElement.componentInstance.form = new FormGroup({'login': new FormControl('aa')}); fixture.detectChanges(); // model -> view const input = fixture.debugElement.query(By.css('input')); expect(input.nativeElement.value).toEqual('!aa!'); input.nativeElement.value = '!bb!'; dispatchEvent(input.nativeElement, 'input'); // view -> model expect(fixture.debugElement.componentInstance.form.value).toEqual({'login': 'bb'}); }); it('should support custom value accessors on non builtin input elements that fire a change event without a \'target\' property', () => { const fixture = TestBed.createComponent(MyInputForm); fixture.debugElement.componentInstance.form = new FormGroup({'login': new FormControl('aa')}); fixture.detectChanges(); const input = fixture.debugElement.query(By.css('my-input')); expect(input.componentInstance.value).toEqual('!aa!'); input.componentInstance.value = '!bb!'; input.componentInstance.onInput.subscribe((value: any) => { expect(fixture.debugElement.componentInstance.form.value).toEqual({'login': 'bb'}); }); input.componentInstance.dispatchChangeEvent(); }); }); }); describe('ngModel interactions', () => { it('should support ngModel for complex forms', fakeAsync(() => { const fixture = TestBed.createComponent(FormGroupNgModel); fixture.debugElement.componentInstance.form = new FormGroup({'login': new FormControl('')}); fixture.debugElement.componentInstance.login = 'oldValue'; fixture.detectChanges(); tick(); const input = fixture.debugElement.query(By.css('input')).nativeElement; expect(input.value).toEqual('oldValue'); input.value = 'updatedValue'; dispatchEvent(input, 'input'); tick(); expect(fixture.debugElement.componentInstance.login).toEqual('updatedValue'); })); it('should support ngModel for single fields', fakeAsync(() => { const fixture = TestBed.createComponent(FormControlNgModel); fixture.debugElement.componentInstance.control = new FormControl(''); fixture.debugElement.componentInstance.login = 'oldValue'; fixture.detectChanges(); tick(); const input = fixture.debugElement.query(By.css('input')).nativeElement; expect(input.value).toEqual('oldValue'); input.value = 'updatedValue'; dispatchEvent(input, 'input'); tick(); expect(fixture.debugElement.componentInstance.login).toEqual('updatedValue'); })); it('should not update the view when the value initially came from the view', fakeAsync(() => { const fixture = TestBed.createComponent(FormControlNgModel); fixture.debugElement.componentInstance.control = new FormControl(''); fixture.detectChanges(); tick(); const input = fixture.debugElement.query(By.css('input')).nativeElement; input.value = 'aa'; input.setSelectionRange(1, 2); dispatchEvent(input, 'input'); fixture.detectChanges(); tick(); // selection start has not changed because we did not reset the value expect(input.selectionStart).toEqual(1); })); }); describe('validations', () => { it('should use sync validators defined in html', () => { const fixture = TestBed.createComponent(LoginIsEmptyWrapper); const form = new FormGroup({ 'login': new FormControl(''), 'min': new FormControl(''), 'max': new FormControl(''), 'pattern': new FormControl('') }); fixture.debugElement.componentInstance.form = form; fixture.detectChanges(); const required = fixture.debugElement.query(By.css('[required]')); const minLength = fixture.debugElement.query(By.css('[minlength]')); const maxLength = fixture.debugElement.query(By.css('[maxlength]')); const pattern = fixture.debugElement.query(By.css('[pattern]')); required.nativeElement.value = ''; minLength.nativeElement.value = '1'; maxLength.nativeElement.value = '1234'; pattern.nativeElement.value = '12'; dispatchEvent(required.nativeElement, 'input'); dispatchEvent(minLength.nativeElement, 'input'); dispatchEvent(maxLength.nativeElement, 'input'); dispatchEvent(pattern.nativeElement, 'input'); expect(form.hasError('required', ['login'])).toEqual(true); expect(form.hasError('minlength', ['min'])).toEqual(true); expect(form.hasError('maxlength', ['max'])).toEqual(true); expect(form.hasError('pattern', ['pattern'])).toEqual(true); expect(form.hasError('loginIsEmpty')).toEqual(true); required.nativeElement.value = '1'; minLength.nativeElement.value = '123'; maxLength.nativeElement.value = '123'; pattern.nativeElement.value = '123'; dispatchEvent(required.nativeElement, 'input'); dispatchEvent(minLength.nativeElement, 'input'); dispatchEvent(maxLength.nativeElement, 'input'); dispatchEvent(pattern.nativeElement, 'input'); expect(form.valid).toEqual(true); }); it('should use sync validators using bindings', () => { const fixture = TestBed.createComponent(ValidationBindingsForm); const form = new FormGroup({ 'login': new FormControl(''), 'min': new FormControl(''), 'max': new FormControl(''), 'pattern': new FormControl('') }); fixture.debugElement.componentInstance.form = form; fixture.debugElement.componentInstance.required = true; fixture.debugElement.componentInstance.minLen = 3; fixture.debugElement.componentInstance.maxLen = 3; fixture.debugElement.componentInstance.pattern = '.{3,}'; fixture.detectChanges(); const required = fixture.debugElement.query(By.css('[name=required]')); const minLength = fixture.debugElement.query(By.css('[name=minlength]')); const maxLength = fixture.debugElement.query(By.css('[name=maxlength]')); const pattern = fixture.debugElement.query(By.css('[name=pattern]')); required.nativeElement.value = ''; minLength.nativeElement.value = '1'; maxLength.nativeElement.value = '1234'; pattern.nativeElement.value = '12'; dispatchEvent(required.nativeElement, 'input'); dispatchEvent(minLength.nativeElement, 'input'); dispatchEvent(maxLength.nativeElement, 'input'); dispatchEvent(pattern.nativeElement, 'input'); expect(form.hasError('required', ['login'])).toEqual(true); expect(form.hasError('minlength', ['min'])).toEqual(true); expect(form.hasError('maxlength', ['max'])).toEqual(true); expect(form.hasError('pattern', ['pattern'])).toEqual(true); required.nativeElement.value = '1'; minLength.nativeElement.value = '123'; maxLength.nativeElement.value = '123'; pattern.nativeElement.value = '123'; dispatchEvent(required.nativeElement, 'input'); dispatchEvent(minLength.nativeElement, 'input'); dispatchEvent(maxLength.nativeElement, 'input'); dispatchEvent(pattern.nativeElement, 'input'); expect(form.valid).toEqual(true); }); it('changes on bound properties should change the validation state of the form', () => { const fixture = TestBed.createComponent(ValidationBindingsForm); const form = new FormGroup({ 'login': new FormControl(''), 'min': new FormControl(''), 'max': new FormControl(''), 'pattern': new FormControl('') }); fixture.debugElement.componentInstance.form = form; fixture.detectChanges(); const required = fixture.debugElement.query(By.css('[name=required]')); const minLength = fixture.debugElement.query(By.css('[name=minlength]')); const maxLength = fixture.debugElement.query(By.css('[name=maxlength]')); const pattern = fixture.debugElement.query(By.css('[name=pattern]')); required.nativeElement.value = ''; minLength.nativeElement.value = '1'; maxLength.nativeElement.value = '1234'; pattern.nativeElement.value = '12'; dispatchEvent(required.nativeElement, 'input'); dispatchEvent(minLength.nativeElement, 'input'); dispatchEvent(maxLength.nativeElement, 'input'); dispatchEvent(pattern.nativeElement, 'input'); expect(form.hasError('required', ['login'])).toEqual(false); expect(form.hasError('minlength', ['min'])).toEqual(false); expect(form.hasError('maxlength', ['max'])).toEqual(false); expect(form.hasError('pattern', ['pattern'])).toEqual(false); expect(form.valid).toEqual(true); fixture.debugElement.componentInstance.required = true; fixture.debugElement.componentInstance.minLen = 3; fixture.debugElement.componentInstance.maxLen = 3; fixture.debugElement.componentInstance.pattern = '.{3,}'; fixture.detectChanges(); dispatchEvent(required.nativeElement, 'input'); dispatchEvent(minLength.nativeElement, 'input'); dispatchEvent(maxLength.nativeElement, 'input'); dispatchEvent(pattern.nativeElement, 'input'); expect(form.hasError('required', ['login'])).toEqual(true); expect(form.hasError('minlength', ['min'])).toEqual(true); expect(form.hasError('maxlength', ['max'])).toEqual(true); expect(form.hasError('pattern', ['pattern'])).toEqual(true); expect(form.valid).toEqual(false); expect(required.nativeElement.getAttribute('required')).toEqual(''); expect(fixture.debugElement.componentInstance.minLen.toString()) .toEqual(minLength.nativeElement.getAttribute('minlength')); expect(fixture.debugElement.componentInstance.maxLen.toString()) .toEqual(maxLength.nativeElement.getAttribute('maxlength')); expect(fixture.debugElement.componentInstance.pattern.toString()) .toEqual(pattern.nativeElement.getAttribute('pattern')); fixture.debugElement.componentInstance.required = false; fixture.debugElement.componentInstance.minLen = null; fixture.debugElement.componentInstance.maxLen = null; fixture.debugElement.componentInstance.pattern = null; fixture.detectChanges(); expect(form.hasError('required', ['login'])).toEqual(false); expect(form.hasError('minlength', ['min'])).toEqual(false); expect(form.hasError('maxlength', ['max'])).toEqual(false); expect(form.hasError('pattern', ['pattern'])).toEqual(false); expect(form.valid).toEqual(true); expect(required.nativeElement.getAttribute('required')).toEqual(null); expect(required.nativeElement.getAttribute('minlength')).toEqual(null); expect(required.nativeElement.getAttribute('maxlength')).toEqual(null); expect(required.nativeElement.getAttribute('pattern')).toEqual(null); }); it('should support rebound controls with rebound validators', () => { const fixture = TestBed.createComponent(ValidationBindingsForm); const form = new FormGroup({ 'login': new FormControl(''), 'min': new FormControl(''), 'max': new FormControl(''), 'pattern': new FormControl('') }); fixture.debugElement.componentInstance.form = form; fixture.debugElement.componentInstance.required = true; fixture.debugElement.componentInstance.minLen = 3; fixture.debugElement.componentInstance.maxLen = 3; fixture.debugElement.componentInstance.pattern = '.{3,}'; fixture.detectChanges(); const newForm = new FormGroup({ 'login': new FormControl(''), 'min': new FormControl(''), 'max': new FormControl(''), 'pattern': new FormControl('') }); fixture.debugElement.componentInstance.form = newForm; fixture.detectChanges(); fixture.debugElement.componentInstance.required = false; fixture.debugElement.componentInstance.minLen = null; fixture.debugElement.componentInstance.maxLen = null; fixture.debugElement.componentInstance.pattern = null; fixture.detectChanges(); expect(newForm.hasError('required', ['login'])).toEqual(false); expect(newForm.hasError('minlength', ['min'])).toEqual(false); expect(newForm.hasError('maxlength', ['max'])).toEqual(false); expect(newForm.hasError('pattern', ['pattern'])).toEqual(false); expect(newForm.valid).toEqual(true); }); it('should use async validators defined in the html', fakeAsync(() => { const fixture = TestBed.createComponent(UniqLoginWrapper); const form = new FormGroup({'login': new FormControl('')}); tick(); fixture.debugElement.componentInstance.form = form; fixture.detectChanges(); expect(form.pending).toEqual(true); tick(100); expect(form.hasError('uniqLogin', ['login'])).toEqual(true); const input = fixture.debugElement.query(By.css('input')); input.nativeElement.value = 'expected'; dispatchEvent(input.nativeElement, 'input'); tick(100); expect(form.valid).toEqual(true); })); it('should use sync validators defined in the model', () => { const fixture = TestBed.createComponent(FormGroupComp); const form = new FormGroup({'login': new FormControl('aa', Validators.required)}); fixture.debugElement.componentInstance.form = form; fixture.detectChanges(); expect(form.valid).toEqual(true); const input = fixture.debugElement.query(By.css('input')); input.nativeElement.value = ''; dispatchEvent(input.nativeElement, 'input'); expect(form.valid).toEqual(false); }); it('should use async validators defined in the model', fakeAsync(() => { const fixture = TestBed.createComponent(FormGroupComp); const control = new FormControl('', Validators.required, uniqLoginAsyncValidator('expected')); const form = new FormGroup({'login': control}); fixture.debugElement.componentInstance.form = form; fixture.detectChanges(); tick(); expect(form.hasError('required', ['login'])).toEqual(true); const input = fixture.debugElement.query(By.css('input')); input.nativeElement.value = 'wrong value'; dispatchEvent(input.nativeElement, 'input'); expect(form.pending).toEqual(true); tick(); expect(form.hasError('uniqLogin', ['login'])).toEqual(true); input.nativeElement.value = 'expected'; dispatchEvent(input.nativeElement, 'input'); tick(); expect(form.valid).toEqual(true); })); }); describe('errors', () => { it('should throw if a form isn\'t passed into formGroup', () => { const fixture = TestBed.createComponent(FormGroupComp); expect(() => fixture.detectChanges()) .toThrowError(new RegExp(`formGroup expects a FormGroup instance`)); }); it('should throw if formControlName is used without a control container', () => { TestBed.overrideComponent(FormGroupComp, { set: { template: ` <input type="text" formControlName="login"> ` } }); const fixture = TestBed.createComponent(FormGroupComp); expect(() => fixture.detectChanges()) .toThrowError( new RegExp(`formControlName must be used with a parent formGroup directive`)); }); it('should throw if formControlName is used with NgForm', () => { TestBed.overrideComponent(FormGroupComp, { set: { template: ` <form> <input type="text" formControlName="login"> </form> ` } }); const fixture = TestBed.createComponent(FormGroupComp); expect(() => fixture.detectChanges()) .toThrowError( new RegExp(`formControlName must be used with a parent formGroup directive.`)); }); it('should throw if formControlName is used with NgModelGroup', () => { TestBed.overrideComponent(FormGroupComp, { set: { template: ` <form> <div ngModelGroup="parent"> <input type="text" formControlName="login"> </div> </form> ` } }); const fixture = TestBed.createComponent(FormGroupComp); expect(() => fixture.detectChanges()) .toThrowError( new RegExp(`formControlName cannot be used with an ngModelGroup parent.`)); }); it('should throw if formGroupName is used without a control container', () => { TestBed.overrideComponent(FormGroupComp, { set: { template: ` <div formGroupName="person"> <input type="text" formControlName="login"> </div> ` } }); const fixture = TestBed.createComponent(FormGroupComp); expect(() => fixture.detectChanges()) .toThrowError( new RegExp(`formGroupName must be used with a parent formGroup directive`)); }); it('should throw if formGroupName is used with NgForm', () => { TestBed.overrideComponent(FormGroupComp, { set: { template: ` <form> <div formGroupName="person"> <input type="text" formControlName="login"> </div> </form> ` } }); const fixture = TestBed.createComponent(FormGroupComp); expect(() => fixture.detectChanges()) .toThrowError( new RegExp(`formGroupName must be used with a parent formGroup directive.`)); }); it('should throw if formArrayName is used without a control container', () => { TestBed.overrideComponent(FormGroupComp, { set: { template: ` <div formArrayName="cities"> <input type="text" formControlName="login"> </div> ` } }); const fixture = TestBed.createComponent(FormGroupComp); expect(() => fixture.detectChanges()) .toThrowError( new RegExp(`formArrayName must be used with a parent formGroup directive`)); }); it('should throw if ngModel is used alone under formGroup', () => { TestBed.overrideComponent(FormGroupComp, { set: { template: ` <div [formGroup]="myGroup"> <input type="text" [(ngModel)]="data"> </div> ` } }); const fixture = TestBed.createComponent(FormGroupComp); fixture.debugElement.componentInstance.myGroup = new FormGroup({}); expect(() => fixture.detectChanges()) .toThrowError(new RegExp( `ngModel cannot be used to register form controls with a parent formGroup directive.`)); }); it('should not throw if ngModel is used alone under formGroup with standalone: true', () => { TestBed.overrideComponent(FormGroupComp, { set: { template: ` <div [formGroup]="myGroup"> <input type="text" [(ngModel)]="data" [ngModelOptions]="{standalone: true}"> </div> ` } }); const fixture = TestBed.createComponent(FormGroupComp); fixture.debugElement.componentInstance.myGroup = new FormGroup({}); expect(() => fixture.detectChanges()).not.toThrowError(); }); it('should throw if ngModel is used alone with formGroupName', () => { TestBed.overrideComponent(FormGroupComp, { set: { template: ` <div [formGroup]="myGroup"> <div formGroupName="person"> <input type="text" [(ngModel)]="data"> </div> </div> ` } }); const fixture = TestBed.createComponent(FormGroupComp); const myGroup = new FormGroup({person: new FormGroup({})}); fixture.debugElement.componentInstance.myGroup = new FormGroup({person: new FormGroup({})}); expect(() => fixture.detectChanges()) .toThrowError(new RegExp( `ngModel cannot be used to register form controls with a parent formGroupName or formArrayName directive.`)); }); it('should throw if ngModelGroup is used with formGroup', () => { TestBed.overrideComponent(FormGroupComp, { set: { template: ` <div [formGroup]="myGroup"> <div ngModelGroup="person"> <input type="text" [(ngModel)]="data"> </div> </div> ` } }); const fixture = TestBed.createComponent(FormGroupComp); fixture.debugElement.componentInstance.myGroup = new FormGroup({}); expect(() => fixture.detectChanges()) .toThrowError( new RegExp(`ngModelGroup cannot be used with a parent formGroup directive`)); }); it('should throw if radio button name does not match formControlName attr', () => { TestBed.overrideComponent(FormGroupComp, { set: { template: ` <form [formGroup]="form">hav <input type="radio" formControlName="food" name="drink" value="chicken"> </form> ` } }); const fixture = TestBed.createComponent(FormGroupComp); fixture.debugElement.componentInstance.form = new FormGroup({'food': new FormControl('fish')}); expect(() => fixture.detectChanges()) .toThrowError(new RegExp('If you define both a name and a formControlName')); }); }); }); } @Directive({ selector: '[wrapped-value]', host: {'(input)': 'handleOnInput($event.target.value)', '[value]': 'value'} }) class WrappedValue implements ControlValueAccessor { value: any; onChange: Function; constructor(cd: NgControl) { cd.valueAccessor = this; } writeValue(value: any) { this.value = `!${value}!`; } registerOnChange(fn: (value: any) => void) { this.onChange = fn; } registerOnTouched(fn: any) {} handleOnInput(value: any) { this.onChange(value.substring(1, value.length - 1)); } } @Component({selector: 'my-input', template: ''}) class MyInput implements ControlValueAccessor { @Output('input') onInput = new EventEmitter(); value: string; constructor(cd: NgControl) { cd.valueAccessor = this; } writeValue(value: any) { this.value = `!${value}!`; } registerOnChange(fn: (value: any) => void) { this.onInput.subscribe({next: fn}); } registerOnTouched(fn: any) {} dispatchChangeEvent() { this.onInput.emit(this.value.substring(1, this.value.length - 1)); } } function uniqLoginAsyncValidator(expectedValue: string) { return (c: AbstractControl) => { var resolve: (result: any) => void; var promise = new Promise(res => { resolve = res; }); var res = (c.value == expectedValue) ? null : {'uniqLogin': true}; resolve(res); return promise; }; } function loginIsEmptyGroupValidator(c: FormGroup) { return c.controls['login'].value == '' ? {'loginIsEmpty': true} : null; } @Directive({ selector: '[login-is-empty-validator]', providers: [{provide: NG_VALIDATORS, useValue: loginIsEmptyGroupValidator, multi: true}] }) class LoginIsEmptyValidator { } @Directive({ selector: '[uniq-login-validator]', providers: [{ provide: NG_ASYNC_VALIDATORS, useExisting: forwardRef(() => UniqLoginValidator), multi: true }] }) class UniqLoginValidator implements Validator { @Input('uniq-login-validator') expected: any /** TODO #9100 */; validate(c: AbstractControl) { return uniqLoginAsyncValidator(this.expected)(c); } } function sortedClassList(el: HTMLElement) { var l = getDOM().classList(el); ListWrapper.sort(l); return l; } @Component({ selector: 'form-control-comp', template: ` <input type="text" [formControl]="control"> ` }) class FormControlComp { control: FormControl; } @Component({ selector: 'form-group-comp', template: ` <form [formGroup]="form" (ngSubmit)="data='submitted'"> <input type="text" formControlName="login"> </form> ` }) class FormGroupComp { form: FormGroup; data: string; } @Component({ selector: 'nested-form-group-comp', template: ` <form [formGroup]="form"> <div formGroupName="signin" login-is-empty-validator> <input formControlName="login"> <input formControlName="password"> </div> <input *ngIf="form.contains('email')" formControlName="email"> </form> ` }) class NestedFormGroupComp { form: FormGroup; } @Component({ selector: 'form-control-number-input', template: ` <input type="number" [formControl]="control"> ` }) class FormControlNumberInput { control: FormControl; } @Component({ selector: 'form-control-radio-buttons', template: ` <form [formGroup]="form" *ngIf="showRadio.value === 'yes'"> <input type="radio" formControlName="food" value="chicken"> <input type="radio" formControlName="food" value="fish"> <input type="radio" formControlName="drink" value="cola"> <input type="radio" formControlName="drink" value="sprite"> </form> <input type="radio" [formControl]="showRadio" value="yes"> <input type="radio" [formControl]="showRadio" value="no"> ` }) class FormControlRadioButtons { form: FormGroup; showRadio = new FormControl('yes'); } @Component({ selector: 'form-array-comp', template: ` <div [formGroup]="form"> <div formArrayName="cities"> <div *ngFor="let city of cityArray.controls; let i=index"> <input [formControlName]="i"> </div> </div> </div> ` }) class FormArrayComp { form: FormGroup; cityArray: FormArray; } @Component({ selector: 'form-array-nested-group', template: ` <div [formGroup]="form"> <div formArrayName="cities"> <div *ngFor="let city of cityArray.controls; let i=index" [formGroupName]="i"> <input formControlName="town"> <input formControlName="state"> </div> </div> </div> ` }) class FormArrayNestedGroup { form: FormGroup; cityArray: FormArray; } @Component({ selector: 'form-control-name-select', template: ` <div [formGroup]="form"> <select formControlName="city"> <option *ngFor="let c of cities" [value]="c"></option> </select> </div> ` }) class FormControlNameSelect { cities = ['SF', 'NY']; form = new FormGroup({city: new FormControl('SF')}); } @Component({ selector: 'wrapped-value-form', template: ` <div [formGroup]="form"> <input type="text" formControlName="login" wrapped-value> </div> ` }) class WrappedValueForm { form: FormGroup; } @Component({ selector: 'my-input-form', template: ` <div [formGroup]="form"> <my-input formControlName="login"></my-input> </div> ` }) class MyInputForm { form: FormGroup; } @Component({ selector: 'form-group-ng-model', template: ` <div [formGroup]="form"> <input type="text" formControlName="login" [(ngModel)]="login"> </div> ` }) class FormGroupNgModel { form: FormGroup; login: string; } @Component({ selector: 'form-control-ng-model', template: ` <input type="text" [formControl]="control" [(ngModel)]="login"> ` }) class FormControlNgModel { control: FormControl; login: string; } @Component({ selector: 'login-is-empty-wrapper', template: ` <div [formGroup]="form" login-is-empty-validator> <input type="text" formControlName="login" required> <input type="text" formControlName="min" minlength="3"> <input type="text" formControlName="max" maxlength="3"> <input type="text" formControlName="pattern" pattern=".{3,}"> </div> ` }) class LoginIsEmptyWrapper { form: FormGroup; } @Component({ selector: 'validation-bindings-form', template: ` <div [formGroup]="form"> <input name="required" type="text" formControlName="login" [required]="required"> <input name="minlength" type="text" formControlName="min" [minlength]="minLen"> <input name="maxlength" type="text" formControlName="max" [maxlength]="maxLen"> <input name="pattern" type="text" formControlName="pattern" [pattern]="pattern"> </div> ` }) class ValidationBindingsForm { form: FormGroup; required: boolean; minLen: number; maxLen: number; pattern: string; } @Component({ selector: 'uniq-login-wrapper', template: ` <div [formGroup]="form"> <input type="text" formControlName="login" uniq-login-validator="expected"> </div> ` }) class UniqLoginWrapper { form: FormGroup; }
modules/@angular/forms/test/reactive_integration_spec.ts
0
https://github.com/angular/angular/commit/d26a82749473803fbcbd735da46736779367521c
[ 0.00018114119302481413, 0.00017619627760723233, 0.0001688377815298736, 0.00017628482601139694, 0.0000024946834855654743 ]
{ "id": 11, "code_window": [ " loader.load('test#Named').then(contents => {\n", " expect(contents).toBe('test module factory');\n", " });\n", " }));\n", " it('loads a named factory with a configured prefix and suffix', async(() => {\n", " let loader = new SystemJsNgModuleLoader(new Compiler(), {\n", " factoryPathPrefix: 'prefixed/',\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " expect(contents).toBe('test NamedNgFactory');\n" ], "file_path": "modules/@angular/core/test/linker/system_ng_module_factory_loader_spec.ts", "type": "replace", "edit_start_line_idx": 33 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {resolveForwardRef} from '../di/forward_ref'; import {DependencyMetadata} from '../di/metadata'; import {OpaqueToken} from '../di/opaque_token'; import {StringWrapper, isString, stringify} from '../facade/lang'; import {Type} from '../type'; /** * This token can be used to create a virtual provider that will populate the * `entryComponents` fields of components and ng modules based on its `useValue`. * All components that are referenced in the `useValue` value (either directly * or in a nested array or map) will be added to the `entryComponents` property. * * ### Example * The following example shows how the router can populate the `entryComponents` * field of an NgModule based on the router configuration which refers * to components. * * ```typescript * // helper function inside the router * function provideRoutes(routes) { * return [ * {provide: ROUTES, useValue: routes}, * {provide: ANALYZE_FOR_ENTRY_COMPONENTS, useValue: routes, multi: true} * ]; * } * * // user code * let routes = [ * {path: '/root', component: RootComp}, * {path: /teams', component: TeamsComp} * ]; * * @NgModule({ * providers: [provideRoutes(routes)] * }) * class ModuleWithRoutes {} * ``` * * @experimental */ export const ANALYZE_FOR_ENTRY_COMPONENTS = new OpaqueToken('AnalyzeForEntryComponents'); /** * Specifies that a constant attribute value should be injected. * * The directive can inject constant string literals of host element attributes. * * ### Example * * Suppose we have an `<input>` element and want to know its `type`. * * ```html * <input type="text"> * ``` * * A decorator can inject string literal `text` like so: * * {@example core/ts/metadata/metadata.ts region='attributeMetadata'} * @stable */ export class AttributeMetadata extends DependencyMetadata { constructor(public attributeName: string) { super(); } get token(): AttributeMetadata { // Normally one would default a token to a type of an injected value but here // the type of a variable is "string" and we can't use primitive type as a return value // so we use instance of Attribute instead. This doesn't matter much in practice as arguments // with @Attribute annotation are injected by ElementInjector that doesn't take tokens into // account. return this; } toString(): string { return `@Attribute(${stringify(this.attributeName)})`; } } /** * Declares an injectable parameter to be a live list of directives or variable * bindings from the content children of a directive. * * ### Example ([live demo](http://plnkr.co/edit/lY9m8HLy7z06vDoUaSN2?p=preview)) * * Assume that `<tabs>` component would like to get a list its children `<pane>` * components as shown in this example: * * ```html * <tabs> * <pane title="Overview">...</pane> * <pane *ngFor="let o of objects" [title]="o.title">{{o.text}}</pane> * </tabs> * ``` * * The preferred solution is to query for `Pane` directives using this decorator. * * ```javascript * @Component({ * selector: 'pane', * inputs: ['title'] * }) * class Pane { * title:string; * } * * @Component({ * selector: 'tabs', * template: ` * <ul> * <li *ngFor="let pane of panes">{{pane.title}}</li> * </ul> * <ng-content></ng-content> * ` * }) * class Tabs { * @ContentChildren(Pane) panes: QueryList<Pane>; * } * ``` * * A query can look for variable bindings by passing in a string with desired binding symbol. * * ### Example ([live demo](http://plnkr.co/edit/sT2j25cH1dURAyBRCKx1?p=preview)) * ```html * <seeker> * <div #findme>...</div> * </seeker> * * @Component({ selector: 'seeker' }) * class Seeker { * @ContentChildren('findme') elList; * } * ``` * * In this case the object that is injected depend on the type of the variable * binding. It can be an ElementRef, a directive or a component. * * Passing in a comma separated list of variable bindings will query for all of them. * * ```html * <seeker> * <div #find-me>...</div> * <div #find-me-too>...</div> * </seeker> * * @Component({ * selector: 'seeker' * }) * class Seeker { * @ContentChildren('findMe, findMeToo') elList: QueryList<ElementRef>; * } * ``` * * Configure whether query looks for direct children or all descendants * of the querying element, by using the `descendants` parameter. * It is set to `false` by default. * * ### Example ([live demo](http://plnkr.co/edit/wtGeB977bv7qvA5FTYl9?p=preview)) * ```html * <container #first> * <item>a</item> * <item>b</item> * <container #second> * <item>c</item> * </container> * </container> * ``` * * When querying for items, the first container will see only `a` and `b` by default, * but with `ContentChildren(TextDirective, {descendants: true})` it will see `c` too. * * The queried directives are kept in a depth-first pre-order with respect to their * positions in the DOM. * * ContentChildren does not look deep into any subcomponent views. * * ContentChildren is updated as part of the change-detection cycle. Since change detection * happens after construction of a directive, QueryList will always be empty when observed in the * constructor. * * The injected object is an unmodifiable live list. * See {@link QueryList} for more details. * @stable */ export class QueryMetadata extends DependencyMetadata { /** * whether we want to query only direct children (false) or all * children (true). */ descendants: boolean; first: boolean; /** * The DI token to read from an element that matches the selector. */ read: any; constructor( private _selector: Type<any>|string, {descendants = false, first = false, read = null}: {descendants?: boolean, first?: boolean, read?: any} = {}) { super(); this.descendants = descendants; this.first = first; this.read = read; } /** * always `false` to differentiate it with {@link ViewQueryMetadata}. */ get isViewQuery(): boolean { return false; } /** * what this is querying for. */ get selector() { return resolveForwardRef(this._selector); } /** * whether this is querying for a variable binding or a directive. */ get isVarBindingQuery(): boolean { return isString(this.selector); } /** * returns a list of variable bindings this is querying for. * Only applicable if this is a variable bindings query. */ get varBindings(): string[] { return StringWrapper.split(this.selector, /\s*,\s*/g); } toString(): string { return `@Query(${stringify(this.selector)})`; } } // TODO: add an example after ContentChildren and ViewChildren are in master /** * Configures a content query. * * Content queries are set before the `ngAfterContentInit` callback is called. * * ### Example * * ``` * @Directive({ * selector: 'someDir' * }) * class SomeDir { * @ContentChildren(ChildDirective) contentChildren: QueryList<ChildDirective>; * * ngAfterContentInit() { * // contentChildren is set * } * } * ``` * @stable */ export class ContentChildrenMetadata extends QueryMetadata { constructor( _selector: Type<any>|string, {descendants = false, read = null}: {descendants?: boolean, read?: any} = {}) { super(_selector, {descendants: descendants, read: read}); } } // TODO: add an example after ContentChild and ViewChild are in master /** * Configures a content query. * * Content queries are set before the `ngAfterContentInit` callback is called. * * ### Example * * ``` * @Directive({ * selector: 'someDir' * }) * class SomeDir { * @ContentChild(ChildDirective) contentChild; * * ngAfterContentInit() { * // contentChild is set * } * } * ``` * @stable */ export class ContentChildMetadata extends QueryMetadata { constructor(_selector: Type<any>|string, {read = null}: {read?: any} = {}) { super(_selector, {descendants: true, first: true, read: read}); } } /** * Similar to {@link ContentChildMetadata}, but querying the component view, instead * of the content children. * * ### Example ([live demo](http://plnkr.co/edit/eNsFHDf7YjyM6IzKxM1j?p=preview)) * * ```javascript * @Component({ * ..., * template: ` * <item> a </item> * <item> b </item> * <item> c </item> * ` * }) * class MyComponent { * shown: boolean; * * constructor(private @ViewChildren(Item) items:QueryList<Item>) { * items.changes.subscribe(() => console.log(items.length)); * } * } * ``` * * As `shown` is flipped between true and false, items will contain zero of one * items. * * Specifies that a {@link QueryList} should be injected. * * The injected object is an iterable and observable live list. * See {@link QueryList} for more details. * @stable */ export class ViewQueryMetadata extends QueryMetadata { constructor( _selector: Type<any>|string, {descendants = false, first = false, read = null}: {descendants?: boolean, first?: boolean, read?: any} = {}) { super(_selector, {descendants: descendants, first: first, read: read}); } /** * always `true` to differentiate it with {@link QueryMetadata}. */ get isViewQuery() { return true; } } /** * Declares a list of child element references. * * Angular automatically updates the list when the DOM is updated. * * `ViewChildren` takes an argument to select elements. * * - If the argument is a type, directives or components with the type will be bound. * * - If the argument is a string, the string is interpreted as a list of comma-separated selectors. * For each selector, an element containing the matching template variable (e.g. `#child`) will be * bound. * * View children are set before the `ngAfterViewInit` callback is called. * * ### Example * * With type selector: * * ``` * @Component({ * selector: 'child-cmp', * template: '<p>child</p>' * }) * class ChildCmp { * doSomething() {} * } * * @Component({ * selector: 'some-cmp', * template: ` * <child-cmp></child-cmp> * <child-cmp></child-cmp> * <child-cmp></child-cmp> * `, * directives: [ChildCmp] * }) * class SomeCmp { * @ViewChildren(ChildCmp) children:QueryList<ChildCmp>; * * ngAfterViewInit() { * // children are set * this.children.toArray().forEach((child)=>child.doSomething()); * } * } * ``` * * With string selector: * * ``` * @Component({ * selector: 'child-cmp', * template: '<p>child</p>' * }) * class ChildCmp { * doSomething() {} * } * * @Component({ * selector: 'some-cmp', * template: ` * <child-cmp #child1></child-cmp> * <child-cmp #child2></child-cmp> * <child-cmp #child3></child-cmp> * `, * directives: [ChildCmp] * }) * class SomeCmp { * @ViewChildren('child1,child2,child3') children:QueryList<ChildCmp>; * * ngAfterViewInit() { * // children are set * this.children.toArray().forEach((child)=>child.doSomething()); * } * } * ``` * @stable */ export class ViewChildrenMetadata extends ViewQueryMetadata { constructor(_selector: Type<any>|string, {read = null}: {read?: any} = {}) { super(_selector, {descendants: true, read: read}); } toString(): string { return `@ViewChildren(${stringify(this.selector)})`; } } /** * * Declares a reference of child element. * * `ViewChildren` takes an argument to select elements. * * - If the argument is a type, a directive or a component with the type will be bound. * * If the argument is a string, the string is interpreted as a selector. An element containing the * matching template variable (e.g. `#child`) will be bound. * * In either case, `@ViewChild()` assigns the first (looking from above) element if there are multiple matches. * * View child is set before the `ngAfterViewInit` callback is called. * * ### Example * * With type selector: * * ``` * @Component({ * selector: 'child-cmp', * template: '<p>child</p>' * }) * class ChildCmp { * doSomething() {} * } * * @Component({ * selector: 'some-cmp', * template: '<child-cmp></child-cmp>', * directives: [ChildCmp] * }) * class SomeCmp { * @ViewChild(ChildCmp) child:ChildCmp; * * ngAfterViewInit() { * // child is set * this.child.doSomething(); * } * } * ``` * * With string selector: * * ``` * @Component({ * selector: 'child-cmp', * template: '<p>child</p>' * }) * class ChildCmp { * doSomething() {} * } * * @Component({ * selector: 'some-cmp', * template: '<child-cmp #child></child-cmp>', * directives: [ChildCmp] * }) * class SomeCmp { * @ViewChild('child') child:ChildCmp; * * ngAfterViewInit() { * // child is set * this.child.doSomething(); * } * } * ``` * @stable */ export class ViewChildMetadata extends ViewQueryMetadata { constructor(_selector: Type<any>|string, {read = null}: {read?: any} = {}) { super(_selector, {descendants: true, first: true, read: read}); } }
modules/@angular/core/src/metadata/di.ts
0
https://github.com/angular/angular/commit/d26a82749473803fbcbd735da46736779367521c
[ 0.00022287489264272153, 0.00017088843742385507, 0.00016105317627079785, 0.00017126694729086012, 0.000008818619789963122 ]
{ "id": 11, "code_window": [ " loader.load('test#Named').then(contents => {\n", " expect(contents).toBe('test module factory');\n", " });\n", " }));\n", " it('loads a named factory with a configured prefix and suffix', async(() => {\n", " let loader = new SystemJsNgModuleLoader(new Compiler(), {\n", " factoryPathPrefix: 'prefixed/',\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " expect(contents).toBe('test NamedNgFactory');\n" ], "file_path": "modules/@angular/core/test/linker/system_ng_module_factory_loader_spec.ts", "type": "replace", "edit_start_line_idx": 33 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * @module * @description * Entry point for all public APIs of the common package. */ export * from './src/common'; // This file only reexports content of the `src` folder. Keep it that way.
modules/@angular/common/index.ts
0
https://github.com/angular/angular/commit/d26a82749473803fbcbd735da46736779367521c
[ 0.000176712273969315, 0.0001704026071820408, 0.00016409295494668186, 0.0001704026071820408, 0.000006309659511316568 ]
{ "id": 12, "code_window": [ " let loader = new SystemJsNgModuleLoader(new Compiler(), {\n", " factoryPathPrefix: 'prefixed/',\n", " factoryPathSuffix: '/suffixed',\n", " });\n", " loader._system = () =>\n", " mockSystem('prefixed/test/suffixed', {'NamedNgFactory': 'test module factory'});\n", " loader.load('test#Named').then(contents => {\n", " expect(contents).toBe('test module factory');\n", " });\n", " }));\n", " });\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "modules/@angular/core/test/linker/system_ng_module_factory_loader_spec.ts", "type": "replace", "edit_start_line_idx": 41 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {Injectable, Optional} from '../di'; import {Compiler} from './compiler'; import {NgModuleFactory} from './ng_module_factory'; import {NgModuleFactoryLoader} from './ng_module_factory_loader'; const _SEPARATOR = '#'; const FACTORY_CLASS_SUFFIX = 'NgFactory'; /** * Configuration for SystemJsNgModuleLoader. * token. * * @experimental */ export abstract class SystemJsNgModuleLoaderConfig { /** * Prefix to add when computing the name of the factory module for a given module name. */ factoryPathPrefix: string; /** * Suffix to add when computing the name of the factory module for a given module name. */ factoryPathSuffix: string; } const DEFAULT_CONFIG: SystemJsNgModuleLoaderConfig = { factoryPathPrefix: '', factoryPathSuffix: '.ngfactory', }; /** * NgModuleFactoryLoader that uses SystemJS to load NgModuleFactory * @experimental */ @Injectable() export class SystemJsNgModuleLoader implements NgModuleFactoryLoader { private _config: SystemJsNgModuleLoaderConfig; /** * @internal */ _system: any; constructor(private _compiler: Compiler, @Optional() config?: SystemJsNgModuleLoaderConfig) { this._system = () => System; this._config = config || DEFAULT_CONFIG; } load(path: string): Promise<NgModuleFactory<any>> { const offlineMode = this._compiler instanceof Compiler; return offlineMode ? this.loadFactory(path) : this.loadAndCompile(path); } private loadAndCompile(path: string): Promise<NgModuleFactory<any>> { let [module, exportName] = path.split(_SEPARATOR); if (exportName === undefined) exportName = 'default'; return this._system() .import(module) .then((module: any) => module[exportName]) .then((type: any) => checkNotEmpty(type, module, exportName)) .then((type: any) => this._compiler.compileModuleAsync(type)); } private loadFactory(path: string): Promise<NgModuleFactory<any>> { let [module, exportName] = path.split(_SEPARATOR); let factoryClassSuffix = FACTORY_CLASS_SUFFIX; if (exportName === undefined) { exportName = 'default'; factoryClassSuffix = ''; } return this._system() .import(this._config.factoryPathPrefix + module + this._config.factoryPathSuffix) .then((module: any) => module[exportName + factoryClassSuffix]) .then((factory: any) => checkNotEmpty(factory, module, exportName)); } } function checkNotEmpty(value: any, modulePath: string, exportName: string): any { if (!value) { throw new Error(`Cannot find '${exportName}' in '${modulePath}'`); } return value; }
modules/@angular/core/src/linker/system_js_ng_module_factory_loader.ts
1
https://github.com/angular/angular/commit/d26a82749473803fbcbd735da46736779367521c
[ 0.00441043172031641, 0.0016423886409029365, 0.00016265263548120856, 0.0013609131565317512, 0.0014519207179546356 ]
{ "id": 12, "code_window": [ " let loader = new SystemJsNgModuleLoader(new Compiler(), {\n", " factoryPathPrefix: 'prefixed/',\n", " factoryPathSuffix: '/suffixed',\n", " });\n", " loader._system = () =>\n", " mockSystem('prefixed/test/suffixed', {'NamedNgFactory': 'test module factory'});\n", " loader.load('test#Named').then(contents => {\n", " expect(contents).toBe('test module factory');\n", " });\n", " }));\n", " });\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "modules/@angular/core/test/linker/system_ng_module_factory_loader_spec.ts", "type": "replace", "edit_start_line_idx": 41 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {ClassProvider, ExistingProvider, FactoryProvider, Provider, TypeProvider, ValueProvider} from '@angular/core'; import * as browser from './browser'; import * as browserDomAdapter from './browser/browser_adapter'; import * as location from './browser/location/browser_platform_location'; import * as testability from './browser/testability'; import * as ng_probe from './dom/debug/ng_probe'; import * as dom_adapter from './dom/dom_adapter'; import * as dom_renderer from './dom/dom_renderer'; import * as dom_events from './dom/events/dom_events'; import * as hammer_gesture from './dom/events/hammer_gestures'; import * as key_events from './dom/events/key_events'; import * as shared_styles_host from './dom/shared_styles_host'; export var __platform_browser_private__: { _BrowserPlatformLocation?: location.BrowserPlatformLocation, BrowserPlatformLocation: typeof location.BrowserPlatformLocation, _DomAdapter?: dom_adapter.DomAdapter, DomAdapter: typeof dom_adapter.DomAdapter, _BrowserDomAdapter?: browserDomAdapter.BrowserDomAdapter, BrowserDomAdapter: typeof browserDomAdapter.BrowserDomAdapter, _BrowserGetTestability?: testability.BrowserGetTestability, BrowserGetTestability: typeof testability.BrowserGetTestability, getDOM: typeof dom_adapter.getDOM, setRootDomAdapter: typeof dom_adapter.setRootDomAdapter, _DomRootRenderer?: dom_renderer.DomRootRenderer, DomRootRenderer: typeof dom_renderer.DomRootRenderer, _DomRootRenderer_?: dom_renderer.DomRootRenderer, DomRootRenderer_: typeof dom_renderer.DomRootRenderer_, _DomSharedStylesHost?: shared_styles_host.DomSharedStylesHost, DomSharedStylesHost: typeof shared_styles_host.DomSharedStylesHost, _SharedStylesHost?: shared_styles_host.SharedStylesHost, SharedStylesHost: typeof shared_styles_host.SharedStylesHost, ELEMENT_PROBE_PROVIDERS: typeof ng_probe.ELEMENT_PROBE_PROVIDERS, _DomEventsPlugin?: dom_events.DomEventsPlugin, DomEventsPlugin: typeof dom_events.DomEventsPlugin, _KeyEventsPlugin?: key_events.KeyEventsPlugin, KeyEventsPlugin: typeof key_events.KeyEventsPlugin, _HammerGesturesPlugin?: hammer_gesture.HammerGesturesPlugin, HammerGesturesPlugin: typeof hammer_gesture.HammerGesturesPlugin, initDomAdapter: typeof browser.initDomAdapter, INTERNAL_BROWSER_PLATFORM_PROVIDERS: typeof browser.INTERNAL_BROWSER_PLATFORM_PROVIDERS, BROWSER_SANITIZATION_PROVIDERS: typeof browser.BROWSER_SANITIZATION_PROVIDERS } = { BrowserPlatformLocation: location.BrowserPlatformLocation, DomAdapter: dom_adapter.DomAdapter, BrowserDomAdapter: browserDomAdapter.BrowserDomAdapter, BrowserGetTestability: testability.BrowserGetTestability, getDOM: dom_adapter.getDOM, setRootDomAdapter: dom_adapter.setRootDomAdapter, DomRootRenderer_: dom_renderer.DomRootRenderer_, DomRootRenderer: dom_renderer.DomRootRenderer, DomSharedStylesHost: shared_styles_host.DomSharedStylesHost, SharedStylesHost: shared_styles_host.SharedStylesHost, ELEMENT_PROBE_PROVIDERS: ng_probe.ELEMENT_PROBE_PROVIDERS, DomEventsPlugin: dom_events.DomEventsPlugin, KeyEventsPlugin: key_events.KeyEventsPlugin, HammerGesturesPlugin: hammer_gesture.HammerGesturesPlugin, initDomAdapter: browser.initDomAdapter, INTERNAL_BROWSER_PLATFORM_PROVIDERS: browser.INTERNAL_BROWSER_PLATFORM_PROVIDERS, BROWSER_SANITIZATION_PROVIDERS: browser.BROWSER_SANITIZATION_PROVIDERS };
modules/@angular/platform-browser/src/private_export.ts
0
https://github.com/angular/angular/commit/d26a82749473803fbcbd735da46736779367521c
[ 0.0031588796991854906, 0.0005422376561909914, 0.00016378094733227044, 0.00016817275900393724, 0.0009890057845041156 ]
{ "id": 12, "code_window": [ " let loader = new SystemJsNgModuleLoader(new Compiler(), {\n", " factoryPathPrefix: 'prefixed/',\n", " factoryPathSuffix: '/suffixed',\n", " });\n", " loader._system = () =>\n", " mockSystem('prefixed/test/suffixed', {'NamedNgFactory': 'test module factory'});\n", " loader.load('test#Named').then(contents => {\n", " expect(contents).toBe('test module factory');\n", " });\n", " }));\n", " });\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "modules/@angular/core/test/linker/system_ng_module_factory_loader_spec.ts", "type": "replace", "edit_start_line_idx": 41 }
export default { entry: '../../../dist/packages-dist/platform-server/testing/index.js', dest: '../../../dist/packages-dist/platform-server/bundles/platform-server-testing.umd.js', format: 'umd', moduleName: 'ng.platformServer.testing', globals: { '@angular/core': 'ng.core', '@angular/common': 'ng.common', '@angular/compiler': 'ng.compiler', '@angular/compiler/testing': 'ng.compiler.testing', '@angular/platform-browser': 'ng.platformBrowser', '@angular/platform-server': 'ng.platformServer', '@angular/platform-browser-dynamic/testing': 'ng.platformBrowserDynamic.testing' } }
modules/@angular/platform-server/rollup-testing.config.js
0
https://github.com/angular/angular/commit/d26a82749473803fbcbd735da46736779367521c
[ 0.00017066093278117478, 0.00016849333769641817, 0.00016632574261166155, 0.00016849333769641817, 0.0000021675950847566128 ]
{ "id": 12, "code_window": [ " let loader = new SystemJsNgModuleLoader(new Compiler(), {\n", " factoryPathPrefix: 'prefixed/',\n", " factoryPathSuffix: '/suffixed',\n", " });\n", " loader._system = () =>\n", " mockSystem('prefixed/test/suffixed', {'NamedNgFactory': 'test module factory'});\n", " loader.load('test#Named').then(contents => {\n", " expect(contents).toBe('test module factory');\n", " });\n", " }));\n", " });\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "modules/@angular/core/test/linker/system_ng_module_factory_loader_spec.ts", "type": "replace", "edit_start_line_idx": 41 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {Component, NgModule} from '@angular/core'; import {BrowserModule} from '@angular/platform-browser'; import {platformBrowserDynamic} from '@angular/platform-browser-dynamic'; // #docregion LowerUpperPipe @Component({ selector: 'lowerupper-example', template: `<div> <label>Name: </label><input #name (keyup)="change(name.value)" type="text"> <p>In lowercase: <pre>'{{value | lowercase}}'</pre></p> <p>In uppercase: <pre>'{{value | uppercase}}'</pre></p> </div>` }) export class LowerUpperPipeExample { value: string; change(value: string) { this.value = value; } } // #enddocregion @Component({ selector: 'example-app', template: ` <h1>LowercasePipe &amp; UppercasePipe Example</h1> <lowerupper-example></lowerupper-example> ` }) export class AppCmp { } @NgModule({imports: [BrowserModule], bootstrap: [AppCmp]}) class AppModule { } export function main() { platformBrowserDynamic().bootstrapModule(AppModule); }
modules/@angular/examples/core/pipes/ts/lowerupper_pipe/lowerupper_pipe_example.ts
0
https://github.com/angular/angular/commit/d26a82749473803fbcbd735da46736779367521c
[ 0.00017618986021261662, 0.00017135792586486787, 0.0001644157455302775, 0.00017195774125866592, 0.000004080401140527101 ]
{ "id": 0, "code_window": [ "\n", " throw error;\n", " }\n", ");\n", "\n", "const wrapper = process.env.NODE_ENV === 'development' ? wrapAxiosInstance(instance) : instance;\n", "\n", "export default wrapper;" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ "const wrapper = wrapAxiosInstance(instance);\n" ], "file_path": "packages/core/admin/admin/src/core/utils/axiosInstance.js", "type": "replace", "edit_start_line_idx": 35 }
import axios from 'axios'; import { auth, wrapAxiosInstance } from '@strapi/helper-plugin'; const instance = axios.create({ baseURL: process.env.STRAPI_ADMIN_BACKEND_URL, }); instance.interceptors.request.use( async (config) => { config.headers = { Authorization: `Bearer ${auth.getToken()}`, Accept: 'application/json', 'Content-Type': 'application/json', }; return config; }, (error) => { Promise.reject(error); } ); instance.interceptors.response.use( (response) => response, (error) => { // whatever you want to do with the error if (error.response?.status === 401) { auth.clearAppStorage(); window.location.reload(); } throw error; } ); const wrapper = process.env.NODE_ENV === 'development' ? wrapAxiosInstance(instance) : instance; export default wrapper;
packages/plugins/users-permissions/admin/src/utils/axiosInstance.js
1
https://github.com/strapi/strapi/commit/7a06c7e44491514fad57e553f17ebfaee00061e7
[ 0.9984232187271118, 0.25081464648246765, 0.00016594951739534736, 0.002334702294319868, 0.4316331446170807 ]
{ "id": 0, "code_window": [ "\n", " throw error;\n", " }\n", ");\n", "\n", "const wrapper = process.env.NODE_ENV === 'development' ? wrapAxiosInstance(instance) : instance;\n", "\n", "export default wrapper;" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ "const wrapper = wrapAxiosInstance(instance);\n" ], "file_path": "packages/core/admin/admin/src/core/utils/axiosInstance.js", "type": "replace", "edit_start_line_idx": 35 }
const IS_DISABLED = false; export default IS_DISABLED;
packages/core/admin/ee/admin/pages/SettingsPage/pages/Roles/EditPage/components/ConditionsModal/ConditionsSelect/MenuList/utils/constants.js
0
https://github.com/strapi/strapi/commit/7a06c7e44491514fad57e553f17ebfaee00061e7
[ 0.0002753371081780642, 0.0002753371081780642, 0.0002753371081780642, 0.0002753371081780642, 0 ]
{ "id": 0, "code_window": [ "\n", " throw error;\n", " }\n", ");\n", "\n", "const wrapper = process.env.NODE_ENV === 'development' ? wrapAxiosInstance(instance) : instance;\n", "\n", "export default wrapper;" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ "const wrapper = wrapAxiosInstance(instance);\n" ], "file_path": "packages/core/admin/admin/src/core/utils/axiosInstance.js", "type": "replace", "edit_start_line_idx": 35 }
'use strict'; const { yup, validateYupSchema } = require('@strapi/utils'); const renewToken = yup.object().shape({ token: yup.string().required() }).required().noUnknown(); module.exports = validateYupSchema(renewToken);
packages/core/admin/server/validation/authentication/renew-token.js
0
https://github.com/strapi/strapi/commit/7a06c7e44491514fad57e553f17ebfaee00061e7
[ 0.00016865355428308249, 0.00016865355428308249, 0.00016865355428308249, 0.00016865355428308249, 0 ]
{ "id": 0, "code_window": [ "\n", " throw error;\n", " }\n", ");\n", "\n", "const wrapper = process.env.NODE_ENV === 'development' ? wrapAxiosInstance(instance) : instance;\n", "\n", "export default wrapper;" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ "const wrapper = wrapAxiosInstance(instance);\n" ], "file_path": "packages/core/admin/admin/src/core/utils/axiosInstance.js", "type": "replace", "edit_start_line_idx": 35 }
'use strict'; const fs = require('fs'); const path = require('path'); const glob = require('glob'); const PACKAGES_DIR_PATH = 'packages/'; const TRANSLATION_FILE_PATH = '/admin/src/translations/en.json'; const getPackageNameFromPath = (filePath) => { return filePath.replace(PACKAGES_DIR_PATH, '').replace(TRANSLATION_FILE_PATH, ''); }; const readTranslationFile = (filePath) => ({ filePath, packageName: getPackageNameFromPath(filePath), fileContent: JSON.parse(fs.readFileSync(filePath).toString('utf-8')), }); const writeTranslationFile = (file) => { fs.writeFileSync(file.filePath, `${JSON.stringify(file.fileContent, null, 2)}\n`); }; const readAllTranslationFiles = () => { const translationFilesPaths = [ ...glob.sync(path.join(PACKAGES_DIR_PATH, 'core/*/', TRANSLATION_FILE_PATH)), ...glob.sync(path.join(PACKAGES_DIR_PATH, 'plugins/*/', TRANSLATION_FILE_PATH)), ]; return translationFilesPaths.map(readTranslationFile); }; const writeAllTranslationFiles = (files) => { files.forEach(writeTranslationFile); }; module.exports = { readTranslationFile, writeTranslationFile, readAllTranslationFiles, writeAllTranslationFiles, };
scripts/front/utils/translation-files.js
0
https://github.com/strapi/strapi/commit/7a06c7e44491514fad57e553f17ebfaee00061e7
[ 0.00017013223259709775, 0.00016795755072962493, 0.00016630449681542814, 0.00016706963651813567, 0.0000017095403563871514 ]
{ "id": 1, "code_window": [ " throw error;\n", " }\n", ");\n", "\n", "const wrapper = process.env.NODE_ENV === 'development' ? wrapAxiosInstance(instance) : instance;\n", "\n", "export default wrapper;" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ "const wrapper = wrapAxiosInstance(instance);\n" ], "file_path": "packages/core/content-type-builder/admin/src/utils/axiosInstance.js", "type": "replace", "edit_start_line_idx": 37 }
/** * axios with a custom config. */ import axios from 'axios'; import { auth, wrapAxiosInstance } from '@strapi/helper-plugin'; const instance = axios.create({ baseURL: process.env.STRAPI_ADMIN_BACKEND_URL, }); instance.interceptors.request.use( async (config) => { config.headers = { Authorization: `Bearer ${auth.getToken()}`, Accept: 'application/json', 'Content-Type': 'application/json', }; return config; }, (error) => { Promise.reject(error); } ); instance.interceptors.response.use( (response) => response, (error) => { // whatever you want to do with the error if (error.response?.status === 401) { auth.clearAppStorage(); window.location.reload(); } throw error; } ); const wrapper = process.env.NODE_ENV === 'development' ? wrapAxiosInstance(instance) : instance; export default wrapper;
packages/generators/generators/lib/files/js/plugin/admin/src/utils/axiosInstance.js
1
https://github.com/strapi/strapi/commit/7a06c7e44491514fad57e553f17ebfaee00061e7
[ 0.997718095779419, 0.2032688558101654, 0.00016829179367050529, 0.002817424712702632, 0.39725983142852783 ]
{ "id": 1, "code_window": [ " throw error;\n", " }\n", ");\n", "\n", "const wrapper = process.env.NODE_ENV === 'development' ? wrapAxiosInstance(instance) : instance;\n", "\n", "export default wrapper;" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ "const wrapper = wrapAxiosInstance(instance);\n" ], "file_path": "packages/core/content-type-builder/admin/src/utils/axiosInstance.js", "type": "replace", "edit_start_line_idx": 37 }
import React from 'react'; import PropTypes from 'prop-types'; import styled from 'styled-components'; import Cross from '@strapi/icons/Cross'; import { Typography } from '@strapi/design-system/Typography'; import { Box } from '@strapi/design-system/Box'; import { Flex } from '@strapi/design-system/Flex'; import { ProgressBar } from '@strapi/design-system/ProgressBar'; import { useIntl } from 'react-intl'; const BoxWrapper = styled(Flex)` width: 100%; height: 100%; flex-direction: column; svg { path { fill: ${({ theme, error }) => (error ? theme.colors.danger600 : undefined)}; } } `; const CancelButton = styled.button` border: none; background: none; display: flex; align-items: center; svg { path { fill: ${({ theme }) => theme.colors.neutral200}; } height: 10px; width: 10px; } `; export const UploadProgress = ({ onCancel, progress, error }) => { const { formatMessage } = useIntl(); return ( <BoxWrapper background={error ? 'danger100' : 'neutral700'} justifyContent="center" error={error} hasRadius > {error ? ( <Cross aria-label={error?.message} /> ) : ( <> <Box paddingBottom={2}> <ProgressBar value={progress} size="S"> {`${progress}/100%`} </ProgressBar> </Box> <CancelButton type="button" onClick={onCancel}> <Typography variant="pi" as="span" textColor="neutral200"> {formatMessage({ id: 'app.components.Button.cancel', defaultMessage: 'Cancel', })} </Typography> <Box as="span" paddingLeft={2} aria-hidden> <Cross /> </Box> </CancelButton> </> )} </BoxWrapper> ); }; UploadProgress.defaultProps = { error: undefined, progress: 0, }; UploadProgress.propTypes = { error: PropTypes.instanceOf(Error), onCancel: PropTypes.func.isRequired, progress: PropTypes.number, };
packages/core/upload/admin/src/components/UploadProgress/index.js
0
https://github.com/strapi/strapi/commit/7a06c7e44491514fad57e553f17ebfaee00061e7
[ 0.0002223720366600901, 0.00017513666534796357, 0.00016538493218831718, 0.00016956815670710057, 0.00001693296871962957 ]
{ "id": 1, "code_window": [ " throw error;\n", " }\n", ");\n", "\n", "const wrapper = process.env.NODE_ENV === 'development' ? wrapAxiosInstance(instance) : instance;\n", "\n", "export default wrapper;" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ "const wrapper = wrapAxiosInstance(instance);\n" ], "file_path": "packages/core/content-type-builder/admin/src/utils/axiosInstance.js", "type": "replace", "edit_start_line_idx": 37 }
'use strict'; const destroyOnSignal = (strapi) => { let signalReceived = false; // For unknown reasons, we receive signals 2 times. // As a temporary fix, we ignore the signals received after the first one. const terminateStrapi = async () => { if (!signalReceived) { signalReceived = true; await strapi.destroy(); process.exit(); } }; ['SIGTERM', 'SIGINT'].forEach((signal) => { process.on(signal, terminateStrapi); }); }; module.exports = { destroyOnSignal, };
packages/core/strapi/lib/utils/signals.js
0
https://github.com/strapi/strapi/commit/7a06c7e44491514fad57e553f17ebfaee00061e7
[ 0.00016986737318802625, 0.0001677532127359882, 0.00016446718655060977, 0.00016892507846932858, 0.000002355200876991148 ]
{ "id": 1, "code_window": [ " throw error;\n", " }\n", ");\n", "\n", "const wrapper = process.env.NODE_ENV === 'development' ? wrapAxiosInstance(instance) : instance;\n", "\n", "export default wrapper;" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ "const wrapper = wrapAxiosInstance(instance);\n" ], "file_path": "packages/core/content-type-builder/admin/src/utils/axiosInstance.js", "type": "replace", "edit_start_line_idx": 37 }
import pluginId from '../pluginId'; const getRequestURL = (endPoint) => `/${pluginId}/${endPoint}`; export default getRequestURL;
packages/plugins/users-permissions/admin/src/utils/getRequestURL.js
0
https://github.com/strapi/strapi/commit/7a06c7e44491514fad57e553f17ebfaee00061e7
[ 0.0001782089238986373, 0.0001782089238986373, 0.0001782089238986373, 0.0001782089238986373, 0 ]
{ "id": 2, "code_window": [ "\n", " throw error;\n", " }\n", ");\n", "\n", "const wrapper = process.env.NODE_ENV === 'development' ? wrapAxiosInstance(instance) : instance;\n", "\n", "export default wrapper;" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ "const wrapper = wrapAxiosInstance(instance);\n" ], "file_path": "packages/core/email/admin/src/utils/axiosInstance.js", "type": "replace", "edit_start_line_idx": 35 }
/** * axios with a custom config. */ import axios from 'axios'; import { auth, wrapAxiosInstance } from '@strapi/helper-plugin'; const instance = axios.create({ baseURL: process.env.STRAPI_ADMIN_BACKEND_URL, }); instance.interceptors.request.use( async (config) => { config.headers = { Authorization: `Bearer ${auth.getToken()}`, Accept: 'application/json', 'Content-Type': 'application/json', }; return config; }, (error) => { Promise.reject(error); } ); instance.interceptors.response.use( (response) => response, (error) => { // whatever you want to do with the error if (error.response?.status === 401) { auth.clearAppStorage(); window.location.reload(); } throw error; } ); const wrapper = process.env.NODE_ENV === 'development' ? wrapAxiosInstance(instance) : instance; export default wrapper;
packages/generators/generators/lib/files/ts/plugin/admin/src/utils/axiosInstance.ts
1
https://github.com/strapi/strapi/commit/7a06c7e44491514fad57e553f17ebfaee00061e7
[ 0.9967870712280273, 0.20296482741832733, 0.0001668827171670273, 0.002804795978590846, 0.39694419503211975 ]
{ "id": 2, "code_window": [ "\n", " throw error;\n", " }\n", ");\n", "\n", "const wrapper = process.env.NODE_ENV === 'development' ? wrapAxiosInstance(instance) : instance;\n", "\n", "export default wrapper;" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ "const wrapper = wrapAxiosInstance(instance);\n" ], "file_path": "packages/core/email/admin/src/utils/axiosInstance.js", "type": "replace", "edit_start_line_idx": 35 }
'use strict'; const { GraphQLDate } = require('graphql-scalars'); const parseAndCast = (parseFn) => (...args) => { const parsedValue = parseFn(...args); if (parsedValue instanceof Date) { return parsedValue.toISOString().split('T')[0]; } return parsedValue; }; // GraphQLDate casts the date string to new Date, we want to keep it as a string so we cast it back to a string // see https://github.com/excitement-engineer/graphql-iso-date/issues/106 GraphQLDate.parseValue = parseAndCast(GraphQLDate.parseValue); GraphQLDate.parseLiteral = parseAndCast(GraphQLDate.parseLiteral); module.exports = GraphQLDate;
packages/plugins/graphql/server/services/internals/scalars/date.js
0
https://github.com/strapi/strapi/commit/7a06c7e44491514fad57e553f17ebfaee00061e7
[ 0.00017185871547553688, 0.00017026765272021294, 0.00016844013589434326, 0.00017050413589458913, 0.0000014056105328563717 ]
{ "id": 2, "code_window": [ "\n", " throw error;\n", " }\n", ");\n", "\n", "const wrapper = process.env.NODE_ENV === 'development' ? wrapAxiosInstance(instance) : instance;\n", "\n", "export default wrapper;" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ "const wrapper = wrapAxiosInstance(instance);\n" ], "file_path": "packages/core/email/admin/src/utils/axiosInstance.js", "type": "replace", "edit_start_line_idx": 35 }
'use strict'; const { getOr } = require('lodash/fp'); /** * Throws an ApolloError if context body contains a bad request * @param contextBody - body of the context object given to the resolver * @throws ApolloError if the body is a bad request */ function checkBadRequest(contextBody) { const statusCode = getOr(200, 'statusCode', contextBody); if (statusCode !== 200) { const errorMessage = getOr('Bad Request', 'error', contextBody); const exception = new Error(errorMessage); exception.code = statusCode || 400; exception.data = contextBody; throw exception; } } module.exports = { checkBadRequest, };
packages/plugins/users-permissions/server/graphql/utils.js
0
https://github.com/strapi/strapi/commit/7a06c7e44491514fad57e553f17ebfaee00061e7
[ 0.00016811986279208213, 0.00016651104670017958, 0.00016420375322923064, 0.00016720955318305641, 0.0000016733005168134696 ]
{ "id": 2, "code_window": [ "\n", " throw error;\n", " }\n", ");\n", "\n", "const wrapper = process.env.NODE_ENV === 'development' ? wrapAxiosInstance(instance) : instance;\n", "\n", "export default wrapper;" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ "const wrapper = wrapAxiosInstance(instance);\n" ], "file_path": "packages/core/email/admin/src/utils/axiosInstance.js", "type": "replace", "edit_start_line_idx": 35 }
'use strict'; const { list } = require('nexus'); const NOT_IN_FIELD_NAME = 'notIn'; module.exports = () => ({ fieldName: NOT_IN_FIELD_NAME, strapiOperator: '$notIn', add(t, type) { t.field(NOT_IN_FIELD_NAME, { type: list(type) }); }, });
packages/plugins/graphql/server/services/builders/filters/operators/not-in.js
0
https://github.com/strapi/strapi/commit/7a06c7e44491514fad57e553f17ebfaee00061e7
[ 0.0001705104805296287, 0.00016902151401154697, 0.00016753256204538047, 0.00016902151401154697, 0.0000014889592421241105 ]
{ "id": 3, "code_window": [ "function wrapAxiosInstance(instance) {\n", " const wrapper = {};\n", " ['request', 'get', 'head', 'delete', 'options', 'post', 'put', 'patch', 'getUri'].forEach(\n", " (methodName) => {\n", " wrapper[methodName] = (...args) => {\n" ], "labels": [ "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " if (process.env.NODE_ENV !== 'development') return instance;\n" ], "file_path": "packages/core/helper-plugin/lib/src/utils/wrapAxiosInstance/index.js", "type": "add", "edit_start_line_idx": 1 }
import axios from 'axios'; import { auth, wrapAxiosInstance } from '@strapi/helper-plugin'; const instance = axios.create({ baseURL: process.env.STRAPI_ADMIN_BACKEND_URL, }); instance.interceptors.request.use( async (config) => { config.headers = { Authorization: `Bearer ${auth.getToken()}`, Accept: 'application/json', 'Content-Type': 'application/json', }; return config; }, (error) => { Promise.reject(error); } ); instance.interceptors.response.use( (response) => response, (error) => { // whatever you want to do with the error if (error.response?.status === 401) { auth.clearAppStorage(); window.location.reload(); } throw error; } ); const wrapper = process.env.NODE_ENV === 'development' ? wrapAxiosInstance(instance) : instance; export default wrapper;
packages/core/email/admin/src/utils/axiosInstance.js
1
https://github.com/strapi/strapi/commit/7a06c7e44491514fad57e553f17ebfaee00061e7
[ 0.9987910389900208, 0.4994751811027527, 0.00017381655925419182, 0.4994679093360901, 0.49929794669151306 ]
{ "id": 3, "code_window": [ "function wrapAxiosInstance(instance) {\n", " const wrapper = {};\n", " ['request', 'get', 'head', 'delete', 'options', 'post', 'put', 'patch', 'getUri'].forEach(\n", " (methodName) => {\n", " wrapper[methodName] = (...args) => {\n" ], "labels": [ "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " if (process.env.NODE_ENV !== 'development') return instance;\n" ], "file_path": "packages/core/helper-plugin/lib/src/utils/wrapAxiosInstance/index.js", "type": "add", "edit_start_line_idx": 1 }
'use strict'; const documentation = require('./documentation'); module.exports = { documentation, };
packages/plugins/documentation/server/services/index.js
0
https://github.com/strapi/strapi/commit/7a06c7e44491514fad57e553f17ebfaee00061e7
[ 0.00017606896290089935, 0.00017606896290089935, 0.00017606896290089935, 0.00017606896290089935, 0 ]
{ "id": 3, "code_window": [ "function wrapAxiosInstance(instance) {\n", " const wrapper = {};\n", " ['request', 'get', 'head', 'delete', 'options', 'post', 'put', 'patch', 'getUri'].forEach(\n", " (methodName) => {\n", " wrapper[methodName] = (...args) => {\n" ], "labels": [ "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " if (process.env.NODE_ENV !== 'development') return instance;\n" ], "file_path": "packages/core/helper-plugin/lib/src/utils/wrapAxiosInstance/index.js", "type": "add", "edit_start_line_idx": 1 }
const action = require('../index'); jest.mock('@actions/github'); jest.mock('@actions/core'); const github = require('@actions/github'); const core = require('@actions/core'); test.each(action.BLOCKING_LABELS)('Test blocking labels %s', async (label) => { github.context = { payload: { pull_request: { labels: [{ name: label }], }, }, }; const setFailed = jest.spyOn(core, 'setFailed'); await action(); expect(setFailed).toHaveBeenCalled(); expect(setFailed.mock.calls[0][0]).toContain(`The PR has been labelled with a blocking label`); setFailed.mockRestore(); }); test('Test missing source label', async () => { github.context = { payload: { pull_request: { labels: [{ name: 'pr: enhancement' }], }, }, }; const setFailed = jest.spyOn(core, 'setFailed'); await action(); expect(setFailed).toHaveBeenCalled(); expect(setFailed.mock.calls[0][0]).toBe(`The PR must have one and only one 'source:' label.`); setFailed.mockRestore(); }); test('Test too many source label', async () => { github.context = { payload: { pull_request: { labels: [{ name: 'source: a' }, { name: 'source: b' }, { name: 'pr: enhancement' }], }, }, }; const setFailed = jest.spyOn(core, 'setFailed'); await action(); expect(setFailed).toHaveBeenCalled(); expect(setFailed.mock.calls[0][0]).toBe(`The PR must have one and only one 'source:' label.`); setFailed.mockRestore(); }); test('Test missing pr label', async () => { github.context = { payload: { pull_request: { labels: [{ name: 'source: core' }], }, }, }; const setFailed = jest.spyOn(core, 'setFailed'); await action(); expect(setFailed).toHaveBeenCalled(); expect(setFailed.mock.calls[0][0]).toBe(`The PR must have one and only one 'pr:' label.`); setFailed.mockRestore(); }); test('Test too many pr label', async () => { github.context = { payload: { pull_request: { labels: [{ name: 'pr: a' }, { name: 'pr: b' }, { name: 'source: core' }], }, }, }; const setFailed = jest.spyOn(core, 'setFailed'); await action(); expect(setFailed).toHaveBeenCalled(); expect(setFailed.mock.calls[0][0]).toBe(`The PR must have one and only one 'pr:' label.`); setFailed.mockRestore(); });
.github/actions/check-pr-status/__tests__/action.test.js
0
https://github.com/strapi/strapi/commit/7a06c7e44491514fad57e553f17ebfaee00061e7
[ 0.0001783546176739037, 0.00017507525626569986, 0.00017141357238870114, 0.0001753602409735322, 0.0000022140857254271396 ]
{ "id": 3, "code_window": [ "function wrapAxiosInstance(instance) {\n", " const wrapper = {};\n", " ['request', 'get', 'head', 'delete', 'options', 'post', 'put', 'patch', 'getUri'].forEach(\n", " (methodName) => {\n", " wrapper[methodName] = (...args) => {\n" ], "labels": [ "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " if (process.env.NODE_ENV !== 'development') return instance;\n" ], "file_path": "packages/core/helper-plugin/lib/src/utils/wrapAxiosInstance/index.js", "type": "add", "edit_start_line_idx": 1 }
'use strict'; module.exports = [ { method: 'GET', path: '/permissions', handler: 'permissions.getPermissions', }, { method: 'GET', path: '/policies', handler: 'permissions.getPolicies', }, { method: 'GET', path: '/routes', handler: 'permissions.getRoutes', }, ];
packages/plugins/users-permissions/server/routes/admin/permissions.js
0
https://github.com/strapi/strapi/commit/7a06c7e44491514fad57e553f17ebfaee00061e7
[ 0.00017473949992563576, 0.00017360640049446374, 0.00017302301421295851, 0.00017305667279288173, 8.013435035536531e-7 ]
{ "id": 4, "code_window": [ " }\n", ");\n", "\n", "const wrapper = process.env.NODE_ENV === 'development' ? wrapAxiosInstance(instance) : instance;\n", "\n", "export default wrapper;" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ "const wrapper = wrapAxiosInstance(instance);\n" ], "file_path": "packages/generators/generators/lib/files/js/plugin/admin/src/utils/axiosInstance.js", "type": "replace", "edit_start_line_idx": 39 }
import axios from 'axios'; import { auth, wrapAxiosInstance } from '@strapi/helper-plugin'; const instance = axios.create({ baseURL: process.env.STRAPI_ADMIN_BACKEND_URL, }); instance.interceptors.request.use( async (config) => { config.headers = { Authorization: `Bearer ${auth.getToken()}`, Accept: 'application/json', 'Content-Type': 'application/json', }; return config; }, (error) => { Promise.reject(error); } ); instance.interceptors.response.use( (response) => response, (error) => { // whatever you want to do with the error if (error.response?.status === 401) { auth.clearAppStorage(); window.location.reload(); } throw error; } ); const wrapper = process.env.NODE_ENV === 'development' ? wrapAxiosInstance(instance) : instance; export default wrapper;
packages/plugins/i18n/admin/src/utils/axiosInstance.js
1
https://github.com/strapi/strapi/commit/7a06c7e44491514fad57e553f17ebfaee00061e7
[ 0.9984117746353149, 0.25046834349632263, 0.00016778755525592715, 0.0016468940302729607, 0.43182700872421265 ]
{ "id": 4, "code_window": [ " }\n", ");\n", "\n", "const wrapper = process.env.NODE_ENV === 'development' ? wrapAxiosInstance(instance) : instance;\n", "\n", "export default wrapper;" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ "const wrapper = wrapAxiosInstance(instance);\n" ], "file_path": "packages/generators/generators/lib/files/js/plugin/admin/src/utils/axiosInstance.js", "type": "replace", "edit_start_line_idx": 39 }
'use strict'; const { createRequest } = require('./request'); const auth = { email: '[email protected]', firstname: 'admin', lastname: 'admin', password: 'Password123', }; const rq = createRequest(); const register = async () => { await rq({ url: '/admin/register-admin', method: 'POST', body: auth, }).catch((err) => { console.error(err); if (err.message === 'You cannot register a new super admin') return; throw err; }); }; const login = async () => { const { body } = await rq({ url: '/admin/login', method: 'POST', body: { email: auth.email, password: auth.password, }, }); return body.data; }; module.exports = { async registerAndLogin() { // register await register(); // login const res = await login(); return res && res.token; }, async login() { const res = await login(); return res && res.token; }, async getUser() { const res = await login(); return res.user; }, };
test/helpers/auth.js
0
https://github.com/strapi/strapi/commit/7a06c7e44491514fad57e553f17ebfaee00061e7
[ 0.0001743231259752065, 0.00016938115004450083, 0.00016610180318821222, 0.00016805485938675702, 0.000003062408040932496 ]
{ "id": 4, "code_window": [ " }\n", ");\n", "\n", "const wrapper = process.env.NODE_ENV === 'development' ? wrapAxiosInstance(instance) : instance;\n", "\n", "export default wrapper;" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ "const wrapper = wrapAxiosInstance(instance);\n" ], "file_path": "packages/generators/generators/lib/files/js/plugin/admin/src/utils/axiosInstance.js", "type": "replace", "edit_start_line_idx": 39 }
save-exact=true
.npmrc
0
https://github.com/strapi/strapi/commit/7a06c7e44491514fad57e553f17ebfaee00061e7
[ 0.00017731990374159068, 0.00017731990374159068, 0.00017731990374159068, 0.00017731990374159068, 0 ]
{ "id": 4, "code_window": [ " }\n", ");\n", "\n", "const wrapper = process.env.NODE_ENV === 'development' ? wrapAxiosInstance(instance) : instance;\n", "\n", "export default wrapper;" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ "const wrapper = wrapAxiosInstance(instance);\n" ], "file_path": "packages/generators/generators/lib/files/js/plugin/admin/src/utils/axiosInstance.js", "type": "replace", "edit_start_line_idx": 39 }
'use strict'; /** * Default db infos */ module.exports = { sqlite: { connection: { filename: '.tmp/data.db', }, useNullAsDefault: true, }, postgres: {}, mysql: {}, };
packages/generators/app/lib/utils/db-configs.js
0
https://github.com/strapi/strapi/commit/7a06c7e44491514fad57e553f17ebfaee00061e7
[ 0.0001720046129776165, 0.00016906388918869197, 0.0001661231799516827, 0.00016906388918869197, 0.000002940716512966901 ]
{ "id": 5, "code_window": [ " throw error;\n", " }\n", ");\n", "\n", "const wrapper = process.env.NODE_ENV === 'development' ? wrapAxiosInstance(instance) : instance;\n", "\n", "export default wrapper;" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ "const wrapper = wrapAxiosInstance(instance);\n" ], "file_path": "packages/generators/generators/lib/files/ts/plugin/admin/src/utils/axiosInstance.ts", "type": "replace", "edit_start_line_idx": 39 }
import axios from 'axios'; import { auth, wrapAxiosInstance } from '@strapi/helper-plugin'; const instance = axios.create({ baseURL: process.env.STRAPI_ADMIN_BACKEND_URL, }); instance.interceptors.request.use( async (config) => { config.headers = { Authorization: `Bearer ${auth.getToken()}`, Accept: 'application/json', 'Content-Type': 'application/json', }; return config; }, (error) => { Promise.reject(error); } ); instance.interceptors.response.use( (response) => response, (error) => { // whatever you want to do with the error if (error.response?.status === 401) { auth.clearAppStorage(); window.location.reload(); } throw error; } ); const wrapper = process.env.NODE_ENV === 'development' ? wrapAxiosInstance(instance) : instance; export default wrapper;
packages/plugins/i18n/admin/src/utils/axiosInstance.js
1
https://github.com/strapi/strapi/commit/7a06c7e44491514fad57e553f17ebfaee00061e7
[ 0.9984204769134521, 0.2508530914783478, 0.00016431481344625354, 0.002413816750049591, 0.4316094219684601 ]
{ "id": 5, "code_window": [ " throw error;\n", " }\n", ");\n", "\n", "const wrapper = process.env.NODE_ENV === 'development' ? wrapAxiosInstance(instance) : instance;\n", "\n", "export default wrapper;" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ "const wrapper = wrapAxiosInstance(instance);\n" ], "file_path": "packages/generators/generators/lib/files/ts/plugin/admin/src/utils/axiosInstance.ts", "type": "replace", "edit_start_line_idx": 39 }
import React from 'react'; import { Router, Route } from 'react-router-dom'; import { StrapiAppProvider, AppInfosContext, TrackingProvider } from '@strapi/helper-plugin'; import { render, screen, waitFor } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { createMemoryHistory } from 'history'; import { lightTheme, darkTheme } from '@strapi/design-system'; import Theme from '../../../components/Theme'; import ThemeToggleProvider from '../../../components/ThemeToggleProvider'; import { SettingsPage } from '..'; import { useSettingsMenu } from '../../../hooks'; jest.mock('../../../hooks', () => ({ useSettingsMenu: jest.fn(() => ({ isLoading: false, menu: [] })), useAppInfos: jest.fn(() => ({ shouldUpdateStrapi: false })), useThemeToggle: jest.fn(() => ({ currentTheme: 'light', themes: { light: lightTheme } })), })); jest.mock('@fortawesome/react-fontawesome', () => ({ FontAwesomeIcon: () => null, })); jest.mock('react-intl', () => ({ FormattedMessage: ({ id }) => id, useIntl: () => ({ formatMessage: jest.fn(({ id }) => id) }), })); jest.mock('../pages/ApplicationInfosPage', () => () => { return <h1>App infos</h1>; }); const appInfos = { shouldUpdateStrapi: false }; const makeApp = (history, settings) => ( <ThemeToggleProvider themes={{ light: lightTheme, dark: darkTheme }}> <TrackingProvider> <Theme> <AppInfosContext.Provider value={appInfos}> <StrapiAppProvider settings={settings} plugins={{}} getPlugin={jest.fn()} runHookParallel={jest.fn()} runHookWaterfall={jest.fn()} runHookSeries={jest.fn()} menu={[]} getFetchClient={jest.fn()} > <Router history={history}> <Route path="/settings/:settingId" component={SettingsPage} /> <Route path="/settings" component={SettingsPage} /> </Router> </StrapiAppProvider> </AppInfosContext.Provider> </Theme> </TrackingProvider> </ThemeToggleProvider> ); describe('ADMIN | pages | SettingsPage', () => { it('should not crash', () => { const history = createMemoryHistory(); const App = makeApp(history, { global: { id: 'global', intlLabel: { id: 'Settings.global', defaultMessage: 'Global Settings', }, links: [], }, }); const route = '/settings/application-infos'; history.push(route); const { container } = render(App); expect(container.firstChild).toMatchInlineSnapshot(` .c12 { padding-bottom: 56px; } .c0 { display: grid; grid-template-columns: auto 1fr; } .c13 { overflow-x: hidden; } .c2 { padding-top: 24px; padding-right: 16px; padding-bottom: 8px; padding-left: 24px; } .c5 { padding-top: 16px; } .c6 { background: #eaeaef; } .c9 { padding-top: 8px; padding-bottom: 16px; } .c1 { width: 14.5rem; background: #f6f6f9; position: -webkit-sticky; position: sticky; top: 0; height: 100vh; overflow-y: auto; border-right: 1px solid #dcdce4; z-index: 1; } .c3 { -webkit-align-items: flex-start; -webkit-box-align: flex-start; -ms-flex-align: flex-start; align-items: flex-start; display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-flex-direction: row; -ms-flex-direction: row; flex-direction: row; -webkit-box-pack: justify; -webkit-justify-content: space-between; -ms-flex-pack: justify; justify-content: space-between; } .c10 { -webkit-align-items: stretch; -webkit-box-align: stretch; -ms-flex-align: stretch; align-items: stretch; display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-flex-direction: column; -ms-flex-direction: column; flex-direction: column; } .c4 { color: #32324d; font-weight: 600; font-size: 1.125rem; line-height: 1.22; } .c7 { height: 1px; border: none; margin: 0; } .c8 { width: 1.5rem; background-color: #dcdce4; } .c11 > * { margin-top: 0; margin-bottom: 0; } .c11 > * + * { margin-top: 8px; } <div class="c0" > <nav aria-label="global.settings" class="c1" > <div class="c2" > <div class="c3" > <h2 class="c4" > global.settings </h2> </div> <div class="c5" > <hr class="c6 c7 c8" /> </div> </div> <div class="c9" > <ol class="c10 c11" spacing="2" /> </div> </nav> <div class="c12 c13" > <h1> App infos </h1> </div> </div> `); }); it('should redirect to the application-infos', async () => { const history = createMemoryHistory(); const App = makeApp(history, { global: { id: 'global', intlLabel: { id: 'Settings.global', defaultMessage: 'Global Settings', }, links: [], }, }); const route = '/settings'; history.push(route); render(App); await screen.findByText('App infos'); expect(screen.getByText(/App infos/)).toBeInTheDocument(); }); it('should create the plugins routes correctly', async () => { useSettingsMenu.mockImplementation(() => ({ isLoading: false, menu: [ { id: 'global', intlLabel: { defaultMessage: 'Global Settings', id: 'Settings.global', }, links: [ { id: 'internationalization', intlLabel: { id: 'i18n.plugin.name', defaultMessage: 'Internationalization' }, isDisplayed: true, permissions: [], to: '/settings/internationalization', Component: () => ({ default: () => <div>i18n settings</div> }), }, ], }, { id: 'email', intlLabel: { id: 'email.plugin', defaultMessage: 'email plugin' }, links: [ { id: 'email-settings', intlLabel: { id: 'email', defaultMessage: 'email' }, isDisplayed: true, permissions: [], to: '/settings/email-settings', Component: () => ({ default: () => <div>email settings</div> }), }, ], }, ], })); const history = createMemoryHistory(); const App = makeApp(history, { global: { id: 'global', intlLabel: { id: 'Settings.global', defaultMessage: 'Global Settings', }, links: [ { id: 'internationalization', intlLabel: { id: 'i18n.plugin.name', defaultMessage: 'Internationalization' }, isDisplayed: true, permissions: [], to: '/settings/internationalization', Component: () => ({ default: () => <div>i18n settings</div> }), }, ], }, email: { id: 'email', intlLabel: { id: 'email.plugin', defaultMessage: 'email plugin' }, links: [ { id: 'email-settings', intlLabel: { id: 'email', defaultMessage: 'email' }, isDisplayed: true, permissions: [], to: '/settings/email-settings', Component: () => ({ default: () => <div>email settings</div> }), }, ], }, }); const route = '/settings/application-infos'; const user = userEvent.setup(); history.push(route); render(App); expect(screen.getByText(/App infos/)).toBeInTheDocument(); await user.click(screen.getByText('i18n.plugin.name')); await waitFor(() => { expect(screen.getByText(/i18n settings/)).toBeInTheDocument(); }); await user.click(screen.getByText('email')); await waitFor(() => { expect(screen.getByText(/email settings/)).toBeInTheDocument(); }); }); });
packages/core/admin/admin/src/pages/SettingsPage/tests/index.test.js
0
https://github.com/strapi/strapi/commit/7a06c7e44491514fad57e553f17ebfaee00061e7
[ 0.0001759826991474256, 0.0001713113597361371, 0.0001649067271500826, 0.0001718746207188815, 0.0000024178500552807236 ]
{ "id": 5, "code_window": [ " throw error;\n", " }\n", ");\n", "\n", "const wrapper = process.env.NODE_ENV === 'development' ? wrapAxiosInstance(instance) : instance;\n", "\n", "export default wrapper;" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ "const wrapper = wrapAxiosInstance(instance);\n" ], "file_path": "packages/generators/generators/lib/files/ts/plugin/admin/src/utils/axiosInstance.ts", "type": "replace", "edit_start_line_idx": 39 }
'use strict'; const { has } = require('lodash/fp'); const pluginsRegistry = (strapi) => { const plugins = {}; return { get(name) { return plugins[name]; }, getAll() { return plugins; }, add(name, pluginConfig) { if (has(name, plugins)) { throw new Error(`Plugin ${name} has already been registered.`); } const pluginModule = strapi.container.get('modules').add(`plugin::${name}`, pluginConfig); plugins[name] = pluginModule; return plugins[name]; }, }; }; module.exports = pluginsRegistry;
packages/core/strapi/lib/core/registries/plugins.js
0
https://github.com/strapi/strapi/commit/7a06c7e44491514fad57e553f17ebfaee00061e7
[ 0.00017141243733931333, 0.00016795274859759957, 0.00016574472829233855, 0.00016670108016114682, 0.0000024773287350399187 ]
{ "id": 5, "code_window": [ " throw error;\n", " }\n", ");\n", "\n", "const wrapper = process.env.NODE_ENV === 'development' ? wrapAxiosInstance(instance) : instance;\n", "\n", "export default wrapper;" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ "const wrapper = wrapAxiosInstance(instance);\n" ], "file_path": "packages/generators/generators/lib/files/ts/plugin/admin/src/utils/axiosInstance.ts", "type": "replace", "edit_start_line_idx": 39 }
const layout = [ [ { intlLabel: { id: 'Auth.form.firstname.label', defaultMessage: 'First name', }, name: 'firstname', placeholder: { id: 'Auth.form.firstname.placeholder', defaultMessage: 'e.g. Kai', }, type: 'text', size: { col: 6, xs: 12, }, required: true, }, { intlLabel: { id: 'Auth.form.lastname.label', defaultMessage: 'Last name', }, name: 'lastname', placeholder: { id: 'Auth.form.lastname.placeholder', defaultMessage: 'e.g. Doe', }, type: 'text', size: { col: 6, xs: 12, }, }, ], [ { intlLabel: { id: 'Auth.form.email.label', defaultMessage: 'Email', }, name: 'email', placeholder: { id: 'Auth.form.email.placeholder', defaultMessage: 'e.g. [email protected]', }, type: 'email', size: { col: 6, xs: 12, }, required: true, }, { intlLabel: { id: 'Auth.form.username.label', defaultMessage: 'Username', }, name: 'username', placeholder: { id: 'Auth.form.username.placeholder', defaultMessage: 'e.g. Kai_Doe', }, type: 'text', size: { col: 6, xs: 12, }, }, ], [ { intlLabel: { id: 'global.password', defaultMessage: 'Password', }, name: 'password', type: 'password', size: { col: 6, xs: 12, }, autoComplete: 'new-password', }, { intlLabel: { id: 'Auth.form.confirmPassword.label', defaultMessage: 'Password confirmation', }, name: 'confirmPassword', type: 'password', size: { col: 6, xs: 12, }, autoComplete: 'new-password', }, ], [ { intlLabel: { id: 'Auth.form.active.label', defaultMessage: 'Active', }, name: 'isActive', type: 'bool', size: { col: 6, xs: 12, }, }, ], ]; export default layout;
packages/core/admin/admin/src/pages/SettingsPage/pages/Users/EditPage/utils/layout.js
0
https://github.com/strapi/strapi/commit/7a06c7e44491514fad57e553f17ebfaee00061e7
[ 0.00019645389693323523, 0.00017411571752745658, 0.00016851851250976324, 0.00017238236614502966, 0.000006909233889018651 ]
{ "id": 6, "code_window": [ " }\n", ");\n", "\n", "const wrapper = process.env.NODE_ENV === 'development' ? wrapAxiosInstance(instance) : instance;\n", "\n", "export default wrapper;" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ "const wrapper = wrapAxiosInstance(instance);\n" ], "file_path": "packages/plugins/i18n/admin/src/utils/axiosInstance.js", "type": "replace", "edit_start_line_idx": 35 }
/** * axios with a custom config. */ import axios from 'axios'; import { auth, wrapAxiosInstance } from '@strapi/helper-plugin'; const instance = axios.create({ baseURL: process.env.STRAPI_ADMIN_BACKEND_URL, }); instance.interceptors.request.use( async (config) => { config.headers = { Authorization: `Bearer ${auth.getToken()}`, Accept: 'application/json', 'Content-Type': 'application/json', }; return config; }, (error) => { Promise.reject(error); } ); instance.interceptors.response.use( (response) => response, (error) => { // whatever you want to do with the error if (error.response?.status === 401) { auth.clearAppStorage(); window.location.reload(); } throw error; } ); const wrapper = process.env.NODE_ENV === 'development' ? wrapAxiosInstance(instance) : instance; export default wrapper;
packages/generators/generators/lib/files/ts/plugin/admin/src/utils/axiosInstance.ts
1
https://github.com/strapi/strapi/commit/7a06c7e44491514fad57e553f17ebfaee00061e7
[ 0.9975337982177734, 0.38389232754707336, 0.000165554229170084, 0.002531839767470956, 0.469635933637619 ]
{ "id": 6, "code_window": [ " }\n", ");\n", "\n", "const wrapper = process.env.NODE_ENV === 'development' ? wrapAxiosInstance(instance) : instance;\n", "\n", "export default wrapper;" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ "const wrapper = wrapAxiosInstance(instance);\n" ], "file_path": "packages/plugins/i18n/admin/src/utils/axiosInstance.js", "type": "replace", "edit_start_line_idx": 35 }
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`BulkActions renders 1`] = ` .c12 { border: 0; -webkit-clip: rect(0 0 0 0); clip: rect(0 0 0 0); height: 1px; margin: -1px; overflow: hidden; padding: 0; position: absolute; width: 1px; } .c0 { padding-bottom: 20px; } .c1 { -webkit-align-items: center; -webkit-box-align: center; -ms-flex-align: center; align-items: center; display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-flex-direction: row; -ms-flex-direction: row; flex-direction: row; } .c2 > * { margin-left: 0; margin-right: 0; } .c2 > * + * { margin-left: 8px; } .c3 { color: #666687; font-size: 1rem; line-height: 1.5; } .c10 { font-weight: 600; color: #32324d; font-size: 0.75rem; line-height: 1.33; } .c7 { padding-right: 8px; } .c4 { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; cursor: pointer; padding: 8px; border-radius: 4px; background: #ffffff; border: 1px solid #dcdce4; position: relative; outline: none; } .c4 svg { height: 12px; width: 12px; } .c4 svg > g, .c4 svg path { fill: #ffffff; } .c4[aria-disabled='true'] { pointer-events: none; } .c4:after { -webkit-transition-property: all; transition-property: all; -webkit-transition-duration: 0.2s; transition-duration: 0.2s; border-radius: 8px; content: ''; position: absolute; top: -4px; bottom: -4px; left: -4px; right: -4px; border: 2px solid transparent; } .c4:focus-visible { outline: none; } .c4:focus-visible:after { border-radius: 8px; content: ''; position: absolute; top: -5px; bottom: -5px; left: -5px; right: -5px; border: 2px solid #4945ff; } .c8 { height: 100%; } .c5 { -webkit-align-items: center; -webkit-box-align: center; -ms-flex-align: center; align-items: center; padding: 8px 16px; background: #4945ff; border: 1px solid #4945ff; border: 1px solid #f5c0b8; background: #fcecea; } .c5 .c6 { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-align-items: center; -webkit-box-align: center; -ms-flex-align: center; align-items: center; } .c5 .c9 { color: #ffffff; } .c5[aria-disabled='true'] { border: 1px solid #dcdce4; background: #eaeaef; } .c5[aria-disabled='true'] .c9 { color: #666687; } .c5[aria-disabled='true'] svg > g, .c5[aria-disabled='true'] svg path { fill: #666687; } .c5[aria-disabled='true']:active { border: 1px solid #dcdce4; background: #eaeaef; } .c5[aria-disabled='true']:active .c9 { color: #666687; } .c5[aria-disabled='true']:active svg > g, .c5[aria-disabled='true']:active svg path { fill: #666687; } .c5:hover { background-color: #ffffff; } .c5:active { background-color: #ffffff; border: 1px solid #d02b20; } .c5:active .c9 { color: #d02b20; } .c5:active svg > g, .c5:active svg path { fill: #d02b20; } .c5 .c9 { color: #b72b1a; } .c5 svg > g, .c5 svg path { fill: #b72b1a; } .c11 { -webkit-align-items: center; -webkit-box-align: center; -ms-flex-align: center; align-items: center; padding: 8px 16px; background: #4945ff; border: 1px solid #4945ff; border: 1px solid #d9d8ff; background: #f0f0ff; } .c11 .c6 { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-align-items: center; -webkit-box-align: center; -ms-flex-align: center; align-items: center; } .c11 .c9 { color: #ffffff; } .c11[aria-disabled='true'] { border: 1px solid #dcdce4; background: #eaeaef; } .c11[aria-disabled='true'] .c9 { color: #666687; } .c11[aria-disabled='true'] svg > g, .c11[aria-disabled='true'] svg path { fill: #666687; } .c11[aria-disabled='true']:active { border: 1px solid #dcdce4; background: #eaeaef; } .c11[aria-disabled='true']:active .c9 { color: #666687; } .c11[aria-disabled='true']:active svg > g, .c11[aria-disabled='true']:active svg path { fill: #666687; } .c11:hover { background-color: #ffffff; } .c11:active { background-color: #ffffff; border: 1px solid #4945ff; } .c11:active .c9 { color: #4945ff; } .c11:active svg > g, .c11:active svg path { fill: #4945ff; } .c11 .c9 { color: #271fe0; } .c11 svg > g, .c11 svg path { fill: #271fe0; } <div> <div class="c0 c1 c2" spacing="2" > <span class="c3" > 0 folders - 0 assets selected </span> <button aria-disabled="false" class="c4 c5" type="button" > <div aria-hidden="true" class="c6 c7 c8" > <svg fill="none" height="1em" viewBox="0 0 24 24" width="1em" xmlns="http://www.w3.org/2000/svg" > <path d="M3.236 6.149a.2.2 0 00-.197.233L6 24h12l2.96-17.618a.2.2 0 00-.196-.233H3.236zM21.8 1.983c.11 0 .2.09.2.2v1.584a.2.2 0 01-.2.2H2.2a.2.2 0 01-.2-.2V2.183c0-.11.09-.2.2-.2h5.511c.9 0 1.631-1.09 1.631-1.983h5.316c0 .894.73 1.983 1.631 1.983H21.8z" fill="#32324D" /> </svg> </div> <span class="c9 c10" > Delete </span> </button> <button aria-disabled="false" class="c4 c11" type="button" > <div aria-hidden="true" class="c6 c7 c8" > <svg fill="none" height="1em" viewBox="0 0 24 24" width="1em" xmlns="http://www.w3.org/2000/svg" > <path d="M12.414 5H21a1 1 0 011 1v14a1 1 0 01-1 1H3a1 1 0 01-1-1V4a1 1 0 011-1h7.414l2 2z" fill="#212134" /> </svg> </div> <span class="c9 c10" > Move </span> </button> </div> <div class="c12" > <p aria-live="polite" aria-relevant="all" id="live-region-log" role="log" /> <p aria-live="polite" aria-relevant="all" id="live-region-status" role="status" /> <p aria-live="assertive" aria-relevant="all" id="live-region-alert" role="alert" /> </div> </div> `;
packages/core/upload/admin/src/pages/App/tests/__snapshots__/BulkActions.test.js.snap
0
https://github.com/strapi/strapi/commit/7a06c7e44491514fad57e553f17ebfaee00061e7
[ 0.00017891447350848466, 0.0001750458322931081, 0.00017086658044718206, 0.0001750932860886678, 0.0000017901372757478384 ]
{ "id": 6, "code_window": [ " }\n", ");\n", "\n", "const wrapper = process.env.NODE_ENV === 'development' ? wrapAxiosInstance(instance) : instance;\n", "\n", "export default wrapper;" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ "const wrapper = wrapAxiosInstance(instance);\n" ], "file_path": "packages/plugins/i18n/admin/src/utils/axiosInstance.js", "type": "replace", "edit_start_line_idx": 35 }
import React from 'react'; import PropTypes from 'prop-types'; import { Box } from '@strapi/design-system/Box'; import { Flex } from '@strapi/design-system/Flex'; import { PaginationURLQuery, PageSizeURLQuery } from '@strapi/helper-plugin'; const PaginationFooter = ({ pagination }) => { return ( <Box paddingTop={4}> <Flex alignItems="flex-end" justifyContent="space-between"> <PageSizeURLQuery trackedEvent="willChangeNumberOfEntriesPerPage" /> <PaginationURLQuery pagination={pagination} /> </Flex> </Box> ); }; PaginationFooter.defaultProps = { pagination: { pageCount: 0, pageSize: 10, total: 0, }, }; PaginationFooter.propTypes = { pagination: PropTypes.shape({ page: PropTypes.number, pageCount: PropTypes.number, pageSize: PropTypes.number, total: PropTypes.number, }), }; export default PaginationFooter;
packages/core/admin/admin/src/content-manager/pages/ListView/PaginationFooter/index.js
0
https://github.com/strapi/strapi/commit/7a06c7e44491514fad57e553f17ebfaee00061e7
[ 0.00017438680515624583, 0.0001715616963338107, 0.00016844962374307215, 0.00017170517821796238, 0.000002104563691318617 ]
{ "id": 6, "code_window": [ " }\n", ");\n", "\n", "const wrapper = process.env.NODE_ENV === 'development' ? wrapAxiosInstance(instance) : instance;\n", "\n", "export default wrapper;" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ "const wrapper = wrapAxiosInstance(instance);\n" ], "file_path": "packages/plugins/i18n/admin/src/utils/axiosInstance.js", "type": "replace", "edit_start_line_idx": 35 }
import React from 'react'; import { fireEvent, render, screen } from '@testing-library/react'; import { ThemeProvider, lightTheme } from '@strapi/design-system'; import { IntlProvider } from 'react-intl'; import { DynamicZone } from '../index'; import { layoutData } from './fixtures'; jest.mock('@fortawesome/react-fontawesome', () => ({ FontAwesomeIcon: () => null, })); const toggleNotification = jest.fn(); jest.mock('@strapi/helper-plugin', () => ({ ...jest.requireActual('@strapi/helper-plugin'), useCMEditViewDataManager: jest.fn().mockImplementation(() => ({ modifiedData: {} })), useNotification: jest.fn().mockImplementation(() => toggleNotification), NotAllowedInput: () => 'This field is not allowed', })); jest.mock('../../../hooks', () => ({ useContentTypeLayout: jest.fn().mockReturnValue({ getComponentLayout: jest.fn().mockImplementation((componentUid) => layoutData[componentUid]), }), })); /** * We _could_ unmock this and use it, but it requires more * harnessing then is necessary and it's not worth it for these * tests when really we're focussing on dynamic zone behaviour. */ jest.mock('../../FieldComponent', () => () => "I'm a field component"); describe('DynamicZone', () => { afterEach(() => { jest.restoreAllMocks(); }); const defaultProps = { addComponentToDynamicZone: jest.fn(), isCreatingEntry: true, isFieldAllowed: true, isFieldReadable: true, fieldSchema: { components: ['component1', 'component2', 'component3'], }, formErrors: {}, metadatas: { label: 'dynamic zone', description: 'dynamic description', }, moveComponentDown: jest.fn(), moveComponentUp: jest.fn(), name: 'DynamicZoneComponent', removeComponentFromDynamicZone: jest.fn(), }; const TestComponent = (props) => ( <ThemeProvider theme={lightTheme}> <IntlProvider locale="en" messages={{}} defaultLocale="en"> <DynamicZone {...defaultProps} {...props} /> </IntlProvider> </ThemeProvider> ); const setup = (props) => render(<TestComponent {...props} />); describe('rendering', () => { it('should not render the dynamic zone if there are no dynamic components to render', () => { setup(); expect(screen.queryByText('dynamic zone')).not.toBeInTheDocument(); expect(screen.queryByText('dynamic description')).not.toBeInTheDocument(); }); it('should render the AddComponentButton by default and render the ComponentPicker when that button is clicked', () => { setup(); const addComponentButton = screen.getByRole('button', { name: /Add a component to/i }); expect(addComponentButton).toBeInTheDocument(); fireEvent.click(addComponentButton); expect(screen.getByText('Pick one component')).toBeInTheDocument(); }); it('should render the dynamic zone of components when there are dynamic components to render', () => { setup({ dynamicDisplayedComponents: ['component1', 'component2'], }); expect(screen.getByText('dynamic zone')).toBeInTheDocument(); expect(screen.getByText('dynamic description')).toBeInTheDocument(); expect(screen.getByText('component1')).toBeInTheDocument(); expect(screen.getByText('component2')).toBeInTheDocument(); }); it('should render the not allowed input if the field is not allowed & the entry is being created', () => { setup({ isFieldAllowed: false, isCreatingEntry: true, }); expect(screen.queryByText('dynamic zone')).not.toBeInTheDocument(); expect(screen.getByText('This field is not allowed')).toBeInTheDocument(); }); it('should render the not allowed input if the field is not allowed & the entry is not being created and the field is not readable', () => { setup({ isFieldAllowed: false, isCreatingEntry: false, isFieldReadable: false, }); expect(screen.queryByText('dynamic zone')).not.toBeInTheDocument(); expect(screen.getByText('This field is not allowed')).toBeInTheDocument(); }); }); describe('callbacks', () => { it('should call the addComponentToDynamicZone callback when the AddComponentButton is clicked', () => { const addComponentToDynamicZone = jest.fn(); setup({ addComponentToDynamicZone }); const addComponentButton = screen.getByRole('button', { name: /Add a component to/i }); fireEvent.click(addComponentButton); const componentPickerButton = screen.getByRole('button', { name: /component1/i, }); fireEvent.click(componentPickerButton); expect(addComponentToDynamicZone).toHaveBeenCalledWith( 'DynamicZoneComponent', { category: 'myComponents', info: { displayName: 'component1', icon: undefined } }, undefined, false ); }); it('should call the moveComponentDown callback when the MoveDownButton is clicked', () => { const moveComponentDown = jest.fn(); setup({ moveComponentDown, dynamicDisplayedComponents: ['component1', 'component2'], }); const moveDownButton = screen.getByRole('button', { name: /Move component down/i }); fireEvent.click(moveDownButton); expect(moveComponentDown).toHaveBeenCalledWith('DynamicZoneComponent', 0); }); it('should call the moveComponentUp callback when the MoveUpButton is clicked', () => { const moveComponentUp = jest.fn(); setup({ moveComponentUp, dynamicDisplayedComponents: ['component1', 'component2'], }); const moveUpButton = screen.getByRole('button', { name: /Move component up/i }); fireEvent.click(moveUpButton); expect(moveComponentUp).toHaveBeenCalledWith('DynamicZoneComponent', 1); }); it('should call the removeComponentFromDynamicZone callback when the RemoveButton is clicked', () => { const removeComponentFromDynamicZone = jest.fn(); setup({ removeComponentFromDynamicZone, dynamicDisplayedComponents: ['component1', 'component2'], }); const removeButton = screen.getByRole('button', { name: /Delete component1/i }); fireEvent.click(removeButton); expect(removeComponentFromDynamicZone).toHaveBeenCalledWith('DynamicZoneComponent', 0); }); }); describe('side effects', () => { it('should call the toggleNotification callback if the amount of dynamic components has hit its max and the user tries to add another', () => { setup({ dynamicDisplayedComponents: ['component1', 'component2', 'component3'], fieldSchema: { components: ['component1', 'component2', 'component3'], max: 3, }, }); const addComponentButton = screen.getByRole('button', { name: /Add a component to/i }); fireEvent.click(addComponentButton); expect(toggleNotification).toHaveBeenCalledWith({ type: 'info', message: { id: 'content-manager.components.notification.info.maximum-requirement', }, }); }); }); });
packages/core/admin/admin/src/content-manager/components/DynamicZone/tests/index.test.js
0
https://github.com/strapi/strapi/commit/7a06c7e44491514fad57e553f17ebfaee00061e7
[ 0.00017417740309610963, 0.0001710041833575815, 0.00016165179840754718, 0.0001718158891890198, 0.000003007389750564471 ]
{ "id": 7, "code_window": [ "\n", " throw error;\n", " }\n", ");\n", "\n", "const wrapper = process.env.NODE_ENV === 'development' ? wrapAxiosInstance(instance) : instance;\n", "\n", "export default wrapper;" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ "const wrapper = wrapAxiosInstance(instance);\n" ], "file_path": "packages/plugins/users-permissions/admin/src/utils/axiosInstance.js", "type": "replace", "edit_start_line_idx": 35 }
function wrapAxiosInstance(instance) { const wrapper = {}; ['request', 'get', 'head', 'delete', 'options', 'post', 'put', 'patch', 'getUri'].forEach( (methodName) => { wrapper[methodName] = (...args) => { console.log( 'Deprecation warning: Usage of "axiosInstance" utility is deprecated and will be removed in the next major release. Instead, use the useFetchClient() hook, which is exported from the helper-plugin: { useFetchClient } from "@strapi/helper-plugin"' ); return instance[methodName](...args); }; } ); return wrapper; } export default wrapAxiosInstance;
packages/core/helper-plugin/lib/src/utils/wrapAxiosInstance/index.js
1
https://github.com/strapi/strapi/commit/7a06c7e44491514fad57e553f17ebfaee00061e7
[ 0.9977097511291504, 0.5082932710647583, 0.018876759335398674, 0.5082932710647583, 0.4894165098667145 ]
{ "id": 7, "code_window": [ "\n", " throw error;\n", " }\n", ");\n", "\n", "const wrapper = process.env.NODE_ENV === 'development' ? wrapAxiosInstance(instance) : instance;\n", "\n", "export default wrapper;" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ "const wrapper = wrapAxiosInstance(instance);\n" ], "file_path": "packages/plugins/users-permissions/admin/src/utils/axiosInstance.js", "type": "replace", "edit_start_line_idx": 35 }
/** * * Tests for PageSizeURLQuery * */ import React from 'react'; import { render } from '@testing-library/react'; import { IntlProvider } from 'react-intl'; import { Router } from 'react-router-dom'; import { createMemoryHistory } from 'history'; import { ThemeProvider, lightTheme } from '@strapi/design-system'; import PageSizeURLQuery from '../index'; jest.mock('../../../hooks/useTracking', () => () => ({ trackUsage: jest.fn(), })); const messages = { 'components.PageFooter.select': 'Entries per page', }; const makeApp = (history) => ( <Router history={history}> <ThemeProvider theme={lightTheme}> <IntlProvider locale="en" messages={messages} textComponent="span"> <PageSizeURLQuery /> </IntlProvider> </ThemeProvider> </Router> ); describe('<PageSizeURLQuery />', () => { it('renders and matches the snapshot', () => { const history = createMemoryHistory(); const { container: { firstChild }, getByText, } = render(makeApp(history)); expect(firstChild).toMatchInlineSnapshot(` .c13 { padding-left: 8px; } .c0 { -webkit-align-items: center; -webkit-box-align: center; -ms-flex-align: center; align-items: center; display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-flex-direction: row; -ms-flex-direction: row; flex-direction: row; } .c5 { position: absolute; left: 0; right: 0; bottom: 0; top: 0; width: 100%; background: transparent; border: none; } .c5:focus { outline: none; } .c5[aria-disabled='true'] { cursor: not-allowed; } .c8 { padding-right: 16px; padding-left: 16px; } .c10 { padding-left: 12px; } .c1 { -webkit-align-items: stretch; -webkit-box-align: stretch; -ms-flex-align: stretch; align-items: stretch; display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-flex-direction: column; -ms-flex-direction: column; flex-direction: column; } .c3 { -webkit-align-items: center; -webkit-box-align: center; -ms-flex-align: center; align-items: center; display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-flex-direction: row; -ms-flex-direction: row; flex-direction: row; } .c6 { -webkit-align-items: center; -webkit-box-align: center; -ms-flex-align: center; align-items: center; display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-flex-direction: row; -ms-flex-direction: row; flex-direction: row; -webkit-box-pack: justify; -webkit-justify-content: space-between; -ms-flex-pack: justify; justify-content: space-between; } .c9 { color: #32324d; display: block; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; font-size: 0.875rem; line-height: 1.43; } .c2 > * { margin-top: 0; margin-bottom: 0; } .c4 { position: relative; border: 1px solid #dcdce4; padding-right: 12px; border-radius: 4px; background: #ffffff; overflow: hidden; min-height: 2rem; outline: none; box-shadow: 0; -webkit-transition-property: border-color,box-shadow,fill; transition-property: border-color,box-shadow,fill; -webkit-transition-duration: 0.2s; transition-duration: 0.2s; } .c4:focus-within { border: 1px solid #4945ff; box-shadow: #4945ff 0px 0px 0px 2px; } .c11 { background: transparent; border: none; position: relative; z-index: 1; } .c11 svg { height: 0.6875rem; width: 0.6875rem; } .c11 svg path { fill: #666687; } .c12 { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; background: none; border: none; } .c12 svg { width: 0.375rem; } .c7 { width: 100%; } .c14 { color: #666687; font-size: 0.875rem; line-height: 1.43; } <div class="c0" > <div> <div class="c1 c2" > <div class="c3 c4" > <button aria-disabled="false" aria-expanded="false" aria-haspopup="listbox" aria-label="Entries per page" aria-labelledby="select-1-label select-1-content" class="c5" id="select-1" type="button" /> <div class="c6 c7" > <div class="c3" > <div class="c8" > <span class="c9" id="select-1-content" > 10 </span> </div> </div> <div class="c3" > <button aria-hidden="true" class="c10 c11 c12" tabindex="-1" type="button" > <svg fill="none" height="1em" viewBox="0 0 14 8" width="1em" xmlns="http://www.w3.org/2000/svg" > <path clip-rule="evenodd" d="M14 .889a.86.86 0 01-.26.625L7.615 7.736A.834.834 0 017 8a.834.834 0 01-.615-.264L.26 1.514A.861.861 0 010 .889c0-.24.087-.45.26-.625A.834.834 0 01.875 0h12.25c.237 0 .442.088.615.264a.86.86 0 01.26.625z" fill="#32324D" fill-rule="evenodd" /> </svg> </button> </div> </div> </div> </div> </div> <div class="c13" > <label class="c14" for="page-size" > Entries per page </label> </div> </div> `); expect(getByText('10')).toBeInTheDocument(); }); it('should display the pageSize correctly', () => { const history = createMemoryHistory(); history.push({ search: 'pageSize=50' }); const { getByText } = render(makeApp(history)); expect(getByText('50')).toBeInTheDocument(); }); });
packages/core/helper-plugin/lib/src/components/PageSizeURLQuery/tests/index.test.js
0
https://github.com/strapi/strapi/commit/7a06c7e44491514fad57e553f17ebfaee00061e7
[ 0.00017641681188251823, 0.000171365900314413, 0.00016482482897117734, 0.00017200675210915506, 0.000003055158003917313 ]
{ "id": 7, "code_window": [ "\n", " throw error;\n", " }\n", ");\n", "\n", "const wrapper = process.env.NODE_ENV === 'development' ? wrapAxiosInstance(instance) : instance;\n", "\n", "export default wrapper;" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ "const wrapper = wrapAxiosInstance(instance);\n" ], "file_path": "packages/plugins/users-permissions/admin/src/utils/axiosInstance.js", "type": "replace", "edit_start_line_idx": 35 }
import myService from './my-service'; export default { myService, };
packages/generators/generators/lib/files/ts/plugin/server/services/index.ts
0
https://github.com/strapi/strapi/commit/7a06c7e44491514fad57e553f17ebfaee00061e7
[ 0.0001842123019741848, 0.0001842123019741848, 0.0001842123019741848, 0.0001842123019741848, 0 ]
{ "id": 7, "code_window": [ "\n", " throw error;\n", " }\n", ");\n", "\n", "const wrapper = process.env.NODE_ENV === 'development' ? wrapAxiosInstance(instance) : instance;\n", "\n", "export default wrapper;" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ "const wrapper = wrapAxiosInstance(instance);\n" ], "file_path": "packages/plugins/users-permissions/admin/src/utils/axiosInstance.js", "type": "replace", "edit_start_line_idx": 35 }
'use strict'; const { getService } = require('./utils'); module.exports = async () => { const { conditionProvider, actionProvider } = getService('permission'); await conditionProvider.clear(); await actionProvider.clear(); };
packages/core/admin/server/destroy.js
0
https://github.com/strapi/strapi/commit/7a06c7e44491514fad57e553f17ebfaee00061e7
[ 0.0001764166372595355, 0.00017384852981194854, 0.00017128042236436158, 0.00017384852981194854, 0.0000025681074475869536 ]
{ "id": 0, "code_window": [ "\tmetrics[\"stats.library_variables.count\"] = statsQuery.Result.LibraryVariables\n", "\tmetrics[\"stats.dashboards_viewers_can_edit.count\"] = statsQuery.Result.DashboardsViewersCanEdit\n", "\tmetrics[\"stats.dashboards_viewers_can_admin.count\"] = statsQuery.Result.DashboardsViewersCanAdmin\n", "\tmetrics[\"stats.folders_viewers_can_edit.count\"] = statsQuery.Result.FoldersViewersCanEdit\n", "\tmetrics[\"stats.folders_viewers_can_admin.count\"] = statsQuery.Result.FoldersViewersCanAdmin\n", "\n", "\tossEditionCount := 1\n", "\tenterpriseEditionCount := 0\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\tmetrics[\"stats.api_keys.count\"] = statsQuery.Result.APIKeys\n" ], "file_path": "pkg/infra/usagestats/service/usage_stats.go", "type": "add", "edit_start_line_idx": 86 }
package service import ( "bytes" "context" "errors" "io/ioutil" "net/http" "net/http/httptest" "runtime" "testing" "time" "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/components/simplejson" "github.com/grafana/grafana/pkg/infra/kvstore" "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/infra/usagestats" "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/plugins" "github.com/grafana/grafana/pkg/services/sqlstore" "github.com/grafana/grafana/pkg/setting" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) // This is to ensure that the interface contract is held by the implementation func Test_InterfaceContractValidity(t *testing.T) { newUsageStats := func() usagestats.Service { return &UsageStats{} } v, ok := newUsageStats().(*UsageStats) assert.NotNil(t, v) assert.True(t, ok) } func TestMetrics(t *testing.T) { t.Run("When sending usage stats", func(t *testing.T) { uss := createService(t, setting.Cfg{}) setupSomeDataSourcePlugins(t, uss) var getSystemStatsQuery *models.GetSystemStatsQuery uss.Bus.AddHandlerCtx(func(ctx context.Context, query *models.GetSystemStatsQuery) error { query.Result = &models.SystemStats{ Dashboards: 1, Datasources: 2, Users: 3, Admins: 31, Editors: 32, Viewers: 33, ActiveUsers: 4, ActiveAdmins: 21, ActiveEditors: 22, ActiveViewers: 23, ActiveSessions: 24, DailyActiveUsers: 25, DailyActiveAdmins: 26, DailyActiveEditors: 27, DailyActiveViewers: 28, DailyActiveSessions: 29, Orgs: 5, Playlists: 6, Alerts: 7, Stars: 8, Folders: 9, DashboardPermissions: 10, FolderPermissions: 11, ProvisionedDashboards: 12, Snapshots: 13, Teams: 14, AuthTokens: 15, DashboardVersions: 16, Annotations: 17, AlertRules: 18, LibraryPanels: 19, LibraryVariables: 20, DashboardsViewersCanAdmin: 3, DashboardsViewersCanEdit: 2, FoldersViewersCanAdmin: 1, FoldersViewersCanEdit: 5, } getSystemStatsQuery = query return nil }) var getDataSourceStatsQuery *models.GetDataSourceStatsQuery uss.Bus.AddHandlerCtx(func(ctx context.Context, query *models.GetDataSourceStatsQuery) error { query.Result = []*models.DataSourceStats{ { Type: models.DS_ES, Count: 9, }, { Type: models.DS_PROMETHEUS, Count: 10, }, { Type: "unknown_ds", Count: 11, }, { Type: "unknown_ds2", Count: 12, }, } getDataSourceStatsQuery = query return nil }) var getESDatasSourcesQuery *models.GetDataSourcesByTypeQuery uss.Bus.AddHandlerCtx(func(ctx context.Context, query *models.GetDataSourcesByTypeQuery) error { query.Result = []*models.DataSource{ { JsonData: simplejson.NewFromAny(map[string]interface{}{ "esVersion": 2, }), }, { JsonData: simplejson.NewFromAny(map[string]interface{}{ "esVersion": 2, }), }, { JsonData: simplejson.NewFromAny(map[string]interface{}{ "esVersion": 70, }), }, } getESDatasSourcesQuery = query return nil }) var getDataSourceAccessStatsQuery *models.GetDataSourceAccessStatsQuery uss.Bus.AddHandlerCtx(func(ctx context.Context, query *models.GetDataSourceAccessStatsQuery) error { query.Result = []*models.DataSourceAccessStats{ { Type: models.DS_ES, Access: "direct", Count: 1, }, { Type: models.DS_ES, Access: "proxy", Count: 2, }, { Type: models.DS_PROMETHEUS, Access: "proxy", Count: 3, }, { Type: "unknown_ds", Access: "proxy", Count: 4, }, { Type: "unknown_ds2", Access: "", Count: 5, }, { Type: "unknown_ds3", Access: "direct", Count: 6, }, { Type: "unknown_ds4", Access: "direct", Count: 7, }, { Type: "unknown_ds5", Access: "proxy", Count: 8, }, } getDataSourceAccessStatsQuery = query return nil }) var getAlertNotifierUsageStatsQuery *models.GetAlertNotifierUsageStatsQuery uss.Bus.AddHandlerCtx(func(ctx context.Context, query *models.GetAlertNotifierUsageStatsQuery) error { query.Result = []*models.NotifierUsageStats{ { Type: "slack", Count: 1, }, { Type: "webhook", Count: 2, }, } getAlertNotifierUsageStatsQuery = query return nil }) createConcurrentTokens(t, uss.SQLStore) uss.oauthProviders = map[string]bool{ "github": true, "gitlab": true, "azuread": true, "google": true, "generic_oauth": true, "grafana_com": true, } err := uss.sendUsageStats(context.Background()) require.NoError(t, err) t.Run("Given reporting not enabled and sending usage stats", func(t *testing.T) { origSendUsageStats := sendUsageStats t.Cleanup(func() { sendUsageStats = origSendUsageStats }) statsSent := false sendUsageStats = func(uss *UsageStats, b *bytes.Buffer) { statsSent = true } uss.Cfg.ReportingEnabled = false err := uss.sendUsageStats(context.Background()) require.NoError(t, err) require.False(t, statsSent) assert.Nil(t, getSystemStatsQuery) assert.Nil(t, getDataSourceStatsQuery) assert.Nil(t, getDataSourceAccessStatsQuery) assert.Nil(t, getESDatasSourcesQuery) }) t.Run("Given reporting enabled, stats should be gathered and sent to HTTP endpoint", func(t *testing.T) { origCfg := uss.Cfg t.Cleanup(func() { uss.Cfg = origCfg }) uss.Cfg = &setting.Cfg{ ReportingEnabled: true, BuildVersion: "5.0.0", AnonymousEnabled: true, BasicAuthEnabled: true, LDAPEnabled: true, AuthProxyEnabled: true, Packaging: "deb", ReportingDistributor: "hosted-grafana", } ch := make(chan httpResp) ticker := time.NewTicker(2 * time.Second) ts := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { buf, err := ioutil.ReadAll(r.Body) if err != nil { t.Logf("Fake HTTP handler received an error: %s", err.Error()) ch <- httpResp{ err: err, } return } require.NoError(t, err, "Failed to read response body, err=%v", err) t.Logf("Fake HTTP handler received a response") ch <- httpResp{ responseBuffer: bytes.NewBuffer(buf), req: r, } })) t.Cleanup(ts.Close) t.Cleanup(func() { close(ch) }) usageStatsURL = ts.URL err := uss.sendUsageStats(context.Background()) require.NoError(t, err) // Wait for fake HTTP server to receive a request var resp httpResp select { case resp = <-ch: require.NoError(t, resp.err, "Fake server experienced an error") case <-ticker.C: t.Fatalf("Timed out waiting for HTTP request") } t.Logf("Received response from fake HTTP server: %+v\n", resp) assert.NotNil(t, getSystemStatsQuery) assert.NotNil(t, getDataSourceStatsQuery) assert.NotNil(t, getESDatasSourcesQuery) assert.NotNil(t, getDataSourceAccessStatsQuery) assert.NotNil(t, getAlertNotifierUsageStatsQuery) assert.NotNil(t, resp.req) assert.Equal(t, http.MethodPost, resp.req.Method) assert.Equal(t, "application/json", resp.req.Header.Get("Content-Type")) require.NotNil(t, resp.responseBuffer) j, err := simplejson.NewFromReader(resp.responseBuffer) require.NoError(t, err) assert.Equal(t, "5_0_0", j.Get("version").MustString()) assert.Equal(t, runtime.GOOS, j.Get("os").MustString()) assert.Equal(t, runtime.GOARCH, j.Get("arch").MustString()) usageId := uss.GetUsageStatsId(context.Background()) assert.NotEmpty(t, usageId) assert.Equal(t, usageId, j.Get("usageStatsId").MustString()) metrics := j.Get("metrics") assert.Equal(t, getSystemStatsQuery.Result.Dashboards, metrics.Get("stats.dashboards.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.Users, metrics.Get("stats.users.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.Admins, metrics.Get("stats.admins.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.Editors, metrics.Get("stats.editors.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.Viewers, metrics.Get("stats.viewers.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.Orgs, metrics.Get("stats.orgs.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.Playlists, metrics.Get("stats.playlist.count").MustInt64()) assert.Equal(t, uss.appCount(context.Background()), metrics.Get("stats.plugins.apps.count").MustInt()) assert.Equal(t, uss.panelCount(context.Background()), metrics.Get("stats.plugins.panels.count").MustInt()) assert.Equal(t, uss.dataSourceCount(context.Background()), metrics.Get("stats.plugins.datasources.count").MustInt()) assert.Equal(t, getSystemStatsQuery.Result.Alerts, metrics.Get("stats.alerts.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.ActiveUsers, metrics.Get("stats.active_users.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.ActiveAdmins, metrics.Get("stats.active_admins.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.ActiveEditors, metrics.Get("stats.active_editors.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.ActiveViewers, metrics.Get("stats.active_viewers.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.ActiveSessions, metrics.Get("stats.active_sessions.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.DailyActiveUsers, metrics.Get("stats.daily_active_users.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.DailyActiveAdmins, metrics.Get("stats.daily_active_admins.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.DailyActiveEditors, metrics.Get("stats.daily_active_editors.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.DailyActiveViewers, metrics.Get("stats.daily_active_viewers.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.DailyActiveSessions, metrics.Get("stats.daily_active_sessions.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.Datasources, metrics.Get("stats.datasources.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.Stars, metrics.Get("stats.stars.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.Folders, metrics.Get("stats.folders.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.DashboardPermissions, metrics.Get("stats.dashboard_permissions.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.FolderPermissions, metrics.Get("stats.folder_permissions.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.ProvisionedDashboards, metrics.Get("stats.provisioned_dashboards.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.Snapshots, metrics.Get("stats.snapshots.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.Teams, metrics.Get("stats.teams.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.DashboardsViewersCanEdit, metrics.Get("stats.dashboards_viewers_can_edit.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.DashboardsViewersCanAdmin, metrics.Get("stats.dashboards_viewers_can_admin.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.FoldersViewersCanEdit, metrics.Get("stats.folders_viewers_can_edit.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.FoldersViewersCanAdmin, metrics.Get("stats.folders_viewers_can_admin.count").MustInt64()) assert.Equal(t, 15, metrics.Get("stats.total_auth_token.count").MustInt()) assert.Equal(t, 5, metrics.Get("stats.avg_auth_token_per_user.count").MustInt()) assert.Equal(t, 16, metrics.Get("stats.dashboard_versions.count").MustInt()) assert.Equal(t, 17, metrics.Get("stats.annotations.count").MustInt()) assert.Equal(t, 18, metrics.Get("stats.alert_rules.count").MustInt()) assert.Equal(t, 19, metrics.Get("stats.library_panels.count").MustInt()) assert.Equal(t, 20, metrics.Get("stats.library_variables.count").MustInt()) assert.Equal(t, 0, metrics.Get("stats.live_users.count").MustInt()) assert.Equal(t, 0, metrics.Get("stats.live_clients.count").MustInt()) assert.Equal(t, 9, metrics.Get("stats.ds."+models.DS_ES+".count").MustInt()) assert.Equal(t, 10, metrics.Get("stats.ds."+models.DS_PROMETHEUS+".count").MustInt()) assert.Equal(t, 2, metrics.Get("stats.ds."+models.DS_ES+".v2.count").MustInt()) assert.Equal(t, 1, metrics.Get("stats.ds."+models.DS_ES+".v70.count").MustInt()) assert.Equal(t, 11+12, metrics.Get("stats.ds.other.count").MustInt()) assert.Equal(t, 1, metrics.Get("stats.ds_access."+models.DS_ES+".direct.count").MustInt()) assert.Equal(t, 2, metrics.Get("stats.ds_access."+models.DS_ES+".proxy.count").MustInt()) assert.Equal(t, 3, metrics.Get("stats.ds_access."+models.DS_PROMETHEUS+".proxy.count").MustInt()) assert.Equal(t, 6+7, metrics.Get("stats.ds_access.other.direct.count").MustInt()) assert.Equal(t, 4+8, metrics.Get("stats.ds_access.other.proxy.count").MustInt()) assert.Equal(t, 1, metrics.Get("stats.alert_notifiers.slack.count").MustInt()) assert.Equal(t, 2, metrics.Get("stats.alert_notifiers.webhook.count").MustInt()) assert.Equal(t, 1, metrics.Get("stats.auth_enabled.anonymous.count").MustInt()) assert.Equal(t, 1, metrics.Get("stats.auth_enabled.basic_auth.count").MustInt()) assert.Equal(t, 1, metrics.Get("stats.auth_enabled.ldap.count").MustInt()) assert.Equal(t, 1, metrics.Get("stats.auth_enabled.auth_proxy.count").MustInt()) assert.Equal(t, 1, metrics.Get("stats.auth_enabled.oauth_github.count").MustInt()) assert.Equal(t, 1, metrics.Get("stats.auth_enabled.oauth_gitlab.count").MustInt()) assert.Equal(t, 1, metrics.Get("stats.auth_enabled.oauth_google.count").MustInt()) assert.Equal(t, 1, metrics.Get("stats.auth_enabled.oauth_azuread.count").MustInt()) assert.Equal(t, 1, metrics.Get("stats.auth_enabled.oauth_generic_oauth.count").MustInt()) assert.Equal(t, 1, metrics.Get("stats.auth_enabled.oauth_grafana_com.count").MustInt()) assert.Equal(t, 1, metrics.Get("stats.packaging.deb.count").MustInt()) assert.Equal(t, 1, metrics.Get("stats.distributor.hosted-grafana.count").MustInt()) assert.Equal(t, 1, metrics.Get("stats.auth_token_per_user_le_3").MustInt()) assert.Equal(t, 2, metrics.Get("stats.auth_token_per_user_le_6").MustInt()) assert.Equal(t, 3, metrics.Get("stats.auth_token_per_user_le_9").MustInt()) assert.Equal(t, 4, metrics.Get("stats.auth_token_per_user_le_12").MustInt()) assert.Equal(t, 5, metrics.Get("stats.auth_token_per_user_le_15").MustInt()) assert.Equal(t, 6, metrics.Get("stats.auth_token_per_user_le_inf").MustInt()) assert.LessOrEqual(t, 60, metrics.Get("stats.uptime").MustInt()) assert.Greater(t, 70, metrics.Get("stats.uptime").MustInt()) }) }) t.Run("When updating total stats", func(t *testing.T) { uss := createService(t, setting.Cfg{}) uss.Cfg.MetricsEndpointEnabled = true uss.Cfg.MetricsEndpointDisableTotalStats = false getSystemStatsWasCalled := false uss.Bus.AddHandlerCtx(func(ctx context.Context, query *models.GetSystemStatsQuery) error { query.Result = &models.SystemStats{} getSystemStatsWasCalled = true return nil }) t.Run("When metrics is disabled and total stats is enabled, stats should not be updated", func(t *testing.T) { uss.Cfg.MetricsEndpointEnabled = false uss.Cfg.MetricsEndpointDisableTotalStats = false uss.updateTotalStats(context.Background()) assert.False(t, getSystemStatsWasCalled) }) t.Run("When metrics is enabled and total stats is disabled, stats should not be updated", func(t *testing.T) { uss.Cfg.MetricsEndpointEnabled = true uss.Cfg.MetricsEndpointDisableTotalStats = true uss.updateTotalStats(context.Background()) assert.False(t, getSystemStatsWasCalled) }) t.Run("When metrics is disabled and total stats is disabled, stats should not be updated", func(t *testing.T) { uss.Cfg.MetricsEndpointEnabled = false uss.Cfg.MetricsEndpointDisableTotalStats = true uss.updateTotalStats(context.Background()) assert.False(t, getSystemStatsWasCalled) }) t.Run("When metrics is enabled and total stats is enabled, stats should be updated", func(t *testing.T) { uss.Cfg.MetricsEndpointEnabled = true uss.Cfg.MetricsEndpointDisableTotalStats = false uss.updateTotalStats(context.Background()) assert.True(t, getSystemStatsWasCalled) }) }) t.Run("When registering a metric", func(t *testing.T) { uss := createService(t, setting.Cfg{}) metricName := "stats.test_metric.count" t.Run("Adds a new metric to the external metrics", func(t *testing.T) { uss.RegisterMetricsFunc(func(context.Context) (map[string]interface{}, error) { return map[string]interface{}{metricName: 1}, nil }) metrics, err := uss.externalMetrics[0](context.Background()) require.NoError(t, err) assert.Equal(t, map[string]interface{}{metricName: 1}, metrics) }) }) t.Run("When getting usage report", func(t *testing.T) { uss := createService(t, setting.Cfg{}) metricName := "stats.test_metric.count" uss.Bus.AddHandlerCtx(func(ctx context.Context, query *models.GetSystemStatsQuery) error { query.Result = &models.SystemStats{} return nil }) uss.Bus.AddHandlerCtx(func(ctx context.Context, query *models.GetDataSourceStatsQuery) error { query.Result = []*models.DataSourceStats{} return nil }) uss.Bus.AddHandlerCtx(func(ctx context.Context, query *models.GetDataSourcesByTypeQuery) error { query.Result = []*models.DataSource{} return nil }) uss.Bus.AddHandlerCtx(func(ctx context.Context, query *models.GetDataSourceAccessStatsQuery) error { query.Result = []*models.DataSourceAccessStats{} return nil }) uss.Bus.AddHandlerCtx(func(ctx context.Context, query *models.GetAlertNotifierUsageStatsQuery) error { query.Result = []*models.NotifierUsageStats{} return nil }) createConcurrentTokens(t, uss.SQLStore) t.Run("Should include metrics for concurrent users", func(t *testing.T) { report, err := uss.GetUsageReport(context.Background()) require.NoError(t, err) assert.Equal(t, int32(1), report.Metrics["stats.auth_token_per_user_le_3"]) assert.Equal(t, int32(2), report.Metrics["stats.auth_token_per_user_le_6"]) assert.Equal(t, int32(3), report.Metrics["stats.auth_token_per_user_le_9"]) assert.Equal(t, int32(4), report.Metrics["stats.auth_token_per_user_le_12"]) assert.Equal(t, int32(5), report.Metrics["stats.auth_token_per_user_le_15"]) assert.Equal(t, int32(6), report.Metrics["stats.auth_token_per_user_le_inf"]) }) t.Run("Should include external metrics", func(t *testing.T) { uss.RegisterMetricsFunc(func(context.Context) (map[string]interface{}, error) { return map[string]interface{}{metricName: 1}, nil }) report, err := uss.GetUsageReport(context.Background()) require.NoError(t, err, "Expected no error") metric := report.Metrics[metricName] assert.Equal(t, 1, metric) }) }) t.Run("When registering external metrics", func(t *testing.T) { uss := createService(t, setting.Cfg{}) metrics := map[string]interface{}{"stats.test_metric.count": 1, "stats.test_metric_second.count": 2} extMetricName := "stats.test_external_metric.count" uss.RegisterMetricsFunc(func(context.Context) (map[string]interface{}, error) { return map[string]interface{}{extMetricName: 1}, nil }) uss.registerExternalMetrics(context.Background(), metrics) assert.Equal(t, 1, metrics[extMetricName]) t.Run("When loading a metric results to an error", func(t *testing.T) { uss.RegisterMetricsFunc(func(context.Context) (map[string]interface{}, error) { return map[string]interface{}{extMetricName: 1}, nil }) extErrorMetricName := "stats.test_external_metric_error.count" t.Run("Should not add it to metrics", func(t *testing.T) { uss.RegisterMetricsFunc(func(context.Context) (map[string]interface{}, error) { return map[string]interface{}{extErrorMetricName: 1}, errors.New("some error") }) uss.registerExternalMetrics(context.Background(), metrics) extErrorMetric := metrics[extErrorMetricName] extMetric := metrics[extMetricName] require.Nil(t, extErrorMetric, "Invalid metric should not be added") assert.Equal(t, 1, extMetric) assert.Len(t, metrics, 3, "Expected only one available metric") }) }) }) } type fakePluginStore struct { plugins.Store plugins map[string]plugins.PluginDTO } func (pr fakePluginStore) Plugin(_ context.Context, pluginID string) (plugins.PluginDTO, bool) { p, exists := pr.plugins[pluginID] return p, exists } func (pr fakePluginStore) Plugins(_ context.Context, pluginTypes ...plugins.Type) []plugins.PluginDTO { var result []plugins.PluginDTO for _, v := range pr.plugins { for _, t := range pluginTypes { if v.Type == t { result = append(result, v) } } } return result } func setupSomeDataSourcePlugins(t *testing.T, uss *UsageStats) { t.Helper() uss.pluginStore = &fakePluginStore{ plugins: map[string]plugins.PluginDTO{ models.DS_ES: { Signature: "internal", }, models.DS_PROMETHEUS: { Signature: "internal", }, models.DS_GRAPHITE: { Signature: "internal", }, models.DS_MYSQL: { Signature: "internal", }, }, } } type httpResp struct { req *http.Request responseBuffer *bytes.Buffer err error } func createService(t *testing.T, cfg setting.Cfg) *UsageStats { t.Helper() sqlStore := sqlstore.InitTestDB(t) return &UsageStats{ Bus: bus.New(), Cfg: &cfg, SQLStore: sqlStore, externalMetrics: make([]usagestats.MetricsFunc, 0), pluginStore: &fakePluginStore{}, kvStore: kvstore.WithNamespace(kvstore.ProvideService(sqlStore), 0, "infra.usagestats"), log: log.New("infra.usagestats"), startTime: time.Now().Add(-1 * time.Minute), } }
pkg/infra/usagestats/service/usage_stats_test.go
1
https://github.com/grafana/grafana/commit/a1b8b5d123bde86fcfd7195c01b43d83a687d0ad
[ 0.023973463103175163, 0.0008431060123257339, 0.00016287053585983813, 0.00017266192298848182, 0.003365170443430543 ]
{ "id": 0, "code_window": [ "\tmetrics[\"stats.library_variables.count\"] = statsQuery.Result.LibraryVariables\n", "\tmetrics[\"stats.dashboards_viewers_can_edit.count\"] = statsQuery.Result.DashboardsViewersCanEdit\n", "\tmetrics[\"stats.dashboards_viewers_can_admin.count\"] = statsQuery.Result.DashboardsViewersCanAdmin\n", "\tmetrics[\"stats.folders_viewers_can_edit.count\"] = statsQuery.Result.FoldersViewersCanEdit\n", "\tmetrics[\"stats.folders_viewers_can_admin.count\"] = statsQuery.Result.FoldersViewersCanAdmin\n", "\n", "\tossEditionCount := 1\n", "\tenterpriseEditionCount := 0\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\tmetrics[\"stats.api_keys.count\"] = statsQuery.Result.APIKeys\n" ], "file_path": "pkg/infra/usagestats/service/usage_stats.go", "type": "add", "edit_start_line_idx": 86 }
import { DataSourceInstanceSettings } from '@grafana/data'; import { reduxTester } from '../../../../test/core/redux/reduxTester'; import { getRootReducer, RootReducerType } from '../state/helpers'; import { toVariableIdentifier, toVariablePayload } from '../state/types'; import { variableAdapters } from '../adapters'; import { createDataSourceVariableAdapter } from './adapter'; import { DataSourceVariableActionDependencies, initDataSourceVariableEditor, updateDataSourceVariableOptions, } from './actions'; import { getMockPlugin } from '../../plugins/__mocks__/pluginMocks'; import { createDataSourceOptions } from './reducer'; import { addVariable, setCurrentVariableValue } from '../state/sharedReducer'; import { changeVariableEditorExtended } from '../editor/reducer'; import { datasourceBuilder } from '../shared/testing/builders'; import { getDataSourceInstanceSetting } from '../shared/testing/helpers'; interface Args { sources?: DataSourceInstanceSettings[]; query?: string; regex?: string; } function getTestContext({ sources = [], query, regex }: Args = {}) { const getListMock = jest.fn().mockReturnValue(sources); const getDatasourceSrvMock = jest.fn().mockReturnValue({ getList: getListMock }); const dependencies: DataSourceVariableActionDependencies = { getDatasourceSrv: getDatasourceSrvMock }; const datasource = datasourceBuilder().withId('0').withQuery(query).withRegEx(regex).build(); return { getListMock, getDatasourceSrvMock, dependencies, datasource }; } describe('data source actions', () => { variableAdapters.setInit(() => [createDataSourceVariableAdapter()]); describe('when updateDataSourceVariableOptions is dispatched', () => { describe('and there is no regex', () => { it('then the correct actions are dispatched', async () => { const meta = getMockPlugin({ name: 'mock-data-name', id: 'mock-data-id' }); const sources: DataSourceInstanceSettings[] = [ getDataSourceInstanceSetting('first-name', meta), getDataSourceInstanceSetting('second-name', meta), ]; const { datasource, dependencies, getListMock, getDatasourceSrvMock } = getTestContext({ sources, query: 'mock-data-id', }); const tester = await reduxTester<RootReducerType>() .givenRootReducer(getRootReducer()) .whenActionIsDispatched( addVariable(toVariablePayload(datasource, { global: false, index: 0, model: datasource })) ) .whenAsyncActionIsDispatched( updateDataSourceVariableOptions(toVariableIdentifier(datasource), dependencies), true ); await tester.thenDispatchedActionsShouldEqual( createDataSourceOptions( toVariablePayload( { type: 'datasource', id: '0' }, { sources, regex: (undefined as unknown) as RegExp, } ) ), setCurrentVariableValue( toVariablePayload( { type: 'datasource', id: '0' }, { option: { text: 'first-name', value: 'first-name', selected: false } } ) ) ); expect(getListMock).toHaveBeenCalledTimes(1); expect(getListMock).toHaveBeenCalledWith({ metrics: true, variables: false }); expect(getDatasourceSrvMock).toHaveBeenCalledTimes(1); }); }); describe('and there is a regex', () => { it('then the correct actions are dispatched', async () => { const meta = getMockPlugin({ name: 'mock-data-name', id: 'mock-data-id' }); const sources: DataSourceInstanceSettings[] = [ getDataSourceInstanceSetting('first-name', meta), getDataSourceInstanceSetting('second-name', meta), ]; const { datasource, dependencies, getListMock, getDatasourceSrvMock } = getTestContext({ sources, query: 'mock-data-id', regex: '/.*(second-name).*/', }); const tester = await reduxTester<RootReducerType>() .givenRootReducer(getRootReducer()) .whenActionIsDispatched( addVariable(toVariablePayload(datasource, { global: false, index: 0, model: datasource })) ) .whenAsyncActionIsDispatched( updateDataSourceVariableOptions(toVariableIdentifier(datasource), dependencies), true ); await tester.thenDispatchedActionsShouldEqual( createDataSourceOptions( toVariablePayload( { type: 'datasource', id: '0' }, { sources, regex: /.*(second-name).*/, } ) ), setCurrentVariableValue( toVariablePayload( { type: 'datasource', id: '0' }, { option: { text: 'second-name', value: 'second-name', selected: false } } ) ) ); expect(getListMock).toHaveBeenCalledTimes(1); expect(getListMock).toHaveBeenCalledWith({ metrics: true, variables: false }); expect(getDatasourceSrvMock).toHaveBeenCalledTimes(1); }); }); }); describe('when initDataSourceVariableEditor is dispatched', () => { it('then the correct actions are dispatched', async () => { const meta = getMockPlugin({ name: 'mock-data-name', id: 'mock-data-id' }); const sources: DataSourceInstanceSettings[] = [ getDataSourceInstanceSetting('first-name', meta), getDataSourceInstanceSetting('second-name', meta), ]; const { dependencies, getListMock, getDatasourceSrvMock } = getTestContext({ sources }); await reduxTester<RootReducerType>() .givenRootReducer(getRootReducer()) .whenActionIsDispatched(initDataSourceVariableEditor(dependencies)) .thenDispatchedActionsShouldEqual( changeVariableEditorExtended({ propName: 'dataSourceTypes', propValue: [ { text: '', value: '' }, { text: 'mock-data-name', value: 'mock-data-id' }, ], }) ); expect(getListMock).toHaveBeenCalledTimes(1); expect(getListMock).toHaveBeenCalledWith({ metrics: true, variables: true }); expect(getDatasourceSrvMock).toHaveBeenCalledTimes(1); }); }); });
public/app/features/variables/datasource/actions.test.ts
0
https://github.com/grafana/grafana/commit/a1b8b5d123bde86fcfd7195c01b43d83a687d0ad
[ 0.00017787941033020616, 0.00017382026999257505, 0.00016551115550100803, 0.00017527115414850414, 0.000003506601615299587 ]
{ "id": 0, "code_window": [ "\tmetrics[\"stats.library_variables.count\"] = statsQuery.Result.LibraryVariables\n", "\tmetrics[\"stats.dashboards_viewers_can_edit.count\"] = statsQuery.Result.DashboardsViewersCanEdit\n", "\tmetrics[\"stats.dashboards_viewers_can_admin.count\"] = statsQuery.Result.DashboardsViewersCanAdmin\n", "\tmetrics[\"stats.folders_viewers_can_edit.count\"] = statsQuery.Result.FoldersViewersCanEdit\n", "\tmetrics[\"stats.folders_viewers_can_admin.count\"] = statsQuery.Result.FoldersViewersCanAdmin\n", "\n", "\tossEditionCount := 1\n", "\tenterpriseEditionCount := 0\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\tmetrics[\"stats.api_keys.count\"] = statsQuery.Result.APIKeys\n" ], "file_path": "pkg/infra/usagestats/service/usage_stats.go", "type": "add", "edit_start_line_idx": 86 }
package channels import "time" // mockTimeNow replaces function timeNow to return constant time. // It returns a function that resets the variable back to its original value. // This allows usage of this function with defer: // func Test (t *testing.T) { // now := time.Now() // defer mockTimeNow(now)() // ... // } func mockTimeNow(constTime time.Time) func() { timeNow = func() time.Time { return constTime } return resetTimeNow } // resetTimeNow resets the global variable timeNow to the default value, which is time.Now func resetTimeNow() { timeNow = time.Now }
pkg/services/ngalert/notifier/channels/testing.go
0
https://github.com/grafana/grafana/commit/a1b8b5d123bde86fcfd7195c01b43d83a687d0ad
[ 0.00017770192062016577, 0.00017249620577786118, 0.00016749136557336897, 0.00017229534569196403, 0.000004170860847807489 ]
{ "id": 0, "code_window": [ "\tmetrics[\"stats.library_variables.count\"] = statsQuery.Result.LibraryVariables\n", "\tmetrics[\"stats.dashboards_viewers_can_edit.count\"] = statsQuery.Result.DashboardsViewersCanEdit\n", "\tmetrics[\"stats.dashboards_viewers_can_admin.count\"] = statsQuery.Result.DashboardsViewersCanAdmin\n", "\tmetrics[\"stats.folders_viewers_can_edit.count\"] = statsQuery.Result.FoldersViewersCanEdit\n", "\tmetrics[\"stats.folders_viewers_can_admin.count\"] = statsQuery.Result.FoldersViewersCanAdmin\n", "\n", "\tossEditionCount := 1\n", "\tenterpriseEditionCount := 0\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\tmetrics[\"stats.api_keys.count\"] = statsQuery.Result.APIKeys\n" ], "file_path": "pkg/infra/usagestats/service/usage_stats.go", "type": "add", "edit_start_line_idx": 86 }
// Copyright (c) 2017 Uber Technologies, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * given a number and a desired precision for the floating * side, return the number at the new precision. * * toFloatPrecision(3.55, 1) // 3.5 * toFloatPrecision(0.04422, 2) // 0.04 * toFloatPrecision(6.24e6, 2) // 6240000.00 * * does not support numbers that use "e" notation on toString. * * @param {number} number * @param {number} precision * @returns {number} number at new floating precision */ export function toFloatPrecision(number: number, precision: number): number { const log10Length = Math.floor(Math.log10(Math.abs(number))) + 1; const targetPrecision = precision + log10Length; if (targetPrecision <= 0) { return Math.trunc(number); } return Number(number.toPrecision(targetPrecision)); }
packages/jaeger-ui-components/src/utils/number.tsx
0
https://github.com/grafana/grafana/commit/a1b8b5d123bde86fcfd7195c01b43d83a687d0ad
[ 0.00017769497935660183, 0.00017373287118971348, 0.0001701066066743806, 0.00017356494208797812, 0.000002934310714408639 ]
{ "id": 1, "code_window": [ "\t\t\t\tDashboardsViewersCanAdmin: 3,\n", "\t\t\t\tDashboardsViewersCanEdit: 2,\n", "\t\t\t\tFoldersViewersCanAdmin: 1,\n", "\t\t\t\tFoldersViewersCanEdit: 5,\n", "\t\t\t}\n", "\t\t\tgetSystemStatsQuery = query\n", "\t\t\treturn nil\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tAPIKeys: 2,\n" ], "file_path": "pkg/infra/usagestats/service/usage_stats_test.go", "type": "add", "edit_start_line_idx": 81 }
package service import ( "bytes" "context" "errors" "io/ioutil" "net/http" "net/http/httptest" "runtime" "testing" "time" "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/components/simplejson" "github.com/grafana/grafana/pkg/infra/kvstore" "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/infra/usagestats" "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/plugins" "github.com/grafana/grafana/pkg/services/sqlstore" "github.com/grafana/grafana/pkg/setting" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) // This is to ensure that the interface contract is held by the implementation func Test_InterfaceContractValidity(t *testing.T) { newUsageStats := func() usagestats.Service { return &UsageStats{} } v, ok := newUsageStats().(*UsageStats) assert.NotNil(t, v) assert.True(t, ok) } func TestMetrics(t *testing.T) { t.Run("When sending usage stats", func(t *testing.T) { uss := createService(t, setting.Cfg{}) setupSomeDataSourcePlugins(t, uss) var getSystemStatsQuery *models.GetSystemStatsQuery uss.Bus.AddHandlerCtx(func(ctx context.Context, query *models.GetSystemStatsQuery) error { query.Result = &models.SystemStats{ Dashboards: 1, Datasources: 2, Users: 3, Admins: 31, Editors: 32, Viewers: 33, ActiveUsers: 4, ActiveAdmins: 21, ActiveEditors: 22, ActiveViewers: 23, ActiveSessions: 24, DailyActiveUsers: 25, DailyActiveAdmins: 26, DailyActiveEditors: 27, DailyActiveViewers: 28, DailyActiveSessions: 29, Orgs: 5, Playlists: 6, Alerts: 7, Stars: 8, Folders: 9, DashboardPermissions: 10, FolderPermissions: 11, ProvisionedDashboards: 12, Snapshots: 13, Teams: 14, AuthTokens: 15, DashboardVersions: 16, Annotations: 17, AlertRules: 18, LibraryPanels: 19, LibraryVariables: 20, DashboardsViewersCanAdmin: 3, DashboardsViewersCanEdit: 2, FoldersViewersCanAdmin: 1, FoldersViewersCanEdit: 5, } getSystemStatsQuery = query return nil }) var getDataSourceStatsQuery *models.GetDataSourceStatsQuery uss.Bus.AddHandlerCtx(func(ctx context.Context, query *models.GetDataSourceStatsQuery) error { query.Result = []*models.DataSourceStats{ { Type: models.DS_ES, Count: 9, }, { Type: models.DS_PROMETHEUS, Count: 10, }, { Type: "unknown_ds", Count: 11, }, { Type: "unknown_ds2", Count: 12, }, } getDataSourceStatsQuery = query return nil }) var getESDatasSourcesQuery *models.GetDataSourcesByTypeQuery uss.Bus.AddHandlerCtx(func(ctx context.Context, query *models.GetDataSourcesByTypeQuery) error { query.Result = []*models.DataSource{ { JsonData: simplejson.NewFromAny(map[string]interface{}{ "esVersion": 2, }), }, { JsonData: simplejson.NewFromAny(map[string]interface{}{ "esVersion": 2, }), }, { JsonData: simplejson.NewFromAny(map[string]interface{}{ "esVersion": 70, }), }, } getESDatasSourcesQuery = query return nil }) var getDataSourceAccessStatsQuery *models.GetDataSourceAccessStatsQuery uss.Bus.AddHandlerCtx(func(ctx context.Context, query *models.GetDataSourceAccessStatsQuery) error { query.Result = []*models.DataSourceAccessStats{ { Type: models.DS_ES, Access: "direct", Count: 1, }, { Type: models.DS_ES, Access: "proxy", Count: 2, }, { Type: models.DS_PROMETHEUS, Access: "proxy", Count: 3, }, { Type: "unknown_ds", Access: "proxy", Count: 4, }, { Type: "unknown_ds2", Access: "", Count: 5, }, { Type: "unknown_ds3", Access: "direct", Count: 6, }, { Type: "unknown_ds4", Access: "direct", Count: 7, }, { Type: "unknown_ds5", Access: "proxy", Count: 8, }, } getDataSourceAccessStatsQuery = query return nil }) var getAlertNotifierUsageStatsQuery *models.GetAlertNotifierUsageStatsQuery uss.Bus.AddHandlerCtx(func(ctx context.Context, query *models.GetAlertNotifierUsageStatsQuery) error { query.Result = []*models.NotifierUsageStats{ { Type: "slack", Count: 1, }, { Type: "webhook", Count: 2, }, } getAlertNotifierUsageStatsQuery = query return nil }) createConcurrentTokens(t, uss.SQLStore) uss.oauthProviders = map[string]bool{ "github": true, "gitlab": true, "azuread": true, "google": true, "generic_oauth": true, "grafana_com": true, } err := uss.sendUsageStats(context.Background()) require.NoError(t, err) t.Run("Given reporting not enabled and sending usage stats", func(t *testing.T) { origSendUsageStats := sendUsageStats t.Cleanup(func() { sendUsageStats = origSendUsageStats }) statsSent := false sendUsageStats = func(uss *UsageStats, b *bytes.Buffer) { statsSent = true } uss.Cfg.ReportingEnabled = false err := uss.sendUsageStats(context.Background()) require.NoError(t, err) require.False(t, statsSent) assert.Nil(t, getSystemStatsQuery) assert.Nil(t, getDataSourceStatsQuery) assert.Nil(t, getDataSourceAccessStatsQuery) assert.Nil(t, getESDatasSourcesQuery) }) t.Run("Given reporting enabled, stats should be gathered and sent to HTTP endpoint", func(t *testing.T) { origCfg := uss.Cfg t.Cleanup(func() { uss.Cfg = origCfg }) uss.Cfg = &setting.Cfg{ ReportingEnabled: true, BuildVersion: "5.0.0", AnonymousEnabled: true, BasicAuthEnabled: true, LDAPEnabled: true, AuthProxyEnabled: true, Packaging: "deb", ReportingDistributor: "hosted-grafana", } ch := make(chan httpResp) ticker := time.NewTicker(2 * time.Second) ts := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { buf, err := ioutil.ReadAll(r.Body) if err != nil { t.Logf("Fake HTTP handler received an error: %s", err.Error()) ch <- httpResp{ err: err, } return } require.NoError(t, err, "Failed to read response body, err=%v", err) t.Logf("Fake HTTP handler received a response") ch <- httpResp{ responseBuffer: bytes.NewBuffer(buf), req: r, } })) t.Cleanup(ts.Close) t.Cleanup(func() { close(ch) }) usageStatsURL = ts.URL err := uss.sendUsageStats(context.Background()) require.NoError(t, err) // Wait for fake HTTP server to receive a request var resp httpResp select { case resp = <-ch: require.NoError(t, resp.err, "Fake server experienced an error") case <-ticker.C: t.Fatalf("Timed out waiting for HTTP request") } t.Logf("Received response from fake HTTP server: %+v\n", resp) assert.NotNil(t, getSystemStatsQuery) assert.NotNil(t, getDataSourceStatsQuery) assert.NotNil(t, getESDatasSourcesQuery) assert.NotNil(t, getDataSourceAccessStatsQuery) assert.NotNil(t, getAlertNotifierUsageStatsQuery) assert.NotNil(t, resp.req) assert.Equal(t, http.MethodPost, resp.req.Method) assert.Equal(t, "application/json", resp.req.Header.Get("Content-Type")) require.NotNil(t, resp.responseBuffer) j, err := simplejson.NewFromReader(resp.responseBuffer) require.NoError(t, err) assert.Equal(t, "5_0_0", j.Get("version").MustString()) assert.Equal(t, runtime.GOOS, j.Get("os").MustString()) assert.Equal(t, runtime.GOARCH, j.Get("arch").MustString()) usageId := uss.GetUsageStatsId(context.Background()) assert.NotEmpty(t, usageId) assert.Equal(t, usageId, j.Get("usageStatsId").MustString()) metrics := j.Get("metrics") assert.Equal(t, getSystemStatsQuery.Result.Dashboards, metrics.Get("stats.dashboards.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.Users, metrics.Get("stats.users.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.Admins, metrics.Get("stats.admins.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.Editors, metrics.Get("stats.editors.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.Viewers, metrics.Get("stats.viewers.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.Orgs, metrics.Get("stats.orgs.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.Playlists, metrics.Get("stats.playlist.count").MustInt64()) assert.Equal(t, uss.appCount(context.Background()), metrics.Get("stats.plugins.apps.count").MustInt()) assert.Equal(t, uss.panelCount(context.Background()), metrics.Get("stats.plugins.panels.count").MustInt()) assert.Equal(t, uss.dataSourceCount(context.Background()), metrics.Get("stats.plugins.datasources.count").MustInt()) assert.Equal(t, getSystemStatsQuery.Result.Alerts, metrics.Get("stats.alerts.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.ActiveUsers, metrics.Get("stats.active_users.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.ActiveAdmins, metrics.Get("stats.active_admins.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.ActiveEditors, metrics.Get("stats.active_editors.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.ActiveViewers, metrics.Get("stats.active_viewers.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.ActiveSessions, metrics.Get("stats.active_sessions.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.DailyActiveUsers, metrics.Get("stats.daily_active_users.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.DailyActiveAdmins, metrics.Get("stats.daily_active_admins.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.DailyActiveEditors, metrics.Get("stats.daily_active_editors.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.DailyActiveViewers, metrics.Get("stats.daily_active_viewers.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.DailyActiveSessions, metrics.Get("stats.daily_active_sessions.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.Datasources, metrics.Get("stats.datasources.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.Stars, metrics.Get("stats.stars.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.Folders, metrics.Get("stats.folders.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.DashboardPermissions, metrics.Get("stats.dashboard_permissions.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.FolderPermissions, metrics.Get("stats.folder_permissions.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.ProvisionedDashboards, metrics.Get("stats.provisioned_dashboards.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.Snapshots, metrics.Get("stats.snapshots.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.Teams, metrics.Get("stats.teams.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.DashboardsViewersCanEdit, metrics.Get("stats.dashboards_viewers_can_edit.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.DashboardsViewersCanAdmin, metrics.Get("stats.dashboards_viewers_can_admin.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.FoldersViewersCanEdit, metrics.Get("stats.folders_viewers_can_edit.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.FoldersViewersCanAdmin, metrics.Get("stats.folders_viewers_can_admin.count").MustInt64()) assert.Equal(t, 15, metrics.Get("stats.total_auth_token.count").MustInt()) assert.Equal(t, 5, metrics.Get("stats.avg_auth_token_per_user.count").MustInt()) assert.Equal(t, 16, metrics.Get("stats.dashboard_versions.count").MustInt()) assert.Equal(t, 17, metrics.Get("stats.annotations.count").MustInt()) assert.Equal(t, 18, metrics.Get("stats.alert_rules.count").MustInt()) assert.Equal(t, 19, metrics.Get("stats.library_panels.count").MustInt()) assert.Equal(t, 20, metrics.Get("stats.library_variables.count").MustInt()) assert.Equal(t, 0, metrics.Get("stats.live_users.count").MustInt()) assert.Equal(t, 0, metrics.Get("stats.live_clients.count").MustInt()) assert.Equal(t, 9, metrics.Get("stats.ds."+models.DS_ES+".count").MustInt()) assert.Equal(t, 10, metrics.Get("stats.ds."+models.DS_PROMETHEUS+".count").MustInt()) assert.Equal(t, 2, metrics.Get("stats.ds."+models.DS_ES+".v2.count").MustInt()) assert.Equal(t, 1, metrics.Get("stats.ds."+models.DS_ES+".v70.count").MustInt()) assert.Equal(t, 11+12, metrics.Get("stats.ds.other.count").MustInt()) assert.Equal(t, 1, metrics.Get("stats.ds_access."+models.DS_ES+".direct.count").MustInt()) assert.Equal(t, 2, metrics.Get("stats.ds_access."+models.DS_ES+".proxy.count").MustInt()) assert.Equal(t, 3, metrics.Get("stats.ds_access."+models.DS_PROMETHEUS+".proxy.count").MustInt()) assert.Equal(t, 6+7, metrics.Get("stats.ds_access.other.direct.count").MustInt()) assert.Equal(t, 4+8, metrics.Get("stats.ds_access.other.proxy.count").MustInt()) assert.Equal(t, 1, metrics.Get("stats.alert_notifiers.slack.count").MustInt()) assert.Equal(t, 2, metrics.Get("stats.alert_notifiers.webhook.count").MustInt()) assert.Equal(t, 1, metrics.Get("stats.auth_enabled.anonymous.count").MustInt()) assert.Equal(t, 1, metrics.Get("stats.auth_enabled.basic_auth.count").MustInt()) assert.Equal(t, 1, metrics.Get("stats.auth_enabled.ldap.count").MustInt()) assert.Equal(t, 1, metrics.Get("stats.auth_enabled.auth_proxy.count").MustInt()) assert.Equal(t, 1, metrics.Get("stats.auth_enabled.oauth_github.count").MustInt()) assert.Equal(t, 1, metrics.Get("stats.auth_enabled.oauth_gitlab.count").MustInt()) assert.Equal(t, 1, metrics.Get("stats.auth_enabled.oauth_google.count").MustInt()) assert.Equal(t, 1, metrics.Get("stats.auth_enabled.oauth_azuread.count").MustInt()) assert.Equal(t, 1, metrics.Get("stats.auth_enabled.oauth_generic_oauth.count").MustInt()) assert.Equal(t, 1, metrics.Get("stats.auth_enabled.oauth_grafana_com.count").MustInt()) assert.Equal(t, 1, metrics.Get("stats.packaging.deb.count").MustInt()) assert.Equal(t, 1, metrics.Get("stats.distributor.hosted-grafana.count").MustInt()) assert.Equal(t, 1, metrics.Get("stats.auth_token_per_user_le_3").MustInt()) assert.Equal(t, 2, metrics.Get("stats.auth_token_per_user_le_6").MustInt()) assert.Equal(t, 3, metrics.Get("stats.auth_token_per_user_le_9").MustInt()) assert.Equal(t, 4, metrics.Get("stats.auth_token_per_user_le_12").MustInt()) assert.Equal(t, 5, metrics.Get("stats.auth_token_per_user_le_15").MustInt()) assert.Equal(t, 6, metrics.Get("stats.auth_token_per_user_le_inf").MustInt()) assert.LessOrEqual(t, 60, metrics.Get("stats.uptime").MustInt()) assert.Greater(t, 70, metrics.Get("stats.uptime").MustInt()) }) }) t.Run("When updating total stats", func(t *testing.T) { uss := createService(t, setting.Cfg{}) uss.Cfg.MetricsEndpointEnabled = true uss.Cfg.MetricsEndpointDisableTotalStats = false getSystemStatsWasCalled := false uss.Bus.AddHandlerCtx(func(ctx context.Context, query *models.GetSystemStatsQuery) error { query.Result = &models.SystemStats{} getSystemStatsWasCalled = true return nil }) t.Run("When metrics is disabled and total stats is enabled, stats should not be updated", func(t *testing.T) { uss.Cfg.MetricsEndpointEnabled = false uss.Cfg.MetricsEndpointDisableTotalStats = false uss.updateTotalStats(context.Background()) assert.False(t, getSystemStatsWasCalled) }) t.Run("When metrics is enabled and total stats is disabled, stats should not be updated", func(t *testing.T) { uss.Cfg.MetricsEndpointEnabled = true uss.Cfg.MetricsEndpointDisableTotalStats = true uss.updateTotalStats(context.Background()) assert.False(t, getSystemStatsWasCalled) }) t.Run("When metrics is disabled and total stats is disabled, stats should not be updated", func(t *testing.T) { uss.Cfg.MetricsEndpointEnabled = false uss.Cfg.MetricsEndpointDisableTotalStats = true uss.updateTotalStats(context.Background()) assert.False(t, getSystemStatsWasCalled) }) t.Run("When metrics is enabled and total stats is enabled, stats should be updated", func(t *testing.T) { uss.Cfg.MetricsEndpointEnabled = true uss.Cfg.MetricsEndpointDisableTotalStats = false uss.updateTotalStats(context.Background()) assert.True(t, getSystemStatsWasCalled) }) }) t.Run("When registering a metric", func(t *testing.T) { uss := createService(t, setting.Cfg{}) metricName := "stats.test_metric.count" t.Run("Adds a new metric to the external metrics", func(t *testing.T) { uss.RegisterMetricsFunc(func(context.Context) (map[string]interface{}, error) { return map[string]interface{}{metricName: 1}, nil }) metrics, err := uss.externalMetrics[0](context.Background()) require.NoError(t, err) assert.Equal(t, map[string]interface{}{metricName: 1}, metrics) }) }) t.Run("When getting usage report", func(t *testing.T) { uss := createService(t, setting.Cfg{}) metricName := "stats.test_metric.count" uss.Bus.AddHandlerCtx(func(ctx context.Context, query *models.GetSystemStatsQuery) error { query.Result = &models.SystemStats{} return nil }) uss.Bus.AddHandlerCtx(func(ctx context.Context, query *models.GetDataSourceStatsQuery) error { query.Result = []*models.DataSourceStats{} return nil }) uss.Bus.AddHandlerCtx(func(ctx context.Context, query *models.GetDataSourcesByTypeQuery) error { query.Result = []*models.DataSource{} return nil }) uss.Bus.AddHandlerCtx(func(ctx context.Context, query *models.GetDataSourceAccessStatsQuery) error { query.Result = []*models.DataSourceAccessStats{} return nil }) uss.Bus.AddHandlerCtx(func(ctx context.Context, query *models.GetAlertNotifierUsageStatsQuery) error { query.Result = []*models.NotifierUsageStats{} return nil }) createConcurrentTokens(t, uss.SQLStore) t.Run("Should include metrics for concurrent users", func(t *testing.T) { report, err := uss.GetUsageReport(context.Background()) require.NoError(t, err) assert.Equal(t, int32(1), report.Metrics["stats.auth_token_per_user_le_3"]) assert.Equal(t, int32(2), report.Metrics["stats.auth_token_per_user_le_6"]) assert.Equal(t, int32(3), report.Metrics["stats.auth_token_per_user_le_9"]) assert.Equal(t, int32(4), report.Metrics["stats.auth_token_per_user_le_12"]) assert.Equal(t, int32(5), report.Metrics["stats.auth_token_per_user_le_15"]) assert.Equal(t, int32(6), report.Metrics["stats.auth_token_per_user_le_inf"]) }) t.Run("Should include external metrics", func(t *testing.T) { uss.RegisterMetricsFunc(func(context.Context) (map[string]interface{}, error) { return map[string]interface{}{metricName: 1}, nil }) report, err := uss.GetUsageReport(context.Background()) require.NoError(t, err, "Expected no error") metric := report.Metrics[metricName] assert.Equal(t, 1, metric) }) }) t.Run("When registering external metrics", func(t *testing.T) { uss := createService(t, setting.Cfg{}) metrics := map[string]interface{}{"stats.test_metric.count": 1, "stats.test_metric_second.count": 2} extMetricName := "stats.test_external_metric.count" uss.RegisterMetricsFunc(func(context.Context) (map[string]interface{}, error) { return map[string]interface{}{extMetricName: 1}, nil }) uss.registerExternalMetrics(context.Background(), metrics) assert.Equal(t, 1, metrics[extMetricName]) t.Run("When loading a metric results to an error", func(t *testing.T) { uss.RegisterMetricsFunc(func(context.Context) (map[string]interface{}, error) { return map[string]interface{}{extMetricName: 1}, nil }) extErrorMetricName := "stats.test_external_metric_error.count" t.Run("Should not add it to metrics", func(t *testing.T) { uss.RegisterMetricsFunc(func(context.Context) (map[string]interface{}, error) { return map[string]interface{}{extErrorMetricName: 1}, errors.New("some error") }) uss.registerExternalMetrics(context.Background(), metrics) extErrorMetric := metrics[extErrorMetricName] extMetric := metrics[extMetricName] require.Nil(t, extErrorMetric, "Invalid metric should not be added") assert.Equal(t, 1, extMetric) assert.Len(t, metrics, 3, "Expected only one available metric") }) }) }) } type fakePluginStore struct { plugins.Store plugins map[string]plugins.PluginDTO } func (pr fakePluginStore) Plugin(_ context.Context, pluginID string) (plugins.PluginDTO, bool) { p, exists := pr.plugins[pluginID] return p, exists } func (pr fakePluginStore) Plugins(_ context.Context, pluginTypes ...plugins.Type) []plugins.PluginDTO { var result []plugins.PluginDTO for _, v := range pr.plugins { for _, t := range pluginTypes { if v.Type == t { result = append(result, v) } } } return result } func setupSomeDataSourcePlugins(t *testing.T, uss *UsageStats) { t.Helper() uss.pluginStore = &fakePluginStore{ plugins: map[string]plugins.PluginDTO{ models.DS_ES: { Signature: "internal", }, models.DS_PROMETHEUS: { Signature: "internal", }, models.DS_GRAPHITE: { Signature: "internal", }, models.DS_MYSQL: { Signature: "internal", }, }, } } type httpResp struct { req *http.Request responseBuffer *bytes.Buffer err error } func createService(t *testing.T, cfg setting.Cfg) *UsageStats { t.Helper() sqlStore := sqlstore.InitTestDB(t) return &UsageStats{ Bus: bus.New(), Cfg: &cfg, SQLStore: sqlStore, externalMetrics: make([]usagestats.MetricsFunc, 0), pluginStore: &fakePluginStore{}, kvStore: kvstore.WithNamespace(kvstore.ProvideService(sqlStore), 0, "infra.usagestats"), log: log.New("infra.usagestats"), startTime: time.Now().Add(-1 * time.Minute), } }
pkg/infra/usagestats/service/usage_stats_test.go
1
https://github.com/grafana/grafana/commit/a1b8b5d123bde86fcfd7195c01b43d83a687d0ad
[ 0.9954908490180969, 0.11099424958229065, 0.00016401881293859333, 0.00017439611838199198, 0.3071947693824768 ]
{ "id": 1, "code_window": [ "\t\t\t\tDashboardsViewersCanAdmin: 3,\n", "\t\t\t\tDashboardsViewersCanEdit: 2,\n", "\t\t\t\tFoldersViewersCanAdmin: 1,\n", "\t\t\t\tFoldersViewersCanEdit: 5,\n", "\t\t\t}\n", "\t\t\tgetSystemStatsQuery = query\n", "\t\t\treturn nil\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tAPIKeys: 2,\n" ], "file_path": "pkg/infra/usagestats/service/usage_stats_test.go", "type": "add", "edit_start_line_idx": 81 }
import './plugins/all'; import './dashboard'; import './profile/all';
public/app/features/all.ts
0
https://github.com/grafana/grafana/commit/a1b8b5d123bde86fcfd7195c01b43d83a687d0ad
[ 0.00017470952298026532, 0.00017470952298026532, 0.00017470952298026532, 0.00017470952298026532, 0 ]
{ "id": 1, "code_window": [ "\t\t\t\tDashboardsViewersCanAdmin: 3,\n", "\t\t\t\tDashboardsViewersCanEdit: 2,\n", "\t\t\t\tFoldersViewersCanAdmin: 1,\n", "\t\t\t\tFoldersViewersCanEdit: 5,\n", "\t\t\t}\n", "\t\t\tgetSystemStatsQuery = query\n", "\t\t\treturn nil\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tAPIKeys: 2,\n" ], "file_path": "pkg/infra/usagestats/service/usage_stats_test.go", "type": "add", "edit_start_line_idx": 81 }
package models type SearchUserFilter interface { GetFilter(filterName string, params []string) Filter GetFilterList() map[string]FilterHandler } type WhereCondition struct { Condition string Params interface{} } type InCondition struct { Condition string Params interface{} } type JoinCondition struct { Operator string Table string Params string } type FilterHandler func(params []string) (Filter, error) type Filter interface { WhereCondition() *WhereCondition InCondition() *InCondition JoinCondition() *JoinCondition }
pkg/models/search_user_filter.go
0
https://github.com/grafana/grafana/commit/a1b8b5d123bde86fcfd7195c01b43d83a687d0ad
[ 0.0001761913881637156, 0.0001698341075098142, 0.0001664390292717144, 0.0001683529990259558, 0.00000390232617064612 ]
{ "id": 1, "code_window": [ "\t\t\t\tDashboardsViewersCanAdmin: 3,\n", "\t\t\t\tDashboardsViewersCanEdit: 2,\n", "\t\t\t\tFoldersViewersCanAdmin: 1,\n", "\t\t\t\tFoldersViewersCanEdit: 5,\n", "\t\t\t}\n", "\t\t\tgetSystemStatsQuery = query\n", "\t\t\treturn nil\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tAPIKeys: 2,\n" ], "file_path": "pkg/infra/usagestats/service/usage_stats_test.go", "type": "add", "edit_start_line_idx": 81 }
#!/usr/bin/env node const fs = require('fs'); const path = require('path'); let includeInternalScripts = false; const isLinkedMode = () => { // In circleci we are in linked mode. Detect by using the circle working directory, // rather than the present working directory. const pwd = process.env.CIRCLE_WORKING_DIRECTORY || process.env.PWD || process.cwd(); if (path.basename(pwd) === 'grafana-toolkit') { return true; } try { const resolvedPath = require.resolve('@grafana/toolkit'); return fs.lstatSync(resolvedPath).isSymbolicLink(); } catch { return false; } }; const entrypoint = () => { const entrypointBase = `${__dirname}/../src/cli/index`; const resolvedJsDir = path.resolve(`${entrypointBase}.js`); const resolvedTsDir = path.resolve(`${entrypointBase}.ts`); // IF we have a toolkit directory AND linked grafana toolkit AND the toolkit dir is a symbolic lik // THEN run everything in linked mode if (isLinkedMode() || !fs.existsSync(resolvedJsDir)) { console.log('Running in local/linked mode'); // This bin is used for cli executed internally var tsProjectPath = path.resolve(__dirname, '../tsconfig.json'); require('ts-node').register({ project: tsProjectPath, transpileOnly: true, }); includeInternalScripts = true; return resolvedTsDir; } // The default entrypoint must exist, return it now. return resolvedJsDir; }; require(entrypoint()).run(includeInternalScripts);
packages/grafana-toolkit/bin/grafana-toolkit.js
0
https://github.com/grafana/grafana/commit/a1b8b5d123bde86fcfd7195c01b43d83a687d0ad
[ 0.00017770615522749722, 0.00017157797992695123, 0.0001667475007707253, 0.00017118442337960005, 0.000003874491085298359 ]
{ "id": 2, "code_window": [ "\t\t\tassert.Equal(t, getSystemStatsQuery.Result.FoldersViewersCanEdit, metrics.Get(\"stats.folders_viewers_can_edit.count\").MustInt64())\n", "\t\t\tassert.Equal(t, getSystemStatsQuery.Result.FoldersViewersCanAdmin, metrics.Get(\"stats.folders_viewers_can_admin.count\").MustInt64())\n", "\t\t\tassert.Equal(t, 15, metrics.Get(\"stats.total_auth_token.count\").MustInt())\n", "\t\t\tassert.Equal(t, 5, metrics.Get(\"stats.avg_auth_token_per_user.count\").MustInt())\n", "\t\t\tassert.Equal(t, 16, metrics.Get(\"stats.dashboard_versions.count\").MustInt())\n", "\t\t\tassert.Equal(t, 17, metrics.Get(\"stats.annotations.count\").MustInt())\n", "\t\t\tassert.Equal(t, 18, metrics.Get(\"stats.alert_rules.count\").MustInt())\n", "\t\t\tassert.Equal(t, 19, metrics.Get(\"stats.library_panels.count\").MustInt())\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tassert.Equal(t, 2, metrics.Get(\"stats.api_keys.count\").MustInt())\n" ], "file_path": "pkg/infra/usagestats/service/usage_stats_test.go", "type": "add", "edit_start_line_idx": 346 }
//go:build integration // +build integration package sqlstore import ( "context" "fmt" "testing" "github.com/grafana/grafana/pkg/models" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestStatsDataAccess(t *testing.T) { sqlStore := InitTestDB(t) populateDB(t, sqlStore) t.Run("Get system stats should not results in error", func(t *testing.T) { query := models.GetSystemStatsQuery{} err := GetSystemStats(context.Background(), &query) require.NoError(t, err) assert.Equal(t, int64(3), query.Result.Users) assert.Equal(t, int64(0), query.Result.Editors) assert.Equal(t, int64(0), query.Result.Viewers) assert.Equal(t, int64(3), query.Result.Admins) assert.Equal(t, int64(0), query.Result.LibraryPanels) assert.Equal(t, int64(0), query.Result.LibraryVariables) }) t.Run("Get system user count stats should not results in error", func(t *testing.T) { query := models.GetSystemUserCountStatsQuery{} err := GetSystemUserCountStats(context.Background(), &query) assert.NoError(t, err) }) t.Run("Get datasource stats should not results in error", func(t *testing.T) { query := models.GetDataSourceStatsQuery{} err := GetDataSourceStats(context.Background(), &query) assert.NoError(t, err) }) t.Run("Get datasource access stats should not results in error", func(t *testing.T) { query := models.GetDataSourceAccessStatsQuery{} err := GetDataSourceAccessStats(context.Background(), &query) assert.NoError(t, err) }) t.Run("Get alert notifier stats should not results in error", func(t *testing.T) { query := models.GetAlertNotifierUsageStatsQuery{} err := GetAlertNotifiersUsageStats(context.Background(), &query) assert.NoError(t, err) }) t.Run("Get admin stats should not result in error", func(t *testing.T) { query := models.GetAdminStatsQuery{} err := GetAdminStats(context.Background(), &query) assert.NoError(t, err) }) } func populateDB(t *testing.T, sqlStore *SQLStore) { t.Helper() users := make([]models.User, 3) for i := range users { cmd := models.CreateUserCommand{ Email: fmt.Sprintf("usertest%[email protected]", i), Name: fmt.Sprintf("user name %v", i), Login: fmt.Sprintf("user_test_%v_login", i), OrgName: fmt.Sprintf("Org #%v", i), } user, err := sqlStore.CreateUser(context.Background(), cmd) require.NoError(t, err) users[i] = *user } // get 1st user's organisation getOrgByIdQuery := &models.GetOrgByIdQuery{Id: users[0].OrgId} err := GetOrgById(context.Background(), getOrgByIdQuery) require.NoError(t, err) org := getOrgByIdQuery.Result // add 2nd user as editor cmd := &models.AddOrgUserCommand{ OrgId: org.Id, UserId: users[1].Id, Role: models.ROLE_EDITOR, } err = sqlStore.AddOrgUser(context.Background(), cmd) require.NoError(t, err) // add 3rd user as viewer cmd = &models.AddOrgUserCommand{ OrgId: org.Id, UserId: users[2].Id, Role: models.ROLE_VIEWER, } err = sqlStore.AddOrgUser(context.Background(), cmd) require.NoError(t, err) // get 2nd user's organisation getOrgByIdQuery = &models.GetOrgByIdQuery{Id: users[1].OrgId} err = GetOrgById(context.Background(), getOrgByIdQuery) require.NoError(t, err) org = getOrgByIdQuery.Result // add 1st user as admin cmd = &models.AddOrgUserCommand{ OrgId: org.Id, UserId: users[0].Id, Role: models.ROLE_ADMIN, } err = sqlStore.AddOrgUser(context.Background(), cmd) require.NoError(t, err) // update 1st user last seen at updateUserLastSeenAtCmd := &models.UpdateUserLastSeenAtCommand{ UserId: users[0].Id, } err = UpdateUserLastSeenAt(context.Background(), updateUserLastSeenAtCmd) require.NoError(t, err) // force renewal of user stats err = updateUserRoleCountsIfNecessary(context.Background(), true) require.NoError(t, err) }
pkg/services/sqlstore/stats_test.go
1
https://github.com/grafana/grafana/commit/a1b8b5d123bde86fcfd7195c01b43d83a687d0ad
[ 0.0030415852088481188, 0.0003932527033612132, 0.0001612260239198804, 0.0001666337193455547, 0.00076474086381495 ]
{ "id": 2, "code_window": [ "\t\t\tassert.Equal(t, getSystemStatsQuery.Result.FoldersViewersCanEdit, metrics.Get(\"stats.folders_viewers_can_edit.count\").MustInt64())\n", "\t\t\tassert.Equal(t, getSystemStatsQuery.Result.FoldersViewersCanAdmin, metrics.Get(\"stats.folders_viewers_can_admin.count\").MustInt64())\n", "\t\t\tassert.Equal(t, 15, metrics.Get(\"stats.total_auth_token.count\").MustInt())\n", "\t\t\tassert.Equal(t, 5, metrics.Get(\"stats.avg_auth_token_per_user.count\").MustInt())\n", "\t\t\tassert.Equal(t, 16, metrics.Get(\"stats.dashboard_versions.count\").MustInt())\n", "\t\t\tassert.Equal(t, 17, metrics.Get(\"stats.annotations.count\").MustInt())\n", "\t\t\tassert.Equal(t, 18, metrics.Get(\"stats.alert_rules.count\").MustInt())\n", "\t\t\tassert.Equal(t, 19, metrics.Get(\"stats.library_panels.count\").MustInt())\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tassert.Equal(t, 2, metrics.Get(\"stats.api_keys.count\").MustInt())\n" ], "file_path": "pkg/infra/usagestats/service/usage_stats_test.go", "type": "add", "edit_start_line_idx": 346 }
import config from 'app/core/config'; export function getThemeColor(dark: string, light: string): string { return config.bootData.user.lightTheme ? light : dark; }
public/app/core/utils/colors.ts
0
https://github.com/grafana/grafana/commit/a1b8b5d123bde86fcfd7195c01b43d83a687d0ad
[ 0.00017384324746672064, 0.00017384324746672064, 0.00017384324746672064, 0.00017384324746672064, 0 ]
{ "id": 2, "code_window": [ "\t\t\tassert.Equal(t, getSystemStatsQuery.Result.FoldersViewersCanEdit, metrics.Get(\"stats.folders_viewers_can_edit.count\").MustInt64())\n", "\t\t\tassert.Equal(t, getSystemStatsQuery.Result.FoldersViewersCanAdmin, metrics.Get(\"stats.folders_viewers_can_admin.count\").MustInt64())\n", "\t\t\tassert.Equal(t, 15, metrics.Get(\"stats.total_auth_token.count\").MustInt())\n", "\t\t\tassert.Equal(t, 5, metrics.Get(\"stats.avg_auth_token_per_user.count\").MustInt())\n", "\t\t\tassert.Equal(t, 16, metrics.Get(\"stats.dashboard_versions.count\").MustInt())\n", "\t\t\tassert.Equal(t, 17, metrics.Get(\"stats.annotations.count\").MustInt())\n", "\t\t\tassert.Equal(t, 18, metrics.Get(\"stats.alert_rules.count\").MustInt())\n", "\t\t\tassert.Equal(t, 19, metrics.Get(\"stats.library_panels.count\").MustInt())\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tassert.Equal(t, 2, metrics.Get(\"stats.api_keys.count\").MustInt())\n" ], "file_path": "pkg/infra/usagestats/service/usage_stats_test.go", "type": "add", "edit_start_line_idx": 346 }
module.exports = { ...require('@grafana/toolkit/src/config/prettier.plugin.config.json'), };
.prettierrc.js
0
https://github.com/grafana/grafana/commit/a1b8b5d123bde86fcfd7195c01b43d83a687d0ad
[ 0.00016944886010605842, 0.00016944886010605842, 0.00016944886010605842, 0.00016944886010605842, 0 ]
{ "id": 2, "code_window": [ "\t\t\tassert.Equal(t, getSystemStatsQuery.Result.FoldersViewersCanEdit, metrics.Get(\"stats.folders_viewers_can_edit.count\").MustInt64())\n", "\t\t\tassert.Equal(t, getSystemStatsQuery.Result.FoldersViewersCanAdmin, metrics.Get(\"stats.folders_viewers_can_admin.count\").MustInt64())\n", "\t\t\tassert.Equal(t, 15, metrics.Get(\"stats.total_auth_token.count\").MustInt())\n", "\t\t\tassert.Equal(t, 5, metrics.Get(\"stats.avg_auth_token_per_user.count\").MustInt())\n", "\t\t\tassert.Equal(t, 16, metrics.Get(\"stats.dashboard_versions.count\").MustInt())\n", "\t\t\tassert.Equal(t, 17, metrics.Get(\"stats.annotations.count\").MustInt())\n", "\t\t\tassert.Equal(t, 18, metrics.Get(\"stats.alert_rules.count\").MustInt())\n", "\t\t\tassert.Equal(t, 19, metrics.Get(\"stats.library_panels.count\").MustInt())\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tassert.Equal(t, 2, metrics.Get(\"stats.api_keys.count\").MustInt())\n" ], "file_path": "pkg/infra/usagestats/service/usage_stats_test.go", "type": "add", "edit_start_line_idx": 346 }
{ "__inputs": [ { "name": "DS_AZURE_MONITOR", "label": "Azure Monitor", "description": "", "type": "datasource", "pluginId": "grafana-azure-monitor-datasource", "pluginName": "Azure Monitor" } ], "__elements": [], "__requires": [ { "type": "grafana", "id": "grafana", "name": "Grafana", "version": "8.3.0-pre" }, { "type": "datasource", "id": "grafana-azure-monitor-datasource", "name": "Azure Monitor", "version": "0.3.0" }, { "type": "panel", "id": "table", "name": "Table", "version": "" } ], "annotations": { "list": [ { "builtIn": 1, "datasource": "-- Grafana --", "enable": true, "hide": true, "iconColor": "rgba(0, 211, 255, 1)", "name": "Annotations & Alerts", "target": { "limit": 100, "matchAny": false, "tags": [], "type": "dashboard" }, "type": "dashboard" } ] }, "description": "A summary of all alerts for the subscription and other filters selected", "editable": true, "fiscalYearStartMonth": 0, "gnetId": null, "graphTooltip": 0, "id": null, "iteration": 1634314135767, "links": [], "liveNow": false, "panels": [ { "datasource": "${DS_AZURE_MONITOR}", "fieldConfig": { "defaults": { "color": { "mode": "continuous-BlYlRd" }, "custom": { "align": "center", "displayMode": "auto", "filterable": true }, "links": [], "mappings": [], "thresholds": { "mode": "absolute", "steps": [ { "color": "green", "value": null }, { "color": "red", "value": 80.0002 } ] } }, "overrides": [ { "matcher": { "id": "byName", "options": "properties_essentials_severity" }, "properties": [ { "id": "mappings", "value": [ { "options": { "\"Sev0\"": { "color": "red", "index": 4, "text": "0 - Critical" }, "\"Sev1\"": { "color": "orange", "index": 3, "text": "1 - Error" }, "\"Sev2\"": { "color": "yellow", "index": 2, "text": "2 - Warning" }, "\"Sev3\"": { "color": "blue", "index": 1, "text": "3 - Informational" }, "\"Sev4\"": { "color": "#8F3BB8", "index": 0, "text": "4 - Verbose" } }, "type": "value" } ] }, { "id": "custom.displayMode", "value": "color-background-solid" }, { "id": "displayName", "value": "Severity" } ] }, { "matcher": { "id": "byName", "options": "name" }, "properties": [ { "id": "displayName", "value": "Name" }, { "id": "custom.displayMode", "value": "color-text" }, { "id": "links", "value": [ { "targetBlank": true, "title": "test title", "url": "https://ms.portal.azure.com/#blade/Microsoft_Azure_Monitoring/AlertDetailsTemplateBlade/alertId/%2Fsubscriptions%2F${sub}%2Fresourcegroups%2F${rg}%2Fproviders%2Fmicrosoft.insights%2Fcomponents%2F${res}%2Fproviders%2FMicrosoft.AlertsManagement%2Falerts%2F${__data.fields.alertId}" } ] }, { "id": "mappings", "value": [] } ] }, { "matcher": { "id": "byName", "options": "properties_essentials_monitorCondition" }, "properties": [ { "id": "displayName", "value": "Monitor condition" }, { "id": "mappings", "value": [ { "options": { "Fired": { "color": "orange", "index": 1 }, "Resolved": { "color": "green", "index": 0 } }, "type": "value" } ] }, { "id": "custom.displayMode", "value": "basic" } ] }, { "matcher": { "id": "byName", "options": "properties_essentials_alertState" }, "properties": [ { "id": "displayName", "value": "Alert state" } ] }, { "matcher": { "id": "byName", "options": "properties_essentials_targetResourceName" }, "properties": [ { "id": "displayName", "value": "Affected resource" }, { "id": "custom.displayMode", "value": "color-text" } ] }, { "matcher": { "id": "byName", "options": "properties_essentials_monitorService" }, "properties": [ { "id": "displayName", "value": "Monitor service" } ] }, { "matcher": { "id": "byName", "options": "properties_essentials_signalType" }, "properties": [ { "id": "displayName", "value": "Signal type" } ] }, { "matcher": { "id": "byName", "options": "properties_essentials_lastModifiedDateTime" }, "properties": [ { "id": "displayName", "value": "Fired time" }, { "id": "unit", "value": "dateTimeAsUS" } ] }, { "matcher": { "id": "byName", "options": "SubName" }, "properties": [ { "id": "displayName", "value": "Subscription name" } ] }, { "matcher": { "id": "byName", "options": "Name" }, "properties": [ { "id": "custom.width", "value": 423 } ] }, { "matcher": { "id": "byName", "options": "Subscription name" }, "properties": [ { "id": "custom.width", "value": 266 } ] } ] }, "gridPos": { "h": 16, "w": 24, "x": 0, "y": 0 }, "id": 2, "links": [], "options": { "footer": { "fields": "", "reducer": ["sum"], "show": false }, "frameIndex": 0, "showHeader": true, "sortBy": [] }, "pluginVersion": "8.3.0-pre", "targets": [ { "appInsights": { "dimension": [], "metricName": "select", "timeGrain": "auto" }, "azureLogAnalytics": { "query": "//change this example to create your own time series query\n<table name> //the table to query (e.g. Usage, Heartbeat, Perf)\n| where $__timeFilter(TimeGenerated) //this is a macro used to show the full chart’s time range, choose the datetime column here\n| summarize count() by <group by column>, bin(TimeGenerated, $__interval) //change “group by column” to a column in your table, such as “Computer”. The $__interval macro is used to auto-select the time grain. Can also use 1h, 5m etc.\n| order by TimeGenerated asc", "resultFormat": "time_series" }, "azureMonitor": { "aggOptions": [], "dimensionFilter": "*", "dimensionFilters": [], "timeGrain": "auto", "timeGrains": [], "top": "10" }, "azureResourceGraph": { "query": "alertsmanagementresources\r\n| join kind=leftouter (ResourceContainers | where type=='microsoft.resources/subscriptions' | project SubName=name, subscriptionId) on subscriptionId\r\n| where type == \"microsoft.alertsmanagement/alerts\"\r\n| where subscriptionId == \"$sub\" and properties.essentials.targetResourceGroup in ($rg) and properties.essentials.monitorCondition in ($mc)\r\nand properties.essentials.alertState in ($as) and properties.essentials.severity in ($sev)\r\nand todatetime(properties.essentials.lastModifiedDateTime) >= $__timeFrom and todatetime(properties.essentials.lastModifiedDateTime) <= $__timeTo\r\n| parse id with * \"alerts/\" alertId\r\n| project name, properties.essentials.severity, tostring(properties.essentials.monitorCondition), \r\ntostring(properties.essentials.alertState), tostring(properties.essentials.targetResourceName),\r\n tostring(properties.essentials.monitorService), tostring(properties.essentials.signalType),\r\n todatetime(properties.essentials.lastModifiedDateTime), tostring(SubName), alertId, id\r\n", "resultFormat": "table" }, "insightsAnalytics": { "query": "", "resultFormat": "time_series" }, "queryType": "Azure Resource Graph", "refId": "A", "subscription": "", "subscriptions": [] } ], "title": "V1 Alerts", "transformations": [ { "id": "filterFieldsByName", "options": { "include": { "names": [ "alertId", "name", "properties_essentials_severity", "properties_essentials_monitorCondition", "properties_essentials_alertState", "properties_essentials_targetResourceName", "properties_essentials_monitorService", "properties_essentials_signalType", "properties_essentials_lastModifiedDateTime", "SubName" ] } } }, { "id": "organize", "options": { "excludeByName": { "alertId": false }, "indexByName": {}, "renameByName": {} } } ], "transparent": true, "type": "table" } ], "refresh": "", "schemaVersion": 31, "style": "dark", "tags": [], "templating": { "list": [ { "allValue": null, "current": {}, "datasource": "${DS_AZURE_MONITOR}", "definition": "subscriptions()", "description": null, "error": null, "hide": 0, "includeAll": false, "label": "Subscription", "multi": false, "name": "sub", "options": [], "query": "subscriptions()", "refresh": 1, "regex": "", "skipUrlSync": false, "sort": 0, "type": "query" }, { "allValue": null, "current": {}, "datasource": "${DS_AZURE_MONITOR}", "definition": "ResourceGroups($sub)", "description": null, "error": null, "hide": 0, "includeAll": false, "label": "Resource group", "multi": true, "name": "rg", "options": [], "query": "ResourceGroups($sub)", "refresh": 1, "regex": "", "skipUrlSync": false, "sort": 0, "type": "query" }, { "allValue": null, "current": { "selected": false, "text": ["Fired", "Resolved"], "value": ["Fired", "Resolved"] }, "description": null, "error": null, "hide": 0, "includeAll": false, "label": "Monitor Condition", "multi": true, "name": "mc", "options": [ { "selected": true, "text": "Fired", "value": "Fired" }, { "selected": true, "text": "Resolved", "value": "Resolved" } ], "query": "Fired, Resolved", "queryValue": "", "skipUrlSync": false, "type": "custom" }, { "allValue": null, "current": { "selected": false, "text": ["New", "Acknowledged", "Closed"], "value": ["New", "Acknowledged", "Closed"] }, "description": null, "error": null, "hide": 0, "includeAll": false, "label": "Alert State", "multi": true, "name": "as", "options": [ { "selected": true, "text": "New", "value": "New" }, { "selected": true, "text": "Acknowledged", "value": "Acknowledged" }, { "selected": true, "text": "Closed", "value": "Closed" } ], "query": "New, Acknowledged, Closed", "queryValue": "", "skipUrlSync": false, "type": "custom" }, { "allValue": null, "current": { "selected": false, "text": ["1 - Error", "0 - Critical", "2 - Warning", "3 - Informational", "4 - Verbose"], "value": ["Sev1", "Sev0", "Sev2", "Sev3", "Sev4"] }, "description": null, "error": null, "hide": 0, "includeAll": false, "label": "Severity", "multi": true, "name": "sev", "options": [ { "selected": true, "text": "0 - Critical", "value": "Sev0" }, { "selected": true, "text": "1 - Error", "value": "Sev1" }, { "selected": true, "text": "2 - Warning", "value": "Sev2" }, { "selected": true, "text": "3 - Informational", "value": "Sev3" }, { "selected": true, "text": "4 - Verbose", "value": "Sev4" } ], "query": "0 - Critical : Sev0, 1 - Error : Sev1, 2 - Warning : Sev2, 3 - Informational : Sev3, 4 - Verbose : Sev4", "queryValue": "", "skipUrlSync": false, "type": "custom" } ] }, "time": { "from": "now-30d", "to": "now" }, "timepicker": { "hidden": false, "refresh_intervals": ["30m", "1h", "12h", "24h", "3d", "7d", "30d"] }, "timezone": "", "title": "Azure Alert Consumption", "uid": "5DLst5N7k", "version": 1 }
public/app/plugins/datasource/grafana-azure-monitor-datasource/dashboards/v1Alerts.json
0
https://github.com/grafana/grafana/commit/a1b8b5d123bde86fcfd7195c01b43d83a687d0ad
[ 0.00017652618407737464, 0.0001719204883556813, 0.00016447000962216407, 0.00017213121464010328, 0.0000026925881684292108 ]
{ "id": 3, "code_window": [ "\tFolderPermissions int64\n", "\tFolders int64\n", "\tProvisionedDashboards int64\n", "\tAuthTokens int64\n", "\tDashboardVersions int64\n", "\tAnnotations int64\n", "\tAlertRules int64\n", "\tLibraryPanels int64\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tAPIKeys int64 `xorm:\"api_keys\"`\n" ], "file_path": "pkg/models/stats.go", "type": "add", "edit_start_line_idx": 20 }
package service import ( "bytes" "context" "errors" "io/ioutil" "net/http" "net/http/httptest" "runtime" "testing" "time" "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/components/simplejson" "github.com/grafana/grafana/pkg/infra/kvstore" "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/infra/usagestats" "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/plugins" "github.com/grafana/grafana/pkg/services/sqlstore" "github.com/grafana/grafana/pkg/setting" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) // This is to ensure that the interface contract is held by the implementation func Test_InterfaceContractValidity(t *testing.T) { newUsageStats := func() usagestats.Service { return &UsageStats{} } v, ok := newUsageStats().(*UsageStats) assert.NotNil(t, v) assert.True(t, ok) } func TestMetrics(t *testing.T) { t.Run("When sending usage stats", func(t *testing.T) { uss := createService(t, setting.Cfg{}) setupSomeDataSourcePlugins(t, uss) var getSystemStatsQuery *models.GetSystemStatsQuery uss.Bus.AddHandlerCtx(func(ctx context.Context, query *models.GetSystemStatsQuery) error { query.Result = &models.SystemStats{ Dashboards: 1, Datasources: 2, Users: 3, Admins: 31, Editors: 32, Viewers: 33, ActiveUsers: 4, ActiveAdmins: 21, ActiveEditors: 22, ActiveViewers: 23, ActiveSessions: 24, DailyActiveUsers: 25, DailyActiveAdmins: 26, DailyActiveEditors: 27, DailyActiveViewers: 28, DailyActiveSessions: 29, Orgs: 5, Playlists: 6, Alerts: 7, Stars: 8, Folders: 9, DashboardPermissions: 10, FolderPermissions: 11, ProvisionedDashboards: 12, Snapshots: 13, Teams: 14, AuthTokens: 15, DashboardVersions: 16, Annotations: 17, AlertRules: 18, LibraryPanels: 19, LibraryVariables: 20, DashboardsViewersCanAdmin: 3, DashboardsViewersCanEdit: 2, FoldersViewersCanAdmin: 1, FoldersViewersCanEdit: 5, } getSystemStatsQuery = query return nil }) var getDataSourceStatsQuery *models.GetDataSourceStatsQuery uss.Bus.AddHandlerCtx(func(ctx context.Context, query *models.GetDataSourceStatsQuery) error { query.Result = []*models.DataSourceStats{ { Type: models.DS_ES, Count: 9, }, { Type: models.DS_PROMETHEUS, Count: 10, }, { Type: "unknown_ds", Count: 11, }, { Type: "unknown_ds2", Count: 12, }, } getDataSourceStatsQuery = query return nil }) var getESDatasSourcesQuery *models.GetDataSourcesByTypeQuery uss.Bus.AddHandlerCtx(func(ctx context.Context, query *models.GetDataSourcesByTypeQuery) error { query.Result = []*models.DataSource{ { JsonData: simplejson.NewFromAny(map[string]interface{}{ "esVersion": 2, }), }, { JsonData: simplejson.NewFromAny(map[string]interface{}{ "esVersion": 2, }), }, { JsonData: simplejson.NewFromAny(map[string]interface{}{ "esVersion": 70, }), }, } getESDatasSourcesQuery = query return nil }) var getDataSourceAccessStatsQuery *models.GetDataSourceAccessStatsQuery uss.Bus.AddHandlerCtx(func(ctx context.Context, query *models.GetDataSourceAccessStatsQuery) error { query.Result = []*models.DataSourceAccessStats{ { Type: models.DS_ES, Access: "direct", Count: 1, }, { Type: models.DS_ES, Access: "proxy", Count: 2, }, { Type: models.DS_PROMETHEUS, Access: "proxy", Count: 3, }, { Type: "unknown_ds", Access: "proxy", Count: 4, }, { Type: "unknown_ds2", Access: "", Count: 5, }, { Type: "unknown_ds3", Access: "direct", Count: 6, }, { Type: "unknown_ds4", Access: "direct", Count: 7, }, { Type: "unknown_ds5", Access: "proxy", Count: 8, }, } getDataSourceAccessStatsQuery = query return nil }) var getAlertNotifierUsageStatsQuery *models.GetAlertNotifierUsageStatsQuery uss.Bus.AddHandlerCtx(func(ctx context.Context, query *models.GetAlertNotifierUsageStatsQuery) error { query.Result = []*models.NotifierUsageStats{ { Type: "slack", Count: 1, }, { Type: "webhook", Count: 2, }, } getAlertNotifierUsageStatsQuery = query return nil }) createConcurrentTokens(t, uss.SQLStore) uss.oauthProviders = map[string]bool{ "github": true, "gitlab": true, "azuread": true, "google": true, "generic_oauth": true, "grafana_com": true, } err := uss.sendUsageStats(context.Background()) require.NoError(t, err) t.Run("Given reporting not enabled and sending usage stats", func(t *testing.T) { origSendUsageStats := sendUsageStats t.Cleanup(func() { sendUsageStats = origSendUsageStats }) statsSent := false sendUsageStats = func(uss *UsageStats, b *bytes.Buffer) { statsSent = true } uss.Cfg.ReportingEnabled = false err := uss.sendUsageStats(context.Background()) require.NoError(t, err) require.False(t, statsSent) assert.Nil(t, getSystemStatsQuery) assert.Nil(t, getDataSourceStatsQuery) assert.Nil(t, getDataSourceAccessStatsQuery) assert.Nil(t, getESDatasSourcesQuery) }) t.Run("Given reporting enabled, stats should be gathered and sent to HTTP endpoint", func(t *testing.T) { origCfg := uss.Cfg t.Cleanup(func() { uss.Cfg = origCfg }) uss.Cfg = &setting.Cfg{ ReportingEnabled: true, BuildVersion: "5.0.0", AnonymousEnabled: true, BasicAuthEnabled: true, LDAPEnabled: true, AuthProxyEnabled: true, Packaging: "deb", ReportingDistributor: "hosted-grafana", } ch := make(chan httpResp) ticker := time.NewTicker(2 * time.Second) ts := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { buf, err := ioutil.ReadAll(r.Body) if err != nil { t.Logf("Fake HTTP handler received an error: %s", err.Error()) ch <- httpResp{ err: err, } return } require.NoError(t, err, "Failed to read response body, err=%v", err) t.Logf("Fake HTTP handler received a response") ch <- httpResp{ responseBuffer: bytes.NewBuffer(buf), req: r, } })) t.Cleanup(ts.Close) t.Cleanup(func() { close(ch) }) usageStatsURL = ts.URL err := uss.sendUsageStats(context.Background()) require.NoError(t, err) // Wait for fake HTTP server to receive a request var resp httpResp select { case resp = <-ch: require.NoError(t, resp.err, "Fake server experienced an error") case <-ticker.C: t.Fatalf("Timed out waiting for HTTP request") } t.Logf("Received response from fake HTTP server: %+v\n", resp) assert.NotNil(t, getSystemStatsQuery) assert.NotNil(t, getDataSourceStatsQuery) assert.NotNil(t, getESDatasSourcesQuery) assert.NotNil(t, getDataSourceAccessStatsQuery) assert.NotNil(t, getAlertNotifierUsageStatsQuery) assert.NotNil(t, resp.req) assert.Equal(t, http.MethodPost, resp.req.Method) assert.Equal(t, "application/json", resp.req.Header.Get("Content-Type")) require.NotNil(t, resp.responseBuffer) j, err := simplejson.NewFromReader(resp.responseBuffer) require.NoError(t, err) assert.Equal(t, "5_0_0", j.Get("version").MustString()) assert.Equal(t, runtime.GOOS, j.Get("os").MustString()) assert.Equal(t, runtime.GOARCH, j.Get("arch").MustString()) usageId := uss.GetUsageStatsId(context.Background()) assert.NotEmpty(t, usageId) assert.Equal(t, usageId, j.Get("usageStatsId").MustString()) metrics := j.Get("metrics") assert.Equal(t, getSystemStatsQuery.Result.Dashboards, metrics.Get("stats.dashboards.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.Users, metrics.Get("stats.users.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.Admins, metrics.Get("stats.admins.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.Editors, metrics.Get("stats.editors.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.Viewers, metrics.Get("stats.viewers.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.Orgs, metrics.Get("stats.orgs.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.Playlists, metrics.Get("stats.playlist.count").MustInt64()) assert.Equal(t, uss.appCount(context.Background()), metrics.Get("stats.plugins.apps.count").MustInt()) assert.Equal(t, uss.panelCount(context.Background()), metrics.Get("stats.plugins.panels.count").MustInt()) assert.Equal(t, uss.dataSourceCount(context.Background()), metrics.Get("stats.plugins.datasources.count").MustInt()) assert.Equal(t, getSystemStatsQuery.Result.Alerts, metrics.Get("stats.alerts.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.ActiveUsers, metrics.Get("stats.active_users.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.ActiveAdmins, metrics.Get("stats.active_admins.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.ActiveEditors, metrics.Get("stats.active_editors.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.ActiveViewers, metrics.Get("stats.active_viewers.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.ActiveSessions, metrics.Get("stats.active_sessions.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.DailyActiveUsers, metrics.Get("stats.daily_active_users.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.DailyActiveAdmins, metrics.Get("stats.daily_active_admins.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.DailyActiveEditors, metrics.Get("stats.daily_active_editors.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.DailyActiveViewers, metrics.Get("stats.daily_active_viewers.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.DailyActiveSessions, metrics.Get("stats.daily_active_sessions.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.Datasources, metrics.Get("stats.datasources.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.Stars, metrics.Get("stats.stars.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.Folders, metrics.Get("stats.folders.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.DashboardPermissions, metrics.Get("stats.dashboard_permissions.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.FolderPermissions, metrics.Get("stats.folder_permissions.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.ProvisionedDashboards, metrics.Get("stats.provisioned_dashboards.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.Snapshots, metrics.Get("stats.snapshots.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.Teams, metrics.Get("stats.teams.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.DashboardsViewersCanEdit, metrics.Get("stats.dashboards_viewers_can_edit.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.DashboardsViewersCanAdmin, metrics.Get("stats.dashboards_viewers_can_admin.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.FoldersViewersCanEdit, metrics.Get("stats.folders_viewers_can_edit.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.FoldersViewersCanAdmin, metrics.Get("stats.folders_viewers_can_admin.count").MustInt64()) assert.Equal(t, 15, metrics.Get("stats.total_auth_token.count").MustInt()) assert.Equal(t, 5, metrics.Get("stats.avg_auth_token_per_user.count").MustInt()) assert.Equal(t, 16, metrics.Get("stats.dashboard_versions.count").MustInt()) assert.Equal(t, 17, metrics.Get("stats.annotations.count").MustInt()) assert.Equal(t, 18, metrics.Get("stats.alert_rules.count").MustInt()) assert.Equal(t, 19, metrics.Get("stats.library_panels.count").MustInt()) assert.Equal(t, 20, metrics.Get("stats.library_variables.count").MustInt()) assert.Equal(t, 0, metrics.Get("stats.live_users.count").MustInt()) assert.Equal(t, 0, metrics.Get("stats.live_clients.count").MustInt()) assert.Equal(t, 9, metrics.Get("stats.ds."+models.DS_ES+".count").MustInt()) assert.Equal(t, 10, metrics.Get("stats.ds."+models.DS_PROMETHEUS+".count").MustInt()) assert.Equal(t, 2, metrics.Get("stats.ds."+models.DS_ES+".v2.count").MustInt()) assert.Equal(t, 1, metrics.Get("stats.ds."+models.DS_ES+".v70.count").MustInt()) assert.Equal(t, 11+12, metrics.Get("stats.ds.other.count").MustInt()) assert.Equal(t, 1, metrics.Get("stats.ds_access."+models.DS_ES+".direct.count").MustInt()) assert.Equal(t, 2, metrics.Get("stats.ds_access."+models.DS_ES+".proxy.count").MustInt()) assert.Equal(t, 3, metrics.Get("stats.ds_access."+models.DS_PROMETHEUS+".proxy.count").MustInt()) assert.Equal(t, 6+7, metrics.Get("stats.ds_access.other.direct.count").MustInt()) assert.Equal(t, 4+8, metrics.Get("stats.ds_access.other.proxy.count").MustInt()) assert.Equal(t, 1, metrics.Get("stats.alert_notifiers.slack.count").MustInt()) assert.Equal(t, 2, metrics.Get("stats.alert_notifiers.webhook.count").MustInt()) assert.Equal(t, 1, metrics.Get("stats.auth_enabled.anonymous.count").MustInt()) assert.Equal(t, 1, metrics.Get("stats.auth_enabled.basic_auth.count").MustInt()) assert.Equal(t, 1, metrics.Get("stats.auth_enabled.ldap.count").MustInt()) assert.Equal(t, 1, metrics.Get("stats.auth_enabled.auth_proxy.count").MustInt()) assert.Equal(t, 1, metrics.Get("stats.auth_enabled.oauth_github.count").MustInt()) assert.Equal(t, 1, metrics.Get("stats.auth_enabled.oauth_gitlab.count").MustInt()) assert.Equal(t, 1, metrics.Get("stats.auth_enabled.oauth_google.count").MustInt()) assert.Equal(t, 1, metrics.Get("stats.auth_enabled.oauth_azuread.count").MustInt()) assert.Equal(t, 1, metrics.Get("stats.auth_enabled.oauth_generic_oauth.count").MustInt()) assert.Equal(t, 1, metrics.Get("stats.auth_enabled.oauth_grafana_com.count").MustInt()) assert.Equal(t, 1, metrics.Get("stats.packaging.deb.count").MustInt()) assert.Equal(t, 1, metrics.Get("stats.distributor.hosted-grafana.count").MustInt()) assert.Equal(t, 1, metrics.Get("stats.auth_token_per_user_le_3").MustInt()) assert.Equal(t, 2, metrics.Get("stats.auth_token_per_user_le_6").MustInt()) assert.Equal(t, 3, metrics.Get("stats.auth_token_per_user_le_9").MustInt()) assert.Equal(t, 4, metrics.Get("stats.auth_token_per_user_le_12").MustInt()) assert.Equal(t, 5, metrics.Get("stats.auth_token_per_user_le_15").MustInt()) assert.Equal(t, 6, metrics.Get("stats.auth_token_per_user_le_inf").MustInt()) assert.LessOrEqual(t, 60, metrics.Get("stats.uptime").MustInt()) assert.Greater(t, 70, metrics.Get("stats.uptime").MustInt()) }) }) t.Run("When updating total stats", func(t *testing.T) { uss := createService(t, setting.Cfg{}) uss.Cfg.MetricsEndpointEnabled = true uss.Cfg.MetricsEndpointDisableTotalStats = false getSystemStatsWasCalled := false uss.Bus.AddHandlerCtx(func(ctx context.Context, query *models.GetSystemStatsQuery) error { query.Result = &models.SystemStats{} getSystemStatsWasCalled = true return nil }) t.Run("When metrics is disabled and total stats is enabled, stats should not be updated", func(t *testing.T) { uss.Cfg.MetricsEndpointEnabled = false uss.Cfg.MetricsEndpointDisableTotalStats = false uss.updateTotalStats(context.Background()) assert.False(t, getSystemStatsWasCalled) }) t.Run("When metrics is enabled and total stats is disabled, stats should not be updated", func(t *testing.T) { uss.Cfg.MetricsEndpointEnabled = true uss.Cfg.MetricsEndpointDisableTotalStats = true uss.updateTotalStats(context.Background()) assert.False(t, getSystemStatsWasCalled) }) t.Run("When metrics is disabled and total stats is disabled, stats should not be updated", func(t *testing.T) { uss.Cfg.MetricsEndpointEnabled = false uss.Cfg.MetricsEndpointDisableTotalStats = true uss.updateTotalStats(context.Background()) assert.False(t, getSystemStatsWasCalled) }) t.Run("When metrics is enabled and total stats is enabled, stats should be updated", func(t *testing.T) { uss.Cfg.MetricsEndpointEnabled = true uss.Cfg.MetricsEndpointDisableTotalStats = false uss.updateTotalStats(context.Background()) assert.True(t, getSystemStatsWasCalled) }) }) t.Run("When registering a metric", func(t *testing.T) { uss := createService(t, setting.Cfg{}) metricName := "stats.test_metric.count" t.Run("Adds a new metric to the external metrics", func(t *testing.T) { uss.RegisterMetricsFunc(func(context.Context) (map[string]interface{}, error) { return map[string]interface{}{metricName: 1}, nil }) metrics, err := uss.externalMetrics[0](context.Background()) require.NoError(t, err) assert.Equal(t, map[string]interface{}{metricName: 1}, metrics) }) }) t.Run("When getting usage report", func(t *testing.T) { uss := createService(t, setting.Cfg{}) metricName := "stats.test_metric.count" uss.Bus.AddHandlerCtx(func(ctx context.Context, query *models.GetSystemStatsQuery) error { query.Result = &models.SystemStats{} return nil }) uss.Bus.AddHandlerCtx(func(ctx context.Context, query *models.GetDataSourceStatsQuery) error { query.Result = []*models.DataSourceStats{} return nil }) uss.Bus.AddHandlerCtx(func(ctx context.Context, query *models.GetDataSourcesByTypeQuery) error { query.Result = []*models.DataSource{} return nil }) uss.Bus.AddHandlerCtx(func(ctx context.Context, query *models.GetDataSourceAccessStatsQuery) error { query.Result = []*models.DataSourceAccessStats{} return nil }) uss.Bus.AddHandlerCtx(func(ctx context.Context, query *models.GetAlertNotifierUsageStatsQuery) error { query.Result = []*models.NotifierUsageStats{} return nil }) createConcurrentTokens(t, uss.SQLStore) t.Run("Should include metrics for concurrent users", func(t *testing.T) { report, err := uss.GetUsageReport(context.Background()) require.NoError(t, err) assert.Equal(t, int32(1), report.Metrics["stats.auth_token_per_user_le_3"]) assert.Equal(t, int32(2), report.Metrics["stats.auth_token_per_user_le_6"]) assert.Equal(t, int32(3), report.Metrics["stats.auth_token_per_user_le_9"]) assert.Equal(t, int32(4), report.Metrics["stats.auth_token_per_user_le_12"]) assert.Equal(t, int32(5), report.Metrics["stats.auth_token_per_user_le_15"]) assert.Equal(t, int32(6), report.Metrics["stats.auth_token_per_user_le_inf"]) }) t.Run("Should include external metrics", func(t *testing.T) { uss.RegisterMetricsFunc(func(context.Context) (map[string]interface{}, error) { return map[string]interface{}{metricName: 1}, nil }) report, err := uss.GetUsageReport(context.Background()) require.NoError(t, err, "Expected no error") metric := report.Metrics[metricName] assert.Equal(t, 1, metric) }) }) t.Run("When registering external metrics", func(t *testing.T) { uss := createService(t, setting.Cfg{}) metrics := map[string]interface{}{"stats.test_metric.count": 1, "stats.test_metric_second.count": 2} extMetricName := "stats.test_external_metric.count" uss.RegisterMetricsFunc(func(context.Context) (map[string]interface{}, error) { return map[string]interface{}{extMetricName: 1}, nil }) uss.registerExternalMetrics(context.Background(), metrics) assert.Equal(t, 1, metrics[extMetricName]) t.Run("When loading a metric results to an error", func(t *testing.T) { uss.RegisterMetricsFunc(func(context.Context) (map[string]interface{}, error) { return map[string]interface{}{extMetricName: 1}, nil }) extErrorMetricName := "stats.test_external_metric_error.count" t.Run("Should not add it to metrics", func(t *testing.T) { uss.RegisterMetricsFunc(func(context.Context) (map[string]interface{}, error) { return map[string]interface{}{extErrorMetricName: 1}, errors.New("some error") }) uss.registerExternalMetrics(context.Background(), metrics) extErrorMetric := metrics[extErrorMetricName] extMetric := metrics[extMetricName] require.Nil(t, extErrorMetric, "Invalid metric should not be added") assert.Equal(t, 1, extMetric) assert.Len(t, metrics, 3, "Expected only one available metric") }) }) }) } type fakePluginStore struct { plugins.Store plugins map[string]plugins.PluginDTO } func (pr fakePluginStore) Plugin(_ context.Context, pluginID string) (plugins.PluginDTO, bool) { p, exists := pr.plugins[pluginID] return p, exists } func (pr fakePluginStore) Plugins(_ context.Context, pluginTypes ...plugins.Type) []plugins.PluginDTO { var result []plugins.PluginDTO for _, v := range pr.plugins { for _, t := range pluginTypes { if v.Type == t { result = append(result, v) } } } return result } func setupSomeDataSourcePlugins(t *testing.T, uss *UsageStats) { t.Helper() uss.pluginStore = &fakePluginStore{ plugins: map[string]plugins.PluginDTO{ models.DS_ES: { Signature: "internal", }, models.DS_PROMETHEUS: { Signature: "internal", }, models.DS_GRAPHITE: { Signature: "internal", }, models.DS_MYSQL: { Signature: "internal", }, }, } } type httpResp struct { req *http.Request responseBuffer *bytes.Buffer err error } func createService(t *testing.T, cfg setting.Cfg) *UsageStats { t.Helper() sqlStore := sqlstore.InitTestDB(t) return &UsageStats{ Bus: bus.New(), Cfg: &cfg, SQLStore: sqlStore, externalMetrics: make([]usagestats.MetricsFunc, 0), pluginStore: &fakePluginStore{}, kvStore: kvstore.WithNamespace(kvstore.ProvideService(sqlStore), 0, "infra.usagestats"), log: log.New("infra.usagestats"), startTime: time.Now().Add(-1 * time.Minute), } }
pkg/infra/usagestats/service/usage_stats_test.go
1
https://github.com/grafana/grafana/commit/a1b8b5d123bde86fcfd7195c01b43d83a687d0ad
[ 0.004464135505259037, 0.00028555732569657266, 0.0001629353064345196, 0.0001704498426988721, 0.000588282011449337 ]
{ "id": 3, "code_window": [ "\tFolderPermissions int64\n", "\tFolders int64\n", "\tProvisionedDashboards int64\n", "\tAuthTokens int64\n", "\tDashboardVersions int64\n", "\tAnnotations int64\n", "\tAlertRules int64\n", "\tLibraryPanels int64\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tAPIKeys int64 `xorm:\"api_keys\"`\n" ], "file_path": "pkg/models/stats.go", "type": "add", "edit_start_line_idx": 20 }
(import 'alerts/alerts.libsonnet') + (import 'dashboards/dashboards.libsonnet') + (import 'rules/rules.libsonnet')
grafana-mixin/mixin.libsonnet
0
https://github.com/grafana/grafana/commit/a1b8b5d123bde86fcfd7195c01b43d83a687d0ad
[ 0.0002814699546433985, 0.0002814699546433985, 0.0002814699546433985, 0.0002814699546433985, 0 ]
{ "id": 3, "code_window": [ "\tFolderPermissions int64\n", "\tFolders int64\n", "\tProvisionedDashboards int64\n", "\tAuthTokens int64\n", "\tDashboardVersions int64\n", "\tAnnotations int64\n", "\tAlertRules int64\n", "\tLibraryPanels int64\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tAPIKeys int64 `xorm:\"api_keys\"`\n" ], "file_path": "pkg/models/stats.go", "type": "add", "edit_start_line_idx": 20 }
FROM centos:centos7 LABEL maintainer="Przemyslaw Ozgo <[email protected]>" RUN \ yum update -y && \ yum install -y net-snmp net-snmp-utils && \ yum clean all COPY bootstrap.sh /tmp/bootstrap.sh EXPOSE 161 ENTRYPOINT ["/tmp/bootstrap.sh"]
devenv/docker/blocks/smtp/Dockerfile
0
https://github.com/grafana/grafana/commit/a1b8b5d123bde86fcfd7195c01b43d83a687d0ad
[ 0.00016548526764381677, 0.00016391222015954554, 0.00016233918722718954, 0.00016391222015954554, 0.0000015730402083136141 ]
{ "id": 3, "code_window": [ "\tFolderPermissions int64\n", "\tFolders int64\n", "\tProvisionedDashboards int64\n", "\tAuthTokens int64\n", "\tDashboardVersions int64\n", "\tAnnotations int64\n", "\tAlertRules int64\n", "\tLibraryPanels int64\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tAPIKeys int64 `xorm:\"api_keys\"`\n" ], "file_path": "pkg/models/stats.go", "type": "add", "edit_start_line_idx": 20 }
<div class="graph-annotation"> <div class="graph-annotation__header"> <div class="graph-annotation__user" bs-tooltip="'Created by {{ctrl.login}}'"> </div> <div class="graph-annotation__title"> <span ng-if="!ctrl.event.id">Add annotation</span> <span ng-if="ctrl.event.id">Edit annotation</span> </div> <div class="graph-annotation__time">{{ctrl.timeFormated}}</div> </div> <form name="ctrl.form" class="graph-annotation__body text-center"> <div style="display: inline-block"> <div class="gf-form gf-form--v-stretch"> <span class="gf-form-label width-7">Description</span> <textarea class="gf-form-input width-20" rows="2" ng-model="ctrl.event.text" placeholder="Description"></textarea> </div> <div class="gf-form"> <span class="gf-form-label width-7">Tags</span> <bootstrap-tagsinput ng-model="ctrl.event.tags" tagclass="label label-tag" placeholder="add tags"> </bootstrap-tagsinput> </div> <div class="gf-form-button-row"> <button type="submit" class="btn btn-primary" ng-click="ctrl.save()">Save</button> <button ng-if="ctrl.event.id" type="submit" class="btn btn-danger" ng-click="ctrl.delete()">Delete</button> <a class="btn-text" ng-click="ctrl.close();">Cancel</a> </div> </div> </form> </div>
public/app/features/annotations/partials/event_editor.html
0
https://github.com/grafana/grafana/commit/a1b8b5d123bde86fcfd7195c01b43d83a687d0ad
[ 0.0001718400453682989, 0.00016787195636425167, 0.0001658323162700981, 0.00016690773190930486, 0.000002373781399001018 ]
{ "id": 4, "code_window": [ "\tsb.Write(`(SELECT COUNT(id) FROM ` + dialect.Quote(\"annotation\") + `) AS annotations,`)\n", "\tsb.Write(`(SELECT COUNT(id) FROM ` + dialect.Quote(\"team\") + `) AS teams,`)\n", "\tsb.Write(`(SELECT COUNT(id) FROM ` + dialect.Quote(\"user_auth_token\") + `) AS auth_tokens,`)\n", "\tsb.Write(`(SELECT COUNT(id) FROM ` + dialect.Quote(\"alert_rule\") + `) AS alert_rules,`)\n", "\tsb.Write(`(SELECT COUNT(id) FROM `+dialect.Quote(\"library_element\")+` WHERE kind = ?) AS library_panels,`, models.PanelElement)\n", "\tsb.Write(`(SELECT COUNT(id) FROM `+dialect.Quote(\"library_element\")+` WHERE kind = ?) AS library_variables,`, models.VariableElement)\n", "\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\tsb.Write(`(SELECT COUNT(id) FROM ` + dialect.Quote(\"api_key\") + `) AS api_keys,`)\n" ], "file_path": "pkg/services/sqlstore/stats.go", "type": "add", "edit_start_line_idx": 95 }
package service import ( "bytes" "context" "encoding/json" "fmt" "net/http" "runtime" "strings" "time" "github.com/google/uuid" "github.com/grafana/grafana/pkg/infra/metrics" "github.com/grafana/grafana/pkg/infra/usagestats" "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/plugins" ) var usageStatsURL = "https://stats.grafana.org/grafana-usage-report" func (uss *UsageStats) GetUsageReport(ctx context.Context) (usagestats.Report, error) { version := strings.ReplaceAll(uss.Cfg.BuildVersion, ".", "_") metrics := map[string]interface{}{} edition := "oss" if uss.Cfg.IsEnterprise { edition = "enterprise" } report := usagestats.Report{ Version: version, Metrics: metrics, Os: runtime.GOOS, Arch: runtime.GOARCH, Edition: edition, Packaging: uss.Cfg.Packaging, UsageStatsId: uss.GetUsageStatsId(ctx), } statsQuery := models.GetSystemStatsQuery{} if err := uss.Bus.DispatchCtx(ctx, &statsQuery); err != nil { uss.log.Error("Failed to get system stats", "error", err) return report, err } metrics["stats.dashboards.count"] = statsQuery.Result.Dashboards metrics["stats.users.count"] = statsQuery.Result.Users metrics["stats.admins.count"] = statsQuery.Result.Admins metrics["stats.editors.count"] = statsQuery.Result.Editors metrics["stats.viewers.count"] = statsQuery.Result.Viewers metrics["stats.orgs.count"] = statsQuery.Result.Orgs metrics["stats.playlist.count"] = statsQuery.Result.Playlists metrics["stats.plugins.apps.count"] = uss.appCount(ctx) metrics["stats.plugins.panels.count"] = uss.panelCount(ctx) metrics["stats.plugins.datasources.count"] = uss.dataSourceCount(ctx) metrics["stats.alerts.count"] = statsQuery.Result.Alerts metrics["stats.active_users.count"] = statsQuery.Result.ActiveUsers metrics["stats.active_admins.count"] = statsQuery.Result.ActiveAdmins metrics["stats.active_editors.count"] = statsQuery.Result.ActiveEditors metrics["stats.active_viewers.count"] = statsQuery.Result.ActiveViewers metrics["stats.active_sessions.count"] = statsQuery.Result.ActiveSessions metrics["stats.monthly_active_users.count"] = statsQuery.Result.MonthlyActiveUsers metrics["stats.daily_active_users.count"] = statsQuery.Result.DailyActiveUsers metrics["stats.daily_active_admins.count"] = statsQuery.Result.DailyActiveAdmins metrics["stats.daily_active_editors.count"] = statsQuery.Result.DailyActiveEditors metrics["stats.daily_active_viewers.count"] = statsQuery.Result.DailyActiveViewers metrics["stats.daily_active_sessions.count"] = statsQuery.Result.DailyActiveSessions metrics["stats.datasources.count"] = statsQuery.Result.Datasources metrics["stats.stars.count"] = statsQuery.Result.Stars metrics["stats.folders.count"] = statsQuery.Result.Folders metrics["stats.dashboard_permissions.count"] = statsQuery.Result.DashboardPermissions metrics["stats.folder_permissions.count"] = statsQuery.Result.FolderPermissions metrics["stats.provisioned_dashboards.count"] = statsQuery.Result.ProvisionedDashboards metrics["stats.snapshots.count"] = statsQuery.Result.Snapshots metrics["stats.teams.count"] = statsQuery.Result.Teams metrics["stats.total_auth_token.count"] = statsQuery.Result.AuthTokens metrics["stats.dashboard_versions.count"] = statsQuery.Result.DashboardVersions metrics["stats.annotations.count"] = statsQuery.Result.Annotations metrics["stats.alert_rules.count"] = statsQuery.Result.AlertRules metrics["stats.library_panels.count"] = statsQuery.Result.LibraryPanels metrics["stats.library_variables.count"] = statsQuery.Result.LibraryVariables metrics["stats.dashboards_viewers_can_edit.count"] = statsQuery.Result.DashboardsViewersCanEdit metrics["stats.dashboards_viewers_can_admin.count"] = statsQuery.Result.DashboardsViewersCanAdmin metrics["stats.folders_viewers_can_edit.count"] = statsQuery.Result.FoldersViewersCanEdit metrics["stats.folders_viewers_can_admin.count"] = statsQuery.Result.FoldersViewersCanAdmin ossEditionCount := 1 enterpriseEditionCount := 0 if uss.Cfg.IsEnterprise { enterpriseEditionCount = 1 ossEditionCount = 0 } metrics["stats.edition.oss.count"] = ossEditionCount metrics["stats.edition.enterprise.count"] = enterpriseEditionCount uss.registerExternalMetrics(ctx, metrics) // must run after registration of external metrics if v, ok := metrics["stats.valid_license.count"]; ok { report.HasValidLicense = v == 1 } else { metrics["stats.valid_license.count"] = 0 } userCount := statsQuery.Result.Users avgAuthTokensPerUser := statsQuery.Result.AuthTokens if userCount != 0 { avgAuthTokensPerUser /= userCount } metrics["stats.avg_auth_token_per_user.count"] = avgAuthTokensPerUser dsStats := models.GetDataSourceStatsQuery{} if err := uss.Bus.DispatchCtx(ctx, &dsStats); err != nil { uss.log.Error("Failed to get datasource stats", "error", err) return report, err } // send counters for each data source // but ignore any custom data sources // as sending that name could be sensitive information dsOtherCount := 0 for _, dsStat := range dsStats.Result { if uss.ShouldBeReported(ctx, dsStat.Type) { metrics["stats.ds."+dsStat.Type+".count"] = dsStat.Count } else { dsOtherCount += dsStat.Count } } metrics["stats.ds.other.count"] = dsOtherCount esDataSourcesQuery := models.GetDataSourcesByTypeQuery{Type: models.DS_ES} if err := uss.Bus.DispatchCtx(ctx, &esDataSourcesQuery); err != nil { uss.log.Error("Failed to get elasticsearch json data", "error", err) return report, err } for _, data := range esDataSourcesQuery.Result { esVersion, err := data.JsonData.Get("esVersion").Int() if err != nil { continue } statName := fmt.Sprintf("stats.ds.elasticsearch.v%d.count", esVersion) count, _ := metrics[statName].(int64) metrics[statName] = count + 1 } metrics["stats.packaging."+uss.Cfg.Packaging+".count"] = 1 metrics["stats.distributor."+uss.Cfg.ReportingDistributor+".count"] = 1 // fetch datasource access stats dsAccessStats := models.GetDataSourceAccessStatsQuery{} if err := uss.Bus.DispatchCtx(ctx, &dsAccessStats); err != nil { uss.log.Error("Failed to get datasource access stats", "error", err) return report, err } // send access counters for each data source // but ignore any custom data sources // as sending that name could be sensitive information dsAccessOtherCount := make(map[string]int64) for _, dsAccessStat := range dsAccessStats.Result { if dsAccessStat.Access == "" { continue } access := strings.ToLower(dsAccessStat.Access) if uss.ShouldBeReported(ctx, dsAccessStat.Type) { metrics["stats.ds_access."+dsAccessStat.Type+"."+access+".count"] = dsAccessStat.Count } else { old := dsAccessOtherCount[access] dsAccessOtherCount[access] = old + dsAccessStat.Count } } for access, count := range dsAccessOtherCount { metrics["stats.ds_access.other."+access+".count"] = count } // get stats about alert notifier usage anStats := models.GetAlertNotifierUsageStatsQuery{} if err := uss.Bus.DispatchCtx(ctx, &anStats); err != nil { uss.log.Error("Failed to get alert notification stats", "error", err) return report, err } for _, stats := range anStats.Result { metrics["stats.alert_notifiers."+stats.Type+".count"] = stats.Count } // Add stats about auth configuration authTypes := map[string]bool{} authTypes["anonymous"] = uss.Cfg.AnonymousEnabled authTypes["basic_auth"] = uss.Cfg.BasicAuthEnabled authTypes["ldap"] = uss.Cfg.LDAPEnabled authTypes["auth_proxy"] = uss.Cfg.AuthProxyEnabled for provider, enabled := range uss.oauthProviders { authTypes["oauth_"+provider] = enabled } for authType, enabled := range authTypes { enabledValue := 0 if enabled { enabledValue = 1 } metrics["stats.auth_enabled."+authType+".count"] = enabledValue } // Get concurrent users stats as histogram concurrentUsersStats, err := uss.GetConcurrentUsersStats(ctx) if err != nil { uss.log.Error("Failed to get concurrent users stats", "error", err) return report, err } // Histogram is cumulative and metric name has a postfix of le_"<upper inclusive bound>" metrics["stats.auth_token_per_user_le_3"] = concurrentUsersStats.BucketLE3 metrics["stats.auth_token_per_user_le_6"] = concurrentUsersStats.BucketLE6 metrics["stats.auth_token_per_user_le_9"] = concurrentUsersStats.BucketLE9 metrics["stats.auth_token_per_user_le_12"] = concurrentUsersStats.BucketLE12 metrics["stats.auth_token_per_user_le_15"] = concurrentUsersStats.BucketLE15 metrics["stats.auth_token_per_user_le_inf"] = concurrentUsersStats.BucketLEInf metrics["stats.uptime"] = int64(time.Since(uss.startTime).Seconds()) return report, nil } func (uss *UsageStats) registerExternalMetrics(ctx context.Context, metrics map[string]interface{}) { for _, fn := range uss.externalMetrics { fnMetrics, err := fn(ctx) if err != nil { uss.log.Error("Failed to fetch external metrics", "error", err) continue } for name, value := range fnMetrics { metrics[name] = value } } } func (uss *UsageStats) RegisterMetricsFunc(fn usagestats.MetricsFunc) { uss.externalMetrics = append(uss.externalMetrics, fn) } func (uss *UsageStats) sendUsageStats(ctx context.Context) error { if !uss.Cfg.ReportingEnabled { return nil } uss.log.Debug(fmt.Sprintf("Sending anonymous usage stats to %s", usageStatsURL)) report, err := uss.GetUsageReport(ctx) if err != nil { return err } out, err := json.MarshalIndent(report, "", " ") if err != nil { return err } data := bytes.NewBuffer(out) sendUsageStats(uss, data) return nil } // sendUsageStats sends usage statistics. // // Stubbable by tests. var sendUsageStats = func(uss *UsageStats, data *bytes.Buffer) { go func() { client := http.Client{Timeout: 5 * time.Second} resp, err := client.Post(usageStatsURL, "application/json", data) if err != nil { uss.log.Error("Failed to send usage stats", "err", err) return } if err := resp.Body.Close(); err != nil { uss.log.Warn("Failed to close response body", "err", err) } }() } func (uss *UsageStats) updateTotalStats(ctx context.Context) { if !uss.Cfg.MetricsEndpointEnabled || uss.Cfg.MetricsEndpointDisableTotalStats { return } statsQuery := models.GetSystemStatsQuery{} if err := uss.Bus.DispatchCtx(ctx, &statsQuery); err != nil { uss.log.Error("Failed to get system stats", "error", err) return } metrics.MStatTotalDashboards.Set(float64(statsQuery.Result.Dashboards)) metrics.MStatTotalFolders.Set(float64(statsQuery.Result.Folders)) metrics.MStatTotalUsers.Set(float64(statsQuery.Result.Users)) metrics.MStatActiveUsers.Set(float64(statsQuery.Result.ActiveUsers)) metrics.MStatTotalPlaylists.Set(float64(statsQuery.Result.Playlists)) metrics.MStatTotalOrgs.Set(float64(statsQuery.Result.Orgs)) metrics.StatsTotalViewers.Set(float64(statsQuery.Result.Viewers)) metrics.StatsTotalActiveViewers.Set(float64(statsQuery.Result.ActiveViewers)) metrics.StatsTotalEditors.Set(float64(statsQuery.Result.Editors)) metrics.StatsTotalActiveEditors.Set(float64(statsQuery.Result.ActiveEditors)) metrics.StatsTotalAdmins.Set(float64(statsQuery.Result.Admins)) metrics.StatsTotalActiveAdmins.Set(float64(statsQuery.Result.ActiveAdmins)) metrics.StatsTotalDashboardVersions.Set(float64(statsQuery.Result.DashboardVersions)) metrics.StatsTotalAnnotations.Set(float64(statsQuery.Result.Annotations)) metrics.StatsTotalAlertRules.Set(float64(statsQuery.Result.AlertRules)) metrics.StatsTotalLibraryPanels.Set(float64(statsQuery.Result.LibraryPanels)) metrics.StatsTotalLibraryVariables.Set(float64(statsQuery.Result.LibraryVariables)) dsStats := models.GetDataSourceStatsQuery{} if err := uss.Bus.DispatchCtx(ctx, &dsStats); err != nil { uss.log.Error("Failed to get datasource stats", "error", err) return } for _, dsStat := range dsStats.Result { metrics.StatsTotalDataSources.WithLabelValues(dsStat.Type).Set(float64(dsStat.Count)) } } func (uss *UsageStats) ShouldBeReported(ctx context.Context, dsType string) bool { ds, exists := uss.pluginStore.Plugin(ctx, dsType) if !exists { return false } return ds.Signature.IsValid() || ds.Signature.IsInternal() } func (uss *UsageStats) GetUsageStatsId(ctx context.Context) string { anonId, ok, err := uss.kvStore.Get(ctx, "anonymous_id") if err != nil { uss.log.Error("Failed to get usage stats id", "error", err) return "" } if ok { return anonId } newId, err := uuid.NewRandom() if err != nil { uss.log.Error("Failed to generate usage stats id", "error", err) return "" } anonId = newId.String() err = uss.kvStore.Set(ctx, "anonymous_id", anonId) if err != nil { uss.log.Error("Failed to store usage stats id", "error", err) return "" } return anonId } func (uss *UsageStats) appCount(ctx context.Context) int { return len(uss.pluginStore.Plugins(ctx, plugins.App)) } func (uss *UsageStats) panelCount(ctx context.Context) int { return len(uss.pluginStore.Plugins(ctx, plugins.Panel)) } func (uss *UsageStats) dataSourceCount(ctx context.Context) int { return len(uss.pluginStore.Plugins(ctx, plugins.DataSource)) }
pkg/infra/usagestats/service/usage_stats.go
1
https://github.com/grafana/grafana/commit/a1b8b5d123bde86fcfd7195c01b43d83a687d0ad
[ 0.0011982698924839497, 0.0002412366884527728, 0.0001628189638722688, 0.00017356581520289183, 0.0002320672938367352 ]
{ "id": 4, "code_window": [ "\tsb.Write(`(SELECT COUNT(id) FROM ` + dialect.Quote(\"annotation\") + `) AS annotations,`)\n", "\tsb.Write(`(SELECT COUNT(id) FROM ` + dialect.Quote(\"team\") + `) AS teams,`)\n", "\tsb.Write(`(SELECT COUNT(id) FROM ` + dialect.Quote(\"user_auth_token\") + `) AS auth_tokens,`)\n", "\tsb.Write(`(SELECT COUNT(id) FROM ` + dialect.Quote(\"alert_rule\") + `) AS alert_rules,`)\n", "\tsb.Write(`(SELECT COUNT(id) FROM `+dialect.Quote(\"library_element\")+` WHERE kind = ?) AS library_panels,`, models.PanelElement)\n", "\tsb.Write(`(SELECT COUNT(id) FROM `+dialect.Quote(\"library_element\")+` WHERE kind = ?) AS library_variables,`, models.VariableElement)\n", "\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\tsb.Write(`(SELECT COUNT(id) FROM ` + dialect.Quote(\"api_key\") + `) AS api_keys,`)\n" ], "file_path": "pkg/services/sqlstore/stats.go", "type": "add", "edit_start_line_idx": 95 }
<?xml version="1.0" encoding="utf-8"?> <!-- Generator: Adobe Illustrator 19.1.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) --> <svg version="1.1" baseProfile="tiny" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="70px" height="70px" viewBox="15 -15 70 70" xml:space="preserve"> <g> <path fill="#EC2128" d="M55.2-7l-0.1,0.4 M78.9-6.1c-3.9-3.9-9.1-6.1-14.6-6.1c-2.7,0-5.4,0.5-7.9,1.6L55.2-7l1.1-3.5l3.4,1.1 l-0.2,0.6c1.5-0.4,3.1-0.6,4.7-0.6c4.8,0,9.4,1.9,12.8,5.3s5.3,7.9,5.3,12.8s-1.9,9.4-5.3,12.8l-27,27l-27-27 c-3.4-3.4-5.3-7.9-5.3-12.8S19.6-0.8,23-4.2s7.9-5.3,12.8-5.3c2,0,4,0.3,5.8,1l0.3-1.5l3.5,0.7l0.1-0.4c-3-1.6-6.3-2.4-9.7-2.4 c-5.6-0.1-10.8,2.1-14.7,6S15,3,15,8.6s2.2,10.7,6.1,14.7L50,52.2l28.9-28.9c3.9-3.9,6.1-9.1,6.1-14.7S82.8-2.2,78.9-6.1z"/> <path fill="#EC2128" d="M51.3,5.3l6.5-1l-11.2,27l-0.1,0.2l1.9-19.7l-7.3,0.5v-0.2l4.3-21.4L41.9-10l-0.3,1.5l-1.1,5.3 c-1.5-0.6-3.1-0.9-4.8-0.9c-3.4,0-6.6,1.3-9,3.7S23,5.2,23,8.6s1.3,6.6,3.7,9L50,40.8l23.2-23.2c2.4-2.4,3.7-5.6,3.7-9 s-1.3-6.6-3.7-9c-2.4-2.4-5.6-3.7-9-3.7c-2.5,0-4.8,0.7-6.8,2l2.2-6.8l0.2-0.6l-3.4-1.1L55.2-7l-0.1,0.4 C55.1-6.6,51.3,5.3,51.3,5.3z"/> </g> </svg>
public/img/critical.svg
0
https://github.com/grafana/grafana/commit/a1b8b5d123bde86fcfd7195c01b43d83a687d0ad
[ 0.00017233789549209177, 0.00017186315380968153, 0.0001713884121272713, 0.00017186315380968153, 4.7474168241024017e-7 ]
{ "id": 4, "code_window": [ "\tsb.Write(`(SELECT COUNT(id) FROM ` + dialect.Quote(\"annotation\") + `) AS annotations,`)\n", "\tsb.Write(`(SELECT COUNT(id) FROM ` + dialect.Quote(\"team\") + `) AS teams,`)\n", "\tsb.Write(`(SELECT COUNT(id) FROM ` + dialect.Quote(\"user_auth_token\") + `) AS auth_tokens,`)\n", "\tsb.Write(`(SELECT COUNT(id) FROM ` + dialect.Quote(\"alert_rule\") + `) AS alert_rules,`)\n", "\tsb.Write(`(SELECT COUNT(id) FROM `+dialect.Quote(\"library_element\")+` WHERE kind = ?) AS library_panels,`, models.PanelElement)\n", "\tsb.Write(`(SELECT COUNT(id) FROM `+dialect.Quote(\"library_element\")+` WHERE kind = ?) AS library_variables,`, models.VariableElement)\n", "\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\tsb.Write(`(SELECT COUNT(id) FROM ` + dialect.Quote(\"api_key\") + `) AS api_keys,`)\n" ], "file_path": "pkg/services/sqlstore/stats.go", "type": "add", "edit_start_line_idx": 95 }
import { PromMetricsMetadata, PromMetricsMetadataItem } from './types'; import { addLabelToQuery } from './add_label_to_query'; import { SUGGESTIONS_LIMIT } from './language_provider'; import { DataQuery, AbstractQuery, AbstractLabelOperator, AbstractLabelMatcher } from '@grafana/data'; import { Token } from 'prismjs'; import { invert } from 'lodash'; export const processHistogramMetrics = (metrics: string[]) => { const resultSet: Set<string> = new Set(); const regexp = new RegExp('_bucket($|:)'); for (let index = 0; index < metrics.length; index++) { const metric = metrics[index]; const isHistogramValue = regexp.test(metric); if (isHistogramValue) { resultSet.add(metric); } } return [...resultSet]; }; export function processLabels(labels: Array<{ [key: string]: string }>, withName = false) { // For processing we are going to use sets as they have significantly better performance than arrays // After we process labels, we will convert sets to arrays and return object with label values in arrays const valueSet: { [key: string]: Set<string> } = {}; labels.forEach((label) => { const { __name__, ...rest } = label; if (withName) { valueSet['__name__'] = valueSet['__name__'] || new Set(); if (!valueSet['__name__'].has(__name__)) { valueSet['__name__'].add(__name__); } } Object.keys(rest).forEach((key) => { if (!valueSet[key]) { valueSet[key] = new Set(); } if (!valueSet[key].has(rest[key])) { valueSet[key].add(rest[key]); } }); }); // valueArray that we are going to return in the object const valueArray: { [key: string]: string[] } = {}; limitSuggestions(Object.keys(valueSet)).forEach((key) => { valueArray[key] = limitSuggestions(Array.from(valueSet[key])); }); return { values: valueArray, keys: Object.keys(valueArray) }; } // const cleanSelectorRegexp = /\{(\w+="[^"\n]*?")(,\w+="[^"\n]*?")*\}/; export const selectorRegexp = /\{[^}]*?(\}|$)/; export const labelRegexp = /\b(\w+)(!?=~?)("[^"\n]*?")/g; export function parseSelector(query: string, cursorOffset = 1): { labelKeys: any[]; selector: string } { if (!query.match(selectorRegexp)) { // Special matcher for metrics if (query.match(/^[A-Za-z:][\w:]*$/)) { return { selector: `{__name__="${query}"}`, labelKeys: ['__name__'], }; } throw new Error('Query must contain a selector: ' + query); } // Check if inside a selector const prefix = query.slice(0, cursorOffset); const prefixOpen = prefix.lastIndexOf('{'); const prefixClose = prefix.lastIndexOf('}'); if (prefixOpen === -1) { throw new Error('Not inside selector, missing open brace: ' + prefix); } if (prefixClose > -1 && prefixClose > prefixOpen) { throw new Error('Not inside selector, previous selector already closed: ' + prefix); } const suffix = query.slice(cursorOffset); const suffixCloseIndex = suffix.indexOf('}'); const suffixClose = suffixCloseIndex + cursorOffset; const suffixOpenIndex = suffix.indexOf('{'); const suffixOpen = suffixOpenIndex + cursorOffset; if (suffixClose === -1) { throw new Error('Not inside selector, missing closing brace in suffix: ' + suffix); } if (suffixOpenIndex > -1 && suffixOpen < suffixClose) { throw new Error('Not inside selector, next selector opens before this one closed: ' + suffix); } // Extract clean labels to form clean selector, incomplete labels are dropped const selector = query.slice(prefixOpen, suffixClose); const labels: { [key: string]: { value: string; operator: string } } = {}; selector.replace(labelRegexp, (label, key, operator, value) => { const labelOffset = query.indexOf(label); const valueStart = labelOffset + key.length + operator.length + 1; const valueEnd = labelOffset + key.length + operator.length + value.length - 1; // Skip label if cursor is in value if (cursorOffset < valueStart || cursorOffset > valueEnd) { labels[key] = { value, operator }; } return ''; }); // Add metric if there is one before the selector const metricPrefix = query.slice(0, prefixOpen); const metricMatch = metricPrefix.match(/[A-Za-z:][\w:]*$/); if (metricMatch) { labels['__name__'] = { value: `"${metricMatch[0]}"`, operator: '=' }; } // Build sorted selector const labelKeys = Object.keys(labels).sort(); const cleanSelector = labelKeys.map((key) => `${key}${labels[key].operator}${labels[key].value}`).join(','); const selectorString = ['{', cleanSelector, '}'].join(''); return { labelKeys, selector: selectorString }; } export function expandRecordingRules(query: string, mapping: { [name: string]: string }): string { const ruleNames = Object.keys(mapping); const rulesRegex = new RegExp(`(\\s|^)(${ruleNames.join('|')})(\\s|$|\\(|\\[|\\{)`, 'ig'); const expandedQuery = query.replace(rulesRegex, (match, pre, name, post) => `${pre}${mapping[name]}${post}`); // Split query into array, so if query uses operators, we can correctly add labels to each individual part. const queryArray = expandedQuery.split(/(\+|\-|\*|\/|\%|\^)/); // Regex that matches occurrences of ){ or }{ or ]{ which is a sign of incorrecly added labels. const invalidLabelsRegex = /(\)\{|\}\{|\]\{)/; const correctlyExpandedQueryArray = queryArray.map((query) => { return addLabelsToExpression(query, invalidLabelsRegex); }); return correctlyExpandedQueryArray.join(''); } function addLabelsToExpression(expr: string, invalidLabelsRegexp: RegExp) { const match = expr.match(invalidLabelsRegexp); if (!match) { return expr; } // Split query into 2 parts - before the invalidLabelsRegex match and after. const indexOfRegexMatch = match.index ?? 0; const exprBeforeRegexMatch = expr.substr(0, indexOfRegexMatch + 1); const exprAfterRegexMatch = expr.substr(indexOfRegexMatch + 1); // Create arrayOfLabelObjects with label objects that have key, operator and value. const arrayOfLabelObjects: Array<{ key: string; operator: string; value: string }> = []; exprAfterRegexMatch.replace(labelRegexp, (label, key, operator, value) => { arrayOfLabelObjects.push({ key, operator, value }); return ''; }); // Loop trough all of the label objects and add them to query. // As a starting point we have valid query without the labels. let result = exprBeforeRegexMatch; arrayOfLabelObjects.filter(Boolean).forEach((obj) => { // Remove extra set of quotes from obj.value const value = obj.value.substr(1, obj.value.length - 2); result = addLabelToQuery(result, obj.key, value, obj.operator); }); return result; } /** * Adds metadata for synthetic metrics for which the API does not provide metadata. * See https://github.com/grafana/grafana/issues/22337 for details. * * @param metadata HELP and TYPE metadata from /api/v1/metadata */ export function fixSummariesMetadata(metadata: { [metric: string]: PromMetricsMetadataItem[] }): PromMetricsMetadata { if (!metadata) { return metadata; } const baseMetadata: PromMetricsMetadata = {}; const summaryMetadata: PromMetricsMetadata = {}; for (const metric in metadata) { // NOTE: based on prometheus-documentation, we can receive // multiple metadata-entries for the given metric, it seems // it happens when the same metric is on multiple targets // and their help-text differs // (https://prometheus.io/docs/prometheus/latest/querying/api/#querying-metric-metadata) // for now we just use the first entry. const item = metadata[metric][0]; baseMetadata[metric] = item; if (item.type === 'histogram') { summaryMetadata[`${metric}_bucket`] = { type: 'counter', help: `Cumulative counters for the observation buckets (${item.help})`, }; summaryMetadata[`${metric}_count`] = { type: 'counter', help: `Count of events that have been observed for the histogram metric (${item.help})`, }; summaryMetadata[`${metric}_sum`] = { type: 'counter', help: `Total sum of all observed values for the histogram metric (${item.help})`, }; } if (item.type === 'summary') { summaryMetadata[`${metric}_count`] = { type: 'counter', help: `Count of events that have been observed for the base metric (${item.help})`, }; summaryMetadata[`${metric}_sum`] = { type: 'counter', help: `Total sum of all observed values for the base metric (${item.help})`, }; } } // Synthetic series const syntheticMetadata: PromMetricsMetadata = {}; syntheticMetadata['ALERTS'] = { type: 'counter', help: 'Time series showing pending and firing alerts. The sample value is set to 1 as long as the alert is in the indicated active (pending or firing) state.', }; return { ...baseMetadata, ...summaryMetadata, ...syntheticMetadata }; } export function roundMsToMin(milliseconds: number): number { return roundSecToMin(milliseconds / 1000); } export function roundSecToMin(seconds: number): number { return Math.floor(seconds / 60); } export function limitSuggestions(items: string[]) { return items.slice(0, SUGGESTIONS_LIMIT); } export function addLimitInfo(items: any[] | undefined): string { return items && items.length >= SUGGESTIONS_LIMIT ? `, limited to the first ${SUGGESTIONS_LIMIT} received items` : ''; } // NOTE: the following 2 exported functions are very similar to the prometheus*Escape // functions in datasource.ts, but they are not exactly the same algorithm, and we found // no way to reuse one in the another or vice versa. // Prometheus regular-expressions use the RE2 syntax (https://github.com/google/re2/wiki/Syntax), // so every character that matches something in that list has to be escaped. // the list of metacharacters is: *+?()|\.[]{}^$ // we make a javascript regular expression that matches those characters: const RE2_METACHARACTERS = /[*+?()|\\.\[\]{}^$]/g; function escapePrometheusRegexp(value: string): string { return value.replace(RE2_METACHARACTERS, '\\$&'); } // based on the openmetrics-documentation, the 3 symbols we have to handle are: // - \n ... the newline character // - \ ... the backslash character // - " ... the double-quote character export function escapeLabelValueInExactSelector(labelValue: string): string { return labelValue.replace(/\\/g, '\\\\').replace(/\n/g, '\\n').replace(/"/g, '\\"'); } export function escapeLabelValueInRegexSelector(labelValue: string): string { return escapeLabelValueInExactSelector(escapePrometheusRegexp(labelValue)); } const FromPromLikeMap: Record<string, AbstractLabelOperator> = { '=': AbstractLabelOperator.Equal, '!=': AbstractLabelOperator.NotEqual, '=~': AbstractLabelOperator.EqualRegEx, '!~': AbstractLabelOperator.NotEqualRegEx, }; const ToPromLikeMap: Record<AbstractLabelOperator, string> = invert(FromPromLikeMap) as Record< AbstractLabelOperator, string >; export function toPromLikeQuery(labelBasedQuery: AbstractQuery): PromLikeQuery { const expr = labelBasedQuery.labelMatchers .map((selector: AbstractLabelMatcher) => { const operator = ToPromLikeMap[selector.operator]; if (operator) { return `${selector.name}${operator}"${selector.value}"`; } else { return ''; } }) .filter((e: string) => e !== '') .join(', '); return { refId: labelBasedQuery.refId, expr: expr ? `{${expr}}` : '', range: true, }; } export interface PromLikeQuery extends DataQuery { expr: string; range: boolean; } export function extractLabelMatchers(tokens: Array<string | Token>): AbstractLabelMatcher[] { const labelMatchers: AbstractLabelMatcher[] = []; for (let prop in tokens) { if (tokens[prop] instanceof Token) { let token: Token = tokens[prop] as Token; if (token.type === 'context-labels') { let labelKey = ''; let labelValue = ''; let labelOperator = ''; let contentTokens: any[] = token.content as any[]; for (let currentToken in contentTokens) { if (typeof contentTokens[currentToken] === 'string') { let currentStr: string; currentStr = contentTokens[currentToken] as string; if (currentStr === '=' || currentStr === '!=' || currentStr === '=~' || currentStr === '!~') { labelOperator = currentStr; } } else if (contentTokens[currentToken] instanceof Token) { switch (contentTokens[currentToken].type) { case 'label-key': labelKey = contentTokens[currentToken].content as string; break; case 'label-value': labelValue = contentTokens[currentToken].content as string; labelValue = labelValue.substring(1, labelValue.length - 1); const labelComparator = FromPromLikeMap[labelOperator]; if (labelComparator) { labelMatchers.push({ name: labelKey, operator: labelComparator, value: labelValue }); } break; } } } } } } return labelMatchers; }
public/app/plugins/datasource/prometheus/language_utils.ts
0
https://github.com/grafana/grafana/commit/a1b8b5d123bde86fcfd7195c01b43d83a687d0ad
[ 0.00017945727449841797, 0.00017380631470587105, 0.00016574171604588628, 0.0001743646862450987, 0.000003601222033466911 ]
{ "id": 4, "code_window": [ "\tsb.Write(`(SELECT COUNT(id) FROM ` + dialect.Quote(\"annotation\") + `) AS annotations,`)\n", "\tsb.Write(`(SELECT COUNT(id) FROM ` + dialect.Quote(\"team\") + `) AS teams,`)\n", "\tsb.Write(`(SELECT COUNT(id) FROM ` + dialect.Quote(\"user_auth_token\") + `) AS auth_tokens,`)\n", "\tsb.Write(`(SELECT COUNT(id) FROM ` + dialect.Quote(\"alert_rule\") + `) AS alert_rules,`)\n", "\tsb.Write(`(SELECT COUNT(id) FROM `+dialect.Quote(\"library_element\")+` WHERE kind = ?) AS library_panels,`, models.PanelElement)\n", "\tsb.Write(`(SELECT COUNT(id) FROM `+dialect.Quote(\"library_element\")+` WHERE kind = ?) AS library_variables,`, models.VariableElement)\n", "\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\tsb.Write(`(SELECT COUNT(id) FROM ` + dialect.Quote(\"api_key\") + `) AS api_keys,`)\n" ], "file_path": "pkg/services/sqlstore/stats.go", "type": "add", "edit_start_line_idx": 95 }
{ "extends": "../../tsconfig.json", "include": ["**/*.ts", "../../packages/grafana-e2e/cypress/support/index.d.ts"] }
e2e/verify/tsconfig.json
0
https://github.com/grafana/grafana/commit/a1b8b5d123bde86fcfd7195c01b43d83a687d0ad
[ 0.000172779182321392, 0.000172779182321392, 0.000172779182321392, 0.000172779182321392, 0 ]
{ "id": 5, "code_window": [ "\t\tassert.Equal(t, int64(0), query.Result.Viewers)\n", "\t\tassert.Equal(t, int64(3), query.Result.Admins)\n", "\t\tassert.Equal(t, int64(0), query.Result.LibraryPanels)\n", "\t\tassert.Equal(t, int64(0), query.Result.LibraryVariables)\n", "\t})\n", "\n", "\tt.Run(\"Get system user count stats should not results in error\", func(t *testing.T) {\n", "\t\tquery := models.GetSystemUserCountStatsQuery{}\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tassert.Equal(t, int64(1), query.Result.APIKeys)\n" ], "file_path": "pkg/services/sqlstore/stats_test.go", "type": "add", "edit_start_line_idx": 29 }
package sqlstore import ( "context" "strconv" "time" "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/models" ) func init() { bus.AddHandlerCtx("sql", GetSystemStats) bus.AddHandlerCtx("sql", GetDataSourceStats) bus.AddHandlerCtx("sql", GetDataSourceAccessStats) bus.AddHandlerCtx("sql", GetAdminStats) bus.AddHandlerCtx("sql", GetAlertNotifiersUsageStats) bus.AddHandlerCtx("sql", GetSystemUserCountStats) } const activeUserTimeLimit = time.Hour * 24 * 30 const dailyActiveUserTimeLimit = time.Hour * 24 func GetAlertNotifiersUsageStats(ctx context.Context, query *models.GetAlertNotifierUsageStatsQuery) error { var rawSQL = `SELECT COUNT(*) AS count, type FROM ` + dialect.Quote("alert_notification") + ` GROUP BY type` query.Result = make([]*models.NotifierUsageStats, 0) err := x.SQL(rawSQL).Find(&query.Result) return err } func GetDataSourceStats(ctx context.Context, query *models.GetDataSourceStatsQuery) error { var rawSQL = `SELECT COUNT(*) AS count, type FROM ` + dialect.Quote("data_source") + ` GROUP BY type` query.Result = make([]*models.DataSourceStats, 0) err := x.SQL(rawSQL).Find(&query.Result) return err } func GetDataSourceAccessStats(ctx context.Context, query *models.GetDataSourceAccessStatsQuery) error { var rawSQL = `SELECT COUNT(*) AS count, type, access FROM ` + dialect.Quote("data_source") + ` GROUP BY type, access` query.Result = make([]*models.DataSourceAccessStats, 0) err := x.SQL(rawSQL).Find(&query.Result) return err } func GetSystemStats(ctx context.Context, query *models.GetSystemStatsQuery) error { sb := &SQLBuilder{} sb.Write("SELECT ") sb.Write(`(SELECT COUNT(*) FROM ` + dialect.Quote("user") + `) AS users,`) sb.Write(`(SELECT COUNT(*) FROM ` + dialect.Quote("org") + `) AS orgs,`) sb.Write(`(SELECT COUNT(*) FROM ` + dialect.Quote("data_source") + `) AS datasources,`) sb.Write(`(SELECT COUNT(*) FROM ` + dialect.Quote("star") + `) AS stars,`) sb.Write(`(SELECT COUNT(*) FROM ` + dialect.Quote("playlist") + `) AS playlists,`) sb.Write(`(SELECT COUNT(*) FROM ` + dialect.Quote("alert") + `) AS alerts,`) now := time.Now() activeUserDeadlineDate := now.Add(-activeUserTimeLimit) sb.Write(`(SELECT COUNT(*) FROM `+dialect.Quote("user")+` WHERE last_seen_at > ?) AS active_users,`, activeUserDeadlineDate) dailyActiveUserDeadlineDate := now.Add(-dailyActiveUserTimeLimit) sb.Write(`(SELECT COUNT(*) FROM `+dialect.Quote("user")+` WHERE last_seen_at > ?) AS daily_active_users,`, dailyActiveUserDeadlineDate) monthlyActiveUserDeadlineDate := time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, now.Location()) sb.Write(`(SELECT COUNT(*) FROM `+dialect.Quote("user")+` WHERE last_seen_at > ?) AS monthly_active_users,`, monthlyActiveUserDeadlineDate) sb.Write(`(SELECT COUNT(id) FROM `+dialect.Quote("dashboard")+` WHERE is_folder = ?) AS dashboards,`, dialect.BooleanStr(false)) sb.Write(`(SELECT COUNT(id) FROM `+dialect.Quote("dashboard")+` WHERE is_folder = ?) AS folders,`, dialect.BooleanStr(true)) sb.Write(`( SELECT COUNT(acl.id) FROM `+dialect.Quote("dashboard_acl")+` AS acl INNER JOIN `+dialect.Quote("dashboard")+` AS d ON d.id = acl.dashboard_id WHERE d.is_folder = ? ) AS dashboard_permissions,`, dialect.BooleanStr(false)) sb.Write(`( SELECT COUNT(acl.id) FROM `+dialect.Quote("dashboard_acl")+` AS acl INNER JOIN `+dialect.Quote("dashboard")+` AS d ON d.id = acl.dashboard_id WHERE d.is_folder = ? ) AS folder_permissions,`, dialect.BooleanStr(true)) sb.Write(viewersPermissionsCounterSQL("dashboards_viewers_can_edit", false, models.PERMISSION_EDIT)) sb.Write(viewersPermissionsCounterSQL("dashboards_viewers_can_admin", false, models.PERMISSION_ADMIN)) sb.Write(viewersPermissionsCounterSQL("folders_viewers_can_edit", true, models.PERMISSION_EDIT)) sb.Write(viewersPermissionsCounterSQL("folders_viewers_can_admin", true, models.PERMISSION_ADMIN)) sb.Write(`(SELECT COUNT(id) FROM ` + dialect.Quote("dashboard_provisioning") + `) AS provisioned_dashboards,`) sb.Write(`(SELECT COUNT(id) FROM ` + dialect.Quote("dashboard_snapshot") + `) AS snapshots,`) sb.Write(`(SELECT COUNT(id) FROM ` + dialect.Quote("dashboard_version") + `) AS dashboard_versions,`) sb.Write(`(SELECT COUNT(id) FROM ` + dialect.Quote("annotation") + `) AS annotations,`) sb.Write(`(SELECT COUNT(id) FROM ` + dialect.Quote("team") + `) AS teams,`) sb.Write(`(SELECT COUNT(id) FROM ` + dialect.Quote("user_auth_token") + `) AS auth_tokens,`) sb.Write(`(SELECT COUNT(id) FROM ` + dialect.Quote("alert_rule") + `) AS alert_rules,`) sb.Write(`(SELECT COUNT(id) FROM `+dialect.Quote("library_element")+` WHERE kind = ?) AS library_panels,`, models.PanelElement) sb.Write(`(SELECT COUNT(id) FROM `+dialect.Quote("library_element")+` WHERE kind = ?) AS library_variables,`, models.VariableElement) sb.Write(roleCounterSQL(ctx)) var stats models.SystemStats _, err := x.SQL(sb.GetSQLString(), sb.params...).Get(&stats) if err != nil { return err } query.Result = &stats return nil } func roleCounterSQL(ctx context.Context) string { const roleCounterTimeout = 20 * time.Second ctx, cancel := context.WithTimeout(ctx, roleCounterTimeout) defer cancel() _ = updateUserRoleCountsIfNecessary(ctx, false) sqlQuery := strconv.FormatInt(userStatsCache.total.Admins, 10) + ` AS admins, ` + strconv.FormatInt(userStatsCache.total.Editors, 10) + ` AS editors, ` + strconv.FormatInt(userStatsCache.total.Viewers, 10) + ` AS viewers, ` + strconv.FormatInt(userStatsCache.active.Admins, 10) + ` AS active_admins, ` + strconv.FormatInt(userStatsCache.active.Editors, 10) + ` AS active_editors, ` + strconv.FormatInt(userStatsCache.active.Viewers, 10) + ` AS active_viewers, ` + strconv.FormatInt(userStatsCache.dailyActive.Admins, 10) + ` AS daily_active_admins, ` + strconv.FormatInt(userStatsCache.dailyActive.Editors, 10) + ` AS daily_active_editors, ` + strconv.FormatInt(userStatsCache.dailyActive.Viewers, 10) + ` AS daily_active_viewers` return sqlQuery } func viewersPermissionsCounterSQL(statName string, isFolder bool, permission models.PermissionType) string { return `( SELECT COUNT(*) FROM ` + dialect.Quote("dashboard_acl") + ` AS acl INNER JOIN ` + dialect.Quote("dashboard") + ` AS d ON d.id = acl.dashboard_id WHERE acl.role = '` + string(models.ROLE_VIEWER) + `' AND d.is_folder = ` + dialect.BooleanStr(isFolder) + ` AND acl.permission = ` + strconv.FormatInt(int64(permission), 10) + ` ) AS ` + statName + `, ` } func GetAdminStats(ctx context.Context, query *models.GetAdminStatsQuery) error { now := time.Now() activeEndDate := now.Add(-activeUserTimeLimit) dailyActiveEndDate := now.Add(-dailyActiveUserTimeLimit) monthlyActiveEndDate := time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, now.Location()) var rawSQL = `SELECT ( SELECT COUNT(*) FROM ` + dialect.Quote("org") + ` ) AS orgs, ( SELECT COUNT(*) FROM ` + dialect.Quote("dashboard") + `WHERE is_folder=` + dialect.BooleanStr(false) + ` ) AS dashboards, ( SELECT COUNT(*) FROM ` + dialect.Quote("dashboard_snapshot") + ` ) AS snapshots, ( SELECT COUNT( DISTINCT ( ` + dialect.Quote("term") + ` )) FROM ` + dialect.Quote("dashboard_tag") + ` ) AS tags, ( SELECT COUNT(*) FROM ` + dialect.Quote("data_source") + ` ) AS datasources, ( SELECT COUNT(*) FROM ` + dialect.Quote("playlist") + ` ) AS playlists, ( SELECT COUNT(*) FROM ` + dialect.Quote("star") + ` ) AS stars, ( SELECT COUNT(*) FROM ` + dialect.Quote("alert") + ` ) AS alerts, ( SELECT COUNT(*) FROM ` + dialect.Quote("user") + ` ) AS users, ( SELECT COUNT(*) FROM ` + dialect.Quote("user") + ` WHERE last_seen_at > ? ) AS active_users, ( SELECT COUNT(*) FROM ` + dialect.Quote("user") + ` WHERE last_seen_at > ? ) AS daily_active_users, ( SELECT COUNT(*) FROM ` + dialect.Quote("user") + ` WHERE last_seen_at > ? ) AS monthly_active_users, ` + roleCounterSQL(ctx) + `, ( SELECT COUNT(*) FROM ` + dialect.Quote("user_auth_token") + ` WHERE rotated_at > ? ) AS active_sessions, ( SELECT COUNT(*) FROM ` + dialect.Quote("user_auth_token") + ` WHERE rotated_at > ? ) AS daily_active_sessions` var stats models.AdminStats _, err := x.SQL(rawSQL, activeEndDate, dailyActiveEndDate, monthlyActiveEndDate, activeEndDate.Unix(), dailyActiveEndDate.Unix()).Get(&stats) if err != nil { return err } query.Result = &stats return nil } func GetSystemUserCountStats(ctx context.Context, query *models.GetSystemUserCountStatsQuery) error { return withDbSession(ctx, x, func(sess *DBSession) error { var rawSQL = `SELECT COUNT(id) AS Count FROM ` + dialect.Quote("user") var stats models.SystemUserCountStats _, err := sess.SQL(rawSQL).Get(&stats) if err != nil { return err } query.Result = &stats return nil }) } func updateUserRoleCountsIfNecessary(ctx context.Context, forced bool) error { memoizationPeriod := time.Now().Add(-userStatsCacheLimetime) if forced || userStatsCache.memoized.Before(memoizationPeriod) { err := updateUserRoleCounts(ctx) if err != nil { return err } } return nil } type memoUserStats struct { active models.UserStats dailyActive models.UserStats total models.UserStats memoized time.Time } var ( userStatsCache = memoUserStats{} userStatsCacheLimetime = 5 * time.Minute ) func updateUserRoleCounts(ctx context.Context) error { query := ` SELECT role AS bitrole, active, COUNT(role) AS count FROM (SELECT last_seen_at>? AS active, last_seen_at>? AS daily_active, SUM(role) AS role FROM (SELECT u.id, CASE org_user.role WHEN 'Admin' THEN 4 WHEN 'Editor' THEN 2 ELSE 1 END AS role, u.last_seen_at FROM ` + dialect.Quote("user") + ` AS u INNER JOIN org_user ON org_user.user_id = u.id GROUP BY u.id, u.last_seen_at, org_user.role) AS t2 GROUP BY id, last_seen_at) AS t1 GROUP BY active, daily_active, role;` activeUserDeadline := time.Now().Add(-activeUserTimeLimit) dailyActiveUserDeadline := time.Now().Add(-dailyActiveUserTimeLimit) type rolebitmap struct { Active bool DailyActive bool Bitrole int64 Count int64 } bitmap := []rolebitmap{} err := x.Context(ctx).SQL(query, activeUserDeadline, dailyActiveUserDeadline).Find(&bitmap) if err != nil { return err } memo := memoUserStats{memoized: time.Now()} for _, role := range bitmap { roletype := models.ROLE_VIEWER if role.Bitrole&0b100 != 0 { roletype = models.ROLE_ADMIN } else if role.Bitrole&0b10 != 0 { roletype = models.ROLE_EDITOR } memo.total = addToStats(memo.total, roletype, role.Count) if role.Active { memo.active = addToStats(memo.active, roletype, role.Count) } if role.DailyActive { memo.dailyActive = addToStats(memo.dailyActive, roletype, role.Count) } } userStatsCache = memo return nil } func addToStats(base models.UserStats, role models.RoleType, count int64) models.UserStats { base.Users += count switch role { case models.ROLE_ADMIN: base.Admins += count case models.ROLE_EDITOR: base.Editors += count default: base.Viewers += count } return base }
pkg/services/sqlstore/stats.go
1
https://github.com/grafana/grafana/commit/a1b8b5d123bde86fcfd7195c01b43d83a687d0ad
[ 0.018292712047696114, 0.0018680907087400556, 0.00016329069330822676, 0.00017442188982386142, 0.0036301708314567804 ]
{ "id": 5, "code_window": [ "\t\tassert.Equal(t, int64(0), query.Result.Viewers)\n", "\t\tassert.Equal(t, int64(3), query.Result.Admins)\n", "\t\tassert.Equal(t, int64(0), query.Result.LibraryPanels)\n", "\t\tassert.Equal(t, int64(0), query.Result.LibraryVariables)\n", "\t})\n", "\n", "\tt.Run(\"Get system user count stats should not results in error\", func(t *testing.T) {\n", "\t\tquery := models.GetSystemUserCountStatsQuery{}\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tassert.Equal(t, int64(1), query.Result.APIKeys)\n" ], "file_path": "pkg/services/sqlstore/stats_test.go", "type": "add", "edit_start_line_idx": 29 }
import { getFieldDisplayValuesProxy } from './getFieldDisplayValuesProxy'; import { applyFieldOverrides } from './fieldOverrides'; import { MutableDataFrame, toDataFrame } from '../dataframe'; import { createTheme } from '../themes'; describe('getFieldDisplayValuesProxy', () => { const shortTimeField = [{ name: 'Time', values: [1, 2, 3] }]; const longTimeField = [{ name: 'Time', values: [1000, 2000, 61000] }]; const dataFields = [ { name: 'power', values: [100, 200, 300], labels: { name: 'POWAH!', }, config: { displayName: 'The Power', }, }, { name: 'Last', values: ['a', 'b', 'c'] }, ]; const overrides = { fieldConfig: { defaults: {}, overrides: [], }, replaceVariables: (val: string) => val, timeZone: 'utc', theme: createTheme(), }; const dataShortTimeRange = applyFieldOverrides({ ...{ data: [toDataFrame({ fields: [...shortTimeField, ...dataFields] })] }, ...overrides, })[0]; const dataLongTimeRange = applyFieldOverrides({ ...{ data: [toDataFrame({ fields: [...longTimeField, ...dataFields] })] }, ...overrides, })[0]; it('should define all display functions', () => { // Field display should be set for (const field of dataShortTimeRange.fields) { expect(field.display).toBeDefined(); } }); it('should format the time values in UTC with ms when time range is minute or less', () => { // Test Proxies in general const p = getFieldDisplayValuesProxy({ frame: dataShortTimeRange, rowIndex: 0 }); const time = p.Time; expect(time.numeric).toEqual(1); expect(time.text).toEqual('1970-01-01 00:00:00.001'); // Should get to the same values by name or index const time2 = p[0]; expect(time2.toString()).toEqual(time.toString()); }); it('should format the time values in UTC without ms when time range is over a minute', () => { const p = getFieldDisplayValuesProxy({ frame: dataLongTimeRange, rowIndex: 0 }); const time = p.Time; expect(time.text).toEqual('1970-01-01 00:00:01'); }); it('Lookup by name, index, or displayName', () => { const p = getFieldDisplayValuesProxy({ frame: dataShortTimeRange, rowIndex: 2 }); expect(p.power.numeric).toEqual(300); expect(p['power'].numeric).toEqual(300); expect(p['POWAH!'].numeric).toEqual(300); expect(p['The Power'].numeric).toEqual(300); expect(p[1].numeric).toEqual(300); }); it('should return undefined when missing', () => { const p = getFieldDisplayValuesProxy({ frame: dataShortTimeRange, rowIndex: 0 }); expect(p.xyz).toBeUndefined(); expect(p[100]).toBeUndefined(); }); it('should use default display processor if display is not defined', () => { const p = getFieldDisplayValuesProxy({ frame: new MutableDataFrame({ fields: [{ name: 'test', values: [1, 2] }] }), rowIndex: 0, }); expect(p.test.text).toBe('1'); expect(p.test.numeric).toBe(1); expect(p.test.toString()).toBe('1'); }); });
packages/grafana-data/src/field/getFieldDisplayValuesProxy.test.tsx
0
https://github.com/grafana/grafana/commit/a1b8b5d123bde86fcfd7195c01b43d83a687d0ad
[ 0.00018006782920565456, 0.00017659159493632615, 0.00017439592920709401, 0.00017587275942787528, 0.000002026830770773813 ]
{ "id": 5, "code_window": [ "\t\tassert.Equal(t, int64(0), query.Result.Viewers)\n", "\t\tassert.Equal(t, int64(3), query.Result.Admins)\n", "\t\tassert.Equal(t, int64(0), query.Result.LibraryPanels)\n", "\t\tassert.Equal(t, int64(0), query.Result.LibraryVariables)\n", "\t})\n", "\n", "\tt.Run(\"Get system user count stats should not results in error\", func(t *testing.T) {\n", "\t\tquery := models.GetSystemUserCountStatsQuery{}\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tassert.Equal(t, int64(1), query.Result.APIKeys)\n" ], "file_path": "pkg/services/sqlstore/stats_test.go", "type": "add", "edit_start_line_idx": 29 }
import { reducerTester } from '../../../../test/core/redux/reducerTester'; import { initialVariableInspectState, initInspect, variableInspectReducer, VariableInspectState } from './reducer'; import { textboxBuilder } from '../shared/testing/builders'; describe('variableInspectReducer', () => { describe('when initInspect is dispatched', () => { it('then state should be correct', () => { const variable = textboxBuilder().withId('text').withName('text').build(); reducerTester<VariableInspectState>() .givenReducer(variableInspectReducer, { ...initialVariableInspectState }) .whenActionIsDispatched( initInspect({ usagesNetwork: [{ edges: [], nodes: [], showGraph: true, variable }], usages: [{ variable, tree: {} }], }) ) .thenStateShouldEqual({ usagesNetwork: [{ edges: [], nodes: [], showGraph: true, variable }], usages: [{ variable, tree: {} }], }); }); }); });
public/app/features/variables/inspect/reducer.test.ts
0
https://github.com/grafana/grafana/commit/a1b8b5d123bde86fcfd7195c01b43d83a687d0ad
[ 0.0001792090042727068, 0.0001762189349392429, 0.00017205959011334926, 0.00017738822498358786, 0.0000030335843348439084 ]
{ "id": 5, "code_window": [ "\t\tassert.Equal(t, int64(0), query.Result.Viewers)\n", "\t\tassert.Equal(t, int64(3), query.Result.Admins)\n", "\t\tassert.Equal(t, int64(0), query.Result.LibraryPanels)\n", "\t\tassert.Equal(t, int64(0), query.Result.LibraryVariables)\n", "\t})\n", "\n", "\tt.Run(\"Get system user count stats should not results in error\", func(t *testing.T) {\n", "\t\tquery := models.GetSystemUserCountStatsQuery{}\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tassert.Equal(t, int64(1), query.Result.APIKeys)\n" ], "file_path": "pkg/services/sqlstore/stats_test.go", "type": "add", "edit_start_line_idx": 29 }
script.inline: on script.indexed: on
devenv/docker/blocks/elastic7/elasticsearch.yml
0
https://github.com/grafana/grafana/commit/a1b8b5d123bde86fcfd7195c01b43d83a687d0ad
[ 0.0001764640910550952, 0.0001764640910550952, 0.0001764640910550952, 0.0001764640910550952, 0 ]
{ "id": 6, "code_window": [ "\t// force renewal of user stats\n", "\terr = updateUserRoleCountsIfNecessary(context.Background(), true)\n", "\trequire.NoError(t, err)\n", "}" ], "labels": [ "keep", "keep", "add", "keep" ], "after_edit": [ "\n", "\t// add 1st api key\n", "\taddAPIKeyCmd := &models.AddApiKeyCommand{OrgId: org.Id, Name: \"Test key 1\", Key: \"secret-key\", Role: models.ROLE_VIEWER}\n", "\terr = sqlStore.AddAPIKey(context.Background(), addAPIKeyCmd)\n", "\trequire.NoError(t, err)\n" ], "file_path": "pkg/services/sqlstore/stats_test.go", "type": "add", "edit_start_line_idx": 127 }
package service import ( "bytes" "context" "errors" "io/ioutil" "net/http" "net/http/httptest" "runtime" "testing" "time" "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/components/simplejson" "github.com/grafana/grafana/pkg/infra/kvstore" "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/infra/usagestats" "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/plugins" "github.com/grafana/grafana/pkg/services/sqlstore" "github.com/grafana/grafana/pkg/setting" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) // This is to ensure that the interface contract is held by the implementation func Test_InterfaceContractValidity(t *testing.T) { newUsageStats := func() usagestats.Service { return &UsageStats{} } v, ok := newUsageStats().(*UsageStats) assert.NotNil(t, v) assert.True(t, ok) } func TestMetrics(t *testing.T) { t.Run("When sending usage stats", func(t *testing.T) { uss := createService(t, setting.Cfg{}) setupSomeDataSourcePlugins(t, uss) var getSystemStatsQuery *models.GetSystemStatsQuery uss.Bus.AddHandlerCtx(func(ctx context.Context, query *models.GetSystemStatsQuery) error { query.Result = &models.SystemStats{ Dashboards: 1, Datasources: 2, Users: 3, Admins: 31, Editors: 32, Viewers: 33, ActiveUsers: 4, ActiveAdmins: 21, ActiveEditors: 22, ActiveViewers: 23, ActiveSessions: 24, DailyActiveUsers: 25, DailyActiveAdmins: 26, DailyActiveEditors: 27, DailyActiveViewers: 28, DailyActiveSessions: 29, Orgs: 5, Playlists: 6, Alerts: 7, Stars: 8, Folders: 9, DashboardPermissions: 10, FolderPermissions: 11, ProvisionedDashboards: 12, Snapshots: 13, Teams: 14, AuthTokens: 15, DashboardVersions: 16, Annotations: 17, AlertRules: 18, LibraryPanels: 19, LibraryVariables: 20, DashboardsViewersCanAdmin: 3, DashboardsViewersCanEdit: 2, FoldersViewersCanAdmin: 1, FoldersViewersCanEdit: 5, } getSystemStatsQuery = query return nil }) var getDataSourceStatsQuery *models.GetDataSourceStatsQuery uss.Bus.AddHandlerCtx(func(ctx context.Context, query *models.GetDataSourceStatsQuery) error { query.Result = []*models.DataSourceStats{ { Type: models.DS_ES, Count: 9, }, { Type: models.DS_PROMETHEUS, Count: 10, }, { Type: "unknown_ds", Count: 11, }, { Type: "unknown_ds2", Count: 12, }, } getDataSourceStatsQuery = query return nil }) var getESDatasSourcesQuery *models.GetDataSourcesByTypeQuery uss.Bus.AddHandlerCtx(func(ctx context.Context, query *models.GetDataSourcesByTypeQuery) error { query.Result = []*models.DataSource{ { JsonData: simplejson.NewFromAny(map[string]interface{}{ "esVersion": 2, }), }, { JsonData: simplejson.NewFromAny(map[string]interface{}{ "esVersion": 2, }), }, { JsonData: simplejson.NewFromAny(map[string]interface{}{ "esVersion": 70, }), }, } getESDatasSourcesQuery = query return nil }) var getDataSourceAccessStatsQuery *models.GetDataSourceAccessStatsQuery uss.Bus.AddHandlerCtx(func(ctx context.Context, query *models.GetDataSourceAccessStatsQuery) error { query.Result = []*models.DataSourceAccessStats{ { Type: models.DS_ES, Access: "direct", Count: 1, }, { Type: models.DS_ES, Access: "proxy", Count: 2, }, { Type: models.DS_PROMETHEUS, Access: "proxy", Count: 3, }, { Type: "unknown_ds", Access: "proxy", Count: 4, }, { Type: "unknown_ds2", Access: "", Count: 5, }, { Type: "unknown_ds3", Access: "direct", Count: 6, }, { Type: "unknown_ds4", Access: "direct", Count: 7, }, { Type: "unknown_ds5", Access: "proxy", Count: 8, }, } getDataSourceAccessStatsQuery = query return nil }) var getAlertNotifierUsageStatsQuery *models.GetAlertNotifierUsageStatsQuery uss.Bus.AddHandlerCtx(func(ctx context.Context, query *models.GetAlertNotifierUsageStatsQuery) error { query.Result = []*models.NotifierUsageStats{ { Type: "slack", Count: 1, }, { Type: "webhook", Count: 2, }, } getAlertNotifierUsageStatsQuery = query return nil }) createConcurrentTokens(t, uss.SQLStore) uss.oauthProviders = map[string]bool{ "github": true, "gitlab": true, "azuread": true, "google": true, "generic_oauth": true, "grafana_com": true, } err := uss.sendUsageStats(context.Background()) require.NoError(t, err) t.Run("Given reporting not enabled and sending usage stats", func(t *testing.T) { origSendUsageStats := sendUsageStats t.Cleanup(func() { sendUsageStats = origSendUsageStats }) statsSent := false sendUsageStats = func(uss *UsageStats, b *bytes.Buffer) { statsSent = true } uss.Cfg.ReportingEnabled = false err := uss.sendUsageStats(context.Background()) require.NoError(t, err) require.False(t, statsSent) assert.Nil(t, getSystemStatsQuery) assert.Nil(t, getDataSourceStatsQuery) assert.Nil(t, getDataSourceAccessStatsQuery) assert.Nil(t, getESDatasSourcesQuery) }) t.Run("Given reporting enabled, stats should be gathered and sent to HTTP endpoint", func(t *testing.T) { origCfg := uss.Cfg t.Cleanup(func() { uss.Cfg = origCfg }) uss.Cfg = &setting.Cfg{ ReportingEnabled: true, BuildVersion: "5.0.0", AnonymousEnabled: true, BasicAuthEnabled: true, LDAPEnabled: true, AuthProxyEnabled: true, Packaging: "deb", ReportingDistributor: "hosted-grafana", } ch := make(chan httpResp) ticker := time.NewTicker(2 * time.Second) ts := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { buf, err := ioutil.ReadAll(r.Body) if err != nil { t.Logf("Fake HTTP handler received an error: %s", err.Error()) ch <- httpResp{ err: err, } return } require.NoError(t, err, "Failed to read response body, err=%v", err) t.Logf("Fake HTTP handler received a response") ch <- httpResp{ responseBuffer: bytes.NewBuffer(buf), req: r, } })) t.Cleanup(ts.Close) t.Cleanup(func() { close(ch) }) usageStatsURL = ts.URL err := uss.sendUsageStats(context.Background()) require.NoError(t, err) // Wait for fake HTTP server to receive a request var resp httpResp select { case resp = <-ch: require.NoError(t, resp.err, "Fake server experienced an error") case <-ticker.C: t.Fatalf("Timed out waiting for HTTP request") } t.Logf("Received response from fake HTTP server: %+v\n", resp) assert.NotNil(t, getSystemStatsQuery) assert.NotNil(t, getDataSourceStatsQuery) assert.NotNil(t, getESDatasSourcesQuery) assert.NotNil(t, getDataSourceAccessStatsQuery) assert.NotNil(t, getAlertNotifierUsageStatsQuery) assert.NotNil(t, resp.req) assert.Equal(t, http.MethodPost, resp.req.Method) assert.Equal(t, "application/json", resp.req.Header.Get("Content-Type")) require.NotNil(t, resp.responseBuffer) j, err := simplejson.NewFromReader(resp.responseBuffer) require.NoError(t, err) assert.Equal(t, "5_0_0", j.Get("version").MustString()) assert.Equal(t, runtime.GOOS, j.Get("os").MustString()) assert.Equal(t, runtime.GOARCH, j.Get("arch").MustString()) usageId := uss.GetUsageStatsId(context.Background()) assert.NotEmpty(t, usageId) assert.Equal(t, usageId, j.Get("usageStatsId").MustString()) metrics := j.Get("metrics") assert.Equal(t, getSystemStatsQuery.Result.Dashboards, metrics.Get("stats.dashboards.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.Users, metrics.Get("stats.users.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.Admins, metrics.Get("stats.admins.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.Editors, metrics.Get("stats.editors.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.Viewers, metrics.Get("stats.viewers.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.Orgs, metrics.Get("stats.orgs.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.Playlists, metrics.Get("stats.playlist.count").MustInt64()) assert.Equal(t, uss.appCount(context.Background()), metrics.Get("stats.plugins.apps.count").MustInt()) assert.Equal(t, uss.panelCount(context.Background()), metrics.Get("stats.plugins.panels.count").MustInt()) assert.Equal(t, uss.dataSourceCount(context.Background()), metrics.Get("stats.plugins.datasources.count").MustInt()) assert.Equal(t, getSystemStatsQuery.Result.Alerts, metrics.Get("stats.alerts.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.ActiveUsers, metrics.Get("stats.active_users.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.ActiveAdmins, metrics.Get("stats.active_admins.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.ActiveEditors, metrics.Get("stats.active_editors.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.ActiveViewers, metrics.Get("stats.active_viewers.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.ActiveSessions, metrics.Get("stats.active_sessions.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.DailyActiveUsers, metrics.Get("stats.daily_active_users.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.DailyActiveAdmins, metrics.Get("stats.daily_active_admins.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.DailyActiveEditors, metrics.Get("stats.daily_active_editors.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.DailyActiveViewers, metrics.Get("stats.daily_active_viewers.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.DailyActiveSessions, metrics.Get("stats.daily_active_sessions.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.Datasources, metrics.Get("stats.datasources.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.Stars, metrics.Get("stats.stars.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.Folders, metrics.Get("stats.folders.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.DashboardPermissions, metrics.Get("stats.dashboard_permissions.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.FolderPermissions, metrics.Get("stats.folder_permissions.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.ProvisionedDashboards, metrics.Get("stats.provisioned_dashboards.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.Snapshots, metrics.Get("stats.snapshots.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.Teams, metrics.Get("stats.teams.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.DashboardsViewersCanEdit, metrics.Get("stats.dashboards_viewers_can_edit.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.DashboardsViewersCanAdmin, metrics.Get("stats.dashboards_viewers_can_admin.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.FoldersViewersCanEdit, metrics.Get("stats.folders_viewers_can_edit.count").MustInt64()) assert.Equal(t, getSystemStatsQuery.Result.FoldersViewersCanAdmin, metrics.Get("stats.folders_viewers_can_admin.count").MustInt64()) assert.Equal(t, 15, metrics.Get("stats.total_auth_token.count").MustInt()) assert.Equal(t, 5, metrics.Get("stats.avg_auth_token_per_user.count").MustInt()) assert.Equal(t, 16, metrics.Get("stats.dashboard_versions.count").MustInt()) assert.Equal(t, 17, metrics.Get("stats.annotations.count").MustInt()) assert.Equal(t, 18, metrics.Get("stats.alert_rules.count").MustInt()) assert.Equal(t, 19, metrics.Get("stats.library_panels.count").MustInt()) assert.Equal(t, 20, metrics.Get("stats.library_variables.count").MustInt()) assert.Equal(t, 0, metrics.Get("stats.live_users.count").MustInt()) assert.Equal(t, 0, metrics.Get("stats.live_clients.count").MustInt()) assert.Equal(t, 9, metrics.Get("stats.ds."+models.DS_ES+".count").MustInt()) assert.Equal(t, 10, metrics.Get("stats.ds."+models.DS_PROMETHEUS+".count").MustInt()) assert.Equal(t, 2, metrics.Get("stats.ds."+models.DS_ES+".v2.count").MustInt()) assert.Equal(t, 1, metrics.Get("stats.ds."+models.DS_ES+".v70.count").MustInt()) assert.Equal(t, 11+12, metrics.Get("stats.ds.other.count").MustInt()) assert.Equal(t, 1, metrics.Get("stats.ds_access."+models.DS_ES+".direct.count").MustInt()) assert.Equal(t, 2, metrics.Get("stats.ds_access."+models.DS_ES+".proxy.count").MustInt()) assert.Equal(t, 3, metrics.Get("stats.ds_access."+models.DS_PROMETHEUS+".proxy.count").MustInt()) assert.Equal(t, 6+7, metrics.Get("stats.ds_access.other.direct.count").MustInt()) assert.Equal(t, 4+8, metrics.Get("stats.ds_access.other.proxy.count").MustInt()) assert.Equal(t, 1, metrics.Get("stats.alert_notifiers.slack.count").MustInt()) assert.Equal(t, 2, metrics.Get("stats.alert_notifiers.webhook.count").MustInt()) assert.Equal(t, 1, metrics.Get("stats.auth_enabled.anonymous.count").MustInt()) assert.Equal(t, 1, metrics.Get("stats.auth_enabled.basic_auth.count").MustInt()) assert.Equal(t, 1, metrics.Get("stats.auth_enabled.ldap.count").MustInt()) assert.Equal(t, 1, metrics.Get("stats.auth_enabled.auth_proxy.count").MustInt()) assert.Equal(t, 1, metrics.Get("stats.auth_enabled.oauth_github.count").MustInt()) assert.Equal(t, 1, metrics.Get("stats.auth_enabled.oauth_gitlab.count").MustInt()) assert.Equal(t, 1, metrics.Get("stats.auth_enabled.oauth_google.count").MustInt()) assert.Equal(t, 1, metrics.Get("stats.auth_enabled.oauth_azuread.count").MustInt()) assert.Equal(t, 1, metrics.Get("stats.auth_enabled.oauth_generic_oauth.count").MustInt()) assert.Equal(t, 1, metrics.Get("stats.auth_enabled.oauth_grafana_com.count").MustInt()) assert.Equal(t, 1, metrics.Get("stats.packaging.deb.count").MustInt()) assert.Equal(t, 1, metrics.Get("stats.distributor.hosted-grafana.count").MustInt()) assert.Equal(t, 1, metrics.Get("stats.auth_token_per_user_le_3").MustInt()) assert.Equal(t, 2, metrics.Get("stats.auth_token_per_user_le_6").MustInt()) assert.Equal(t, 3, metrics.Get("stats.auth_token_per_user_le_9").MustInt()) assert.Equal(t, 4, metrics.Get("stats.auth_token_per_user_le_12").MustInt()) assert.Equal(t, 5, metrics.Get("stats.auth_token_per_user_le_15").MustInt()) assert.Equal(t, 6, metrics.Get("stats.auth_token_per_user_le_inf").MustInt()) assert.LessOrEqual(t, 60, metrics.Get("stats.uptime").MustInt()) assert.Greater(t, 70, metrics.Get("stats.uptime").MustInt()) }) }) t.Run("When updating total stats", func(t *testing.T) { uss := createService(t, setting.Cfg{}) uss.Cfg.MetricsEndpointEnabled = true uss.Cfg.MetricsEndpointDisableTotalStats = false getSystemStatsWasCalled := false uss.Bus.AddHandlerCtx(func(ctx context.Context, query *models.GetSystemStatsQuery) error { query.Result = &models.SystemStats{} getSystemStatsWasCalled = true return nil }) t.Run("When metrics is disabled and total stats is enabled, stats should not be updated", func(t *testing.T) { uss.Cfg.MetricsEndpointEnabled = false uss.Cfg.MetricsEndpointDisableTotalStats = false uss.updateTotalStats(context.Background()) assert.False(t, getSystemStatsWasCalled) }) t.Run("When metrics is enabled and total stats is disabled, stats should not be updated", func(t *testing.T) { uss.Cfg.MetricsEndpointEnabled = true uss.Cfg.MetricsEndpointDisableTotalStats = true uss.updateTotalStats(context.Background()) assert.False(t, getSystemStatsWasCalled) }) t.Run("When metrics is disabled and total stats is disabled, stats should not be updated", func(t *testing.T) { uss.Cfg.MetricsEndpointEnabled = false uss.Cfg.MetricsEndpointDisableTotalStats = true uss.updateTotalStats(context.Background()) assert.False(t, getSystemStatsWasCalled) }) t.Run("When metrics is enabled and total stats is enabled, stats should be updated", func(t *testing.T) { uss.Cfg.MetricsEndpointEnabled = true uss.Cfg.MetricsEndpointDisableTotalStats = false uss.updateTotalStats(context.Background()) assert.True(t, getSystemStatsWasCalled) }) }) t.Run("When registering a metric", func(t *testing.T) { uss := createService(t, setting.Cfg{}) metricName := "stats.test_metric.count" t.Run("Adds a new metric to the external metrics", func(t *testing.T) { uss.RegisterMetricsFunc(func(context.Context) (map[string]interface{}, error) { return map[string]interface{}{metricName: 1}, nil }) metrics, err := uss.externalMetrics[0](context.Background()) require.NoError(t, err) assert.Equal(t, map[string]interface{}{metricName: 1}, metrics) }) }) t.Run("When getting usage report", func(t *testing.T) { uss := createService(t, setting.Cfg{}) metricName := "stats.test_metric.count" uss.Bus.AddHandlerCtx(func(ctx context.Context, query *models.GetSystemStatsQuery) error { query.Result = &models.SystemStats{} return nil }) uss.Bus.AddHandlerCtx(func(ctx context.Context, query *models.GetDataSourceStatsQuery) error { query.Result = []*models.DataSourceStats{} return nil }) uss.Bus.AddHandlerCtx(func(ctx context.Context, query *models.GetDataSourcesByTypeQuery) error { query.Result = []*models.DataSource{} return nil }) uss.Bus.AddHandlerCtx(func(ctx context.Context, query *models.GetDataSourceAccessStatsQuery) error { query.Result = []*models.DataSourceAccessStats{} return nil }) uss.Bus.AddHandlerCtx(func(ctx context.Context, query *models.GetAlertNotifierUsageStatsQuery) error { query.Result = []*models.NotifierUsageStats{} return nil }) createConcurrentTokens(t, uss.SQLStore) t.Run("Should include metrics for concurrent users", func(t *testing.T) { report, err := uss.GetUsageReport(context.Background()) require.NoError(t, err) assert.Equal(t, int32(1), report.Metrics["stats.auth_token_per_user_le_3"]) assert.Equal(t, int32(2), report.Metrics["stats.auth_token_per_user_le_6"]) assert.Equal(t, int32(3), report.Metrics["stats.auth_token_per_user_le_9"]) assert.Equal(t, int32(4), report.Metrics["stats.auth_token_per_user_le_12"]) assert.Equal(t, int32(5), report.Metrics["stats.auth_token_per_user_le_15"]) assert.Equal(t, int32(6), report.Metrics["stats.auth_token_per_user_le_inf"]) }) t.Run("Should include external metrics", func(t *testing.T) { uss.RegisterMetricsFunc(func(context.Context) (map[string]interface{}, error) { return map[string]interface{}{metricName: 1}, nil }) report, err := uss.GetUsageReport(context.Background()) require.NoError(t, err, "Expected no error") metric := report.Metrics[metricName] assert.Equal(t, 1, metric) }) }) t.Run("When registering external metrics", func(t *testing.T) { uss := createService(t, setting.Cfg{}) metrics := map[string]interface{}{"stats.test_metric.count": 1, "stats.test_metric_second.count": 2} extMetricName := "stats.test_external_metric.count" uss.RegisterMetricsFunc(func(context.Context) (map[string]interface{}, error) { return map[string]interface{}{extMetricName: 1}, nil }) uss.registerExternalMetrics(context.Background(), metrics) assert.Equal(t, 1, metrics[extMetricName]) t.Run("When loading a metric results to an error", func(t *testing.T) { uss.RegisterMetricsFunc(func(context.Context) (map[string]interface{}, error) { return map[string]interface{}{extMetricName: 1}, nil }) extErrorMetricName := "stats.test_external_metric_error.count" t.Run("Should not add it to metrics", func(t *testing.T) { uss.RegisterMetricsFunc(func(context.Context) (map[string]interface{}, error) { return map[string]interface{}{extErrorMetricName: 1}, errors.New("some error") }) uss.registerExternalMetrics(context.Background(), metrics) extErrorMetric := metrics[extErrorMetricName] extMetric := metrics[extMetricName] require.Nil(t, extErrorMetric, "Invalid metric should not be added") assert.Equal(t, 1, extMetric) assert.Len(t, metrics, 3, "Expected only one available metric") }) }) }) } type fakePluginStore struct { plugins.Store plugins map[string]plugins.PluginDTO } func (pr fakePluginStore) Plugin(_ context.Context, pluginID string) (plugins.PluginDTO, bool) { p, exists := pr.plugins[pluginID] return p, exists } func (pr fakePluginStore) Plugins(_ context.Context, pluginTypes ...plugins.Type) []plugins.PluginDTO { var result []plugins.PluginDTO for _, v := range pr.plugins { for _, t := range pluginTypes { if v.Type == t { result = append(result, v) } } } return result } func setupSomeDataSourcePlugins(t *testing.T, uss *UsageStats) { t.Helper() uss.pluginStore = &fakePluginStore{ plugins: map[string]plugins.PluginDTO{ models.DS_ES: { Signature: "internal", }, models.DS_PROMETHEUS: { Signature: "internal", }, models.DS_GRAPHITE: { Signature: "internal", }, models.DS_MYSQL: { Signature: "internal", }, }, } } type httpResp struct { req *http.Request responseBuffer *bytes.Buffer err error } func createService(t *testing.T, cfg setting.Cfg) *UsageStats { t.Helper() sqlStore := sqlstore.InitTestDB(t) return &UsageStats{ Bus: bus.New(), Cfg: &cfg, SQLStore: sqlStore, externalMetrics: make([]usagestats.MetricsFunc, 0), pluginStore: &fakePluginStore{}, kvStore: kvstore.WithNamespace(kvstore.ProvideService(sqlStore), 0, "infra.usagestats"), log: log.New("infra.usagestats"), startTime: time.Now().Add(-1 * time.Minute), } }
pkg/infra/usagestats/service/usage_stats_test.go
1
https://github.com/grafana/grafana/commit/a1b8b5d123bde86fcfd7195c01b43d83a687d0ad
[ 0.022052155807614326, 0.001520237186923623, 0.0001628638565307483, 0.00017137060058303177, 0.003911640960723162 ]
{ "id": 6, "code_window": [ "\t// force renewal of user stats\n", "\terr = updateUserRoleCountsIfNecessary(context.Background(), true)\n", "\trequire.NoError(t, err)\n", "}" ], "labels": [ "keep", "keep", "add", "keep" ], "after_edit": [ "\n", "\t// add 1st api key\n", "\taddAPIKeyCmd := &models.AddApiKeyCommand{OrgId: org.Id, Name: \"Test key 1\", Key: \"secret-key\", Role: models.ROLE_VIEWER}\n", "\terr = sqlStore.AddAPIKey(context.Background(), addAPIKeyCmd)\n", "\trequire.NoError(t, err)\n" ], "file_path": "pkg/services/sqlstore/stats_test.go", "type": "add", "edit_start_line_idx": 127 }
import { lastValueFrom, Observable, of } from 'rxjs'; import { DataFrame, dataFrameToJSON, DataSourceInstanceSettings, FieldType, getDefaultTimeRange, LoadingState, MutableDataFrame, PluginType, } from '@grafana/data'; import { createFetchResponse } from 'test/helpers/createFetchResponse'; import { BackendDataSourceResponse, FetchResponse, setBackendSrv, setDataSourceSrv } from '@grafana/runtime'; import { DEFAULT_LIMIT, TempoJsonData, TempoDatasource, TempoQuery } from './datasource'; import mockJson from './mockJsonResponse.json'; describe('Tempo data source', () => { it('parses json fields from backend', async () => { setupBackendSrv( new MutableDataFrame({ fields: [ { name: 'traceID', values: ['04450900759028499335'] }, { name: 'spanID', values: ['4322526419282105830'] }, { name: 'parentSpanID', values: [''] }, { name: 'operationName', values: ['store.validateQueryTimeRange'] }, { name: 'startTime', values: [1619712655875.4539] }, { name: 'duration', values: [14.984] }, { name: 'serviceTags', values: ['{"key":"servicetag1","value":"service"}'] }, { name: 'logs', values: ['{"timestamp":12345,"fields":[{"key":"count","value":1}]}'] }, { name: 'tags', values: ['{"key":"tag1","value":"val1"}'] }, { name: 'serviceName', values: ['service'] }, ], }) ); const ds = new TempoDatasource(defaultSettings); const response = await lastValueFrom(ds.query({ targets: [{ refId: 'refid1' }] } as any)); expect( (response.data[0] as DataFrame).fields.map((f) => ({ name: f.name, values: f.values.toArray(), })) ).toMatchObject([ { name: 'traceID', values: ['04450900759028499335'] }, { name: 'spanID', values: ['4322526419282105830'] }, { name: 'parentSpanID', values: [''] }, { name: 'operationName', values: ['store.validateQueryTimeRange'] }, { name: 'startTime', values: [1619712655875.4539] }, { name: 'duration', values: [14.984] }, { name: 'serviceTags', values: [{ key: 'servicetag1', value: 'service' }] }, { name: 'logs', values: [{ timestamp: 12345, fields: [{ key: 'count', value: 1 }] }] }, { name: 'tags', values: [{ key: 'tag1', value: 'val1' }] }, { name: 'serviceName', values: ['service'] }, ]); expect( (response.data[1] as DataFrame).fields.map((f) => ({ name: f.name, values: f.values.toArray(), })) ).toMatchObject([ { name: 'id', values: ['4322526419282105830'] }, { name: 'title', values: ['service'] }, { name: 'subTitle', values: ['store.validateQueryTimeRange'] }, { name: 'mainStat', values: ['14.98ms (100%)'] }, { name: 'secondaryStat', values: ['14.98ms (100%)'] }, { name: 'color', values: [1.000007560204647] }, ]); expect( (response.data[2] as DataFrame).fields.map((f) => ({ name: f.name, values: f.values.toArray(), })) ).toMatchObject([ { name: 'id', values: [] }, { name: 'target', values: [] }, { name: 'source', values: [] }, ]); }); it('runs service graph queries', async () => { const ds = new TempoDatasource({ ...defaultSettings, jsonData: { serviceMap: { datasourceUid: 'prom', }, }, }); setDataSourceSrv(backendSrvWithPrometheus as any); const response = await lastValueFrom( ds.query({ targets: [{ queryType: 'serviceMap' }], range: getDefaultTimeRange() } as any) ); expect(response.data).toHaveLength(2); expect(response.data[0].name).toBe('Nodes'); expect(response.data[0].fields[0].values.length).toBe(3); expect(response.data[0].fields[0].config.links.length).toBeGreaterThan(0); expect(response.data[1].name).toBe('Edges'); expect(response.data[1].fields[0].values.length).toBe(2); expect(response.state).toBe(LoadingState.Done); }); it('should handle json file upload', async () => { const ds = new TempoDatasource(defaultSettings); ds.uploadedJson = JSON.stringify(mockJson); const response = await lastValueFrom( ds.query({ targets: [{ queryType: 'upload', refId: 'A' }], } as any) ); const field = response.data[0].fields[0]; expect(field.name).toBe('traceID'); expect(field.type).toBe(FieldType.string); expect(field.values.get(0)).toBe('60ba2abb44f13eae'); expect(field.values.length).toBe(6); }); it('should fail on invalid json file upload', async () => { const ds = new TempoDatasource(defaultSettings); ds.uploadedJson = JSON.stringify(mockInvalidJson); const response = await lastValueFrom( ds.query({ targets: [{ queryType: 'upload', refId: 'A' }], } as any) ); expect(response.error?.message).toBeDefined(); expect(response.data.length).toBe(0); }); it('should build search query correctly', () => { const ds = new TempoDatasource(defaultSettings); const tempoQuery: TempoQuery = { queryType: 'search', refId: 'A', query: '', serviceName: 'frontend', spanName: '/config', search: 'root.http.status_code=500', minDuration: '1ms', maxDuration: '100s', limit: 10, }; const builtQuery = ds.buildSearchQuery(tempoQuery); expect(builtQuery).toStrictEqual({ tags: 'root.http.status_code=500 service.name="frontend" name="/config"', minDuration: '1ms', maxDuration: '100s', limit: 10, }); }); it('should include a default limit', () => { const ds = new TempoDatasource(defaultSettings); const tempoQuery: TempoQuery = { queryType: 'search', refId: 'A', query: '', search: '', }; const builtQuery = ds.buildSearchQuery(tempoQuery); expect(builtQuery).toStrictEqual({ tags: '', limit: DEFAULT_LIMIT, }); }); it('formats native search query history correctly', () => { const ds = new TempoDatasource(defaultSettings); const tempoQuery: TempoQuery = { queryType: 'nativeSearch', refId: 'A', query: '', serviceName: 'frontend', spanName: '/config', search: 'root.http.status_code=500', minDuration: '1ms', maxDuration: '100s', limit: 10, }; const result = ds.getQueryDisplayText(tempoQuery); expect(result).toBe( 'Service Name: frontend, Span Name: /config, Search: root.http.status_code=500, Min Duration: 1ms, Max Duration: 100s, Limit: 10' ); }); }); const backendSrvWithPrometheus = { async get(uid: string) { if (uid === 'prom') { return { query() { return of({ data: [totalsPromMetric, secondsPromMetric, failedPromMetric] }); }, }; } throw new Error('unexpected uid'); }, }; function setupBackendSrv(frame: DataFrame) { setBackendSrv({ fetch(): Observable<FetchResponse<BackendDataSourceResponse>> { return of( createFetchResponse({ results: { refid1: { frames: [dataFrameToJSON(frame)], }, }, }) ); }, } as any); } const defaultSettings: DataSourceInstanceSettings<TempoJsonData> = { id: 0, uid: '0', type: 'tracing', name: 'tempo', access: 'proxy', meta: { id: 'tempo', name: 'tempo', type: PluginType.datasource, info: {} as any, module: '', baseUrl: '', }, jsonData: { nodeGraph: { enabled: true, }, }, }; const totalsPromMetric = new MutableDataFrame({ refId: 'traces_service_graph_request_total', fields: [ { name: 'Time', values: [1628169788000, 1628169788000] }, { name: 'client', values: ['app', 'lb'] }, { name: 'instance', values: ['127.0.0.1:12345', '127.0.0.1:12345'] }, { name: 'job', values: ['local_scrape', 'local_scrape'] }, { name: 'server', values: ['db', 'app'] }, { name: 'tempo_config', values: ['default', 'default'] }, { name: 'Value #traces_service_graph_request_total', values: [10, 20] }, ], }); const secondsPromMetric = new MutableDataFrame({ refId: 'traces_service_graph_request_server_seconds_sum', fields: [ { name: 'Time', values: [1628169788000, 1628169788000] }, { name: 'client', values: ['app', 'lb'] }, { name: 'instance', values: ['127.0.0.1:12345', '127.0.0.1:12345'] }, { name: 'job', values: ['local_scrape', 'local_scrape'] }, { name: 'server', values: ['db', 'app'] }, { name: 'tempo_config', values: ['default', 'default'] }, { name: 'Value #traces_service_graph_request_server_seconds_sum', values: [10, 40] }, ], }); const failedPromMetric = new MutableDataFrame({ refId: 'traces_service_graph_request_failed_total', fields: [ { name: 'Time', values: [1628169788000, 1628169788000] }, { name: 'client', values: ['app', 'lb'] }, { name: 'instance', values: ['127.0.0.1:12345', '127.0.0.1:12345'] }, { name: 'job', values: ['local_scrape', 'local_scrape'] }, { name: 'server', values: ['db', 'app'] }, { name: 'tempo_config', values: ['default', 'default'] }, { name: 'Value #traces_service_graph_request_failed_total', values: [2, 15] }, ], }); const mockInvalidJson = { batches: [ { resource: { attributes: [], }, instrumentation_library_spans: [ { instrumentation_library: {}, spans: [ { trace_id: 'AAAAAAAAAABguiq7RPE+rg==', span_id: 'cmteMBAvwNA=', parentSpanId: 'OY8PIaPbma4=', name: 'HTTP GET - root', kind: 'SPAN_KIND_SERVER', startTimeUnixNano: '1627471657255809000', endTimeUnixNano: '1627471657256268000', attributes: [ { key: 'http.status_code', value: { intValue: '200' } }, { key: 'http.method', value: { stringValue: 'GET' } }, { key: 'http.url', value: { stringValue: '/' } }, { key: 'component', value: { stringValue: 'net/http' } }, ], status: {}, }, ], }, ], }, ], };
public/app/plugins/datasource/tempo/datasource.test.ts
0
https://github.com/grafana/grafana/commit/a1b8b5d123bde86fcfd7195c01b43d83a687d0ad
[ 0.00017667167412582785, 0.00017120590200647712, 0.00016648774908389896, 0.00017125887097790837, 0.000002570789092715131 ]
{ "id": 6, "code_window": [ "\t// force renewal of user stats\n", "\terr = updateUserRoleCountsIfNecessary(context.Background(), true)\n", "\trequire.NoError(t, err)\n", "}" ], "labels": [ "keep", "keep", "add", "keep" ], "after_edit": [ "\n", "\t// add 1st api key\n", "\taddAPIKeyCmd := &models.AddApiKeyCommand{OrgId: org.Id, Name: \"Test key 1\", Key: \"secret-key\", Role: models.ROLE_VIEWER}\n", "\terr = sqlStore.AddAPIKey(context.Background(), addAPIKeyCmd)\n", "\trequire.NoError(t, err)\n" ], "file_path": "pkg/services/sqlstore/stats_test.go", "type": "add", "edit_start_line_idx": 127 }
import React, { Component } from 'react'; import { PanelProps } from '@grafana/data'; import { PanelOptions } from './models.gen'; import { ElementState } from 'app/features/canvas/runtime/element'; import { iconItem } from 'app/features/canvas/elements/icon'; import { ColorDimensionConfig, DimensionContext, getColorDimensionFromData, getResourceDimensionFromData, getScalarDimensionFromData, getScaleDimensionFromData, getTextDimensionFromData, ResourceDimensionConfig, ScalarDimensionConfig, ScaleDimensionConfig, TextDimensionConfig, } from 'app/features/dimensions'; interface Props extends PanelProps<PanelOptions> {} export class IconPanel extends Component<Props> { private element: ElementState; constructor(props: Props) { super(props); this.element = this.initElement(props); } initElement = (props: Props) => { this.element = new ElementState(iconItem, props.options.root as any); this.updateSize(props); this.element.updateData(this.dims); return this.element; }; updateSize = (props: Props) => { const { width, height } = props; this.element.anchor = { top: true, left: true, }; this.element.placement = { left: 0, top: 0, width, height, }; this.element.updateSize(width, height); }; dims: DimensionContext = { getColor: (color: ColorDimensionConfig) => getColorDimensionFromData(this.props.data, color), getScale: (scale: ScaleDimensionConfig) => getScaleDimensionFromData(this.props.data, scale), getScalar: (scalar: ScalarDimensionConfig) => getScalarDimensionFromData(this.props.data, scalar), getText: (text: TextDimensionConfig) => getTextDimensionFromData(this.props.data, text), getResource: (res: ResourceDimensionConfig) => getResourceDimensionFromData(this.props.data, res), }; shouldComponentUpdate(nextProps: Props) { const { width, height, data } = this.props; let changed = false; if (width !== nextProps.width || height !== nextProps.height) { this.updateSize(nextProps); changed = true; } if (data !== nextProps.data) { this.element.updateData(this.dims); changed = true; } // Reload the element when options change if (this.props.options?.root !== nextProps.options?.root) { this.initElement(nextProps); changed = true; } return changed; } render() { const { width, height } = this.props; return <div style={{ width, height, overflow: 'hidden', position: 'relative' }}>{this.element.render()}</div>; } }
public/app/plugins/panel/icon/IconPanel.tsx
0
https://github.com/grafana/grafana/commit/a1b8b5d123bde86fcfd7195c01b43d83a687d0ad
[ 0.00017376700998283923, 0.0001702507579466328, 0.00016275332018267363, 0.0001702615845715627, 0.0000031876711545919534 ]
{ "id": 6, "code_window": [ "\t// force renewal of user stats\n", "\terr = updateUserRoleCountsIfNecessary(context.Background(), true)\n", "\trequire.NoError(t, err)\n", "}" ], "labels": [ "keep", "keep", "add", "keep" ], "after_edit": [ "\n", "\t// add 1st api key\n", "\taddAPIKeyCmd := &models.AddApiKeyCommand{OrgId: org.Id, Name: \"Test key 1\", Key: \"secret-key\", Role: models.ROLE_VIEWER}\n", "\terr = sqlStore.AddAPIKey(context.Background(), addAPIKeyCmd)\n", "\trequire.NoError(t, err)\n" ], "file_path": "pkg/services/sqlstore/stats_test.go", "type": "add", "edit_start_line_idx": 127 }
package models import ( "encoding/json" "fmt" "time" "github.com/grafana/grafana-plugin-sdk-go/backend" "github.com/grafana/grafana/pkg/expr" ) const defaultMaxDataPoints float64 = 43200 // 12 hours at 1sec interval const defaultIntervalMS float64 = 1000 // Duration is a type used for marshalling durations. type Duration time.Duration func (d Duration) String() string { return time.Duration(d).String() } func (d Duration) MarshalJSON() ([]byte, error) { return json.Marshal(time.Duration(d).Seconds()) } func (d *Duration) UnmarshalJSON(b []byte) error { var v interface{} if err := json.Unmarshal(b, &v); err != nil { return err } switch value := v.(type) { case float64: *d = Duration(time.Duration(value) * time.Second) return nil default: return fmt.Errorf("invalid duration %v", v) } } // RelativeTimeRange is the per query start and end time // for requests. type RelativeTimeRange struct { From Duration `json:"from"` To Duration `json:"to"` } // isValid checks that From duration is greater than To duration. func (rtr *RelativeTimeRange) isValid() bool { return rtr.From > rtr.To } func (rtr *RelativeTimeRange) ToTimeRange(now time.Time) backend.TimeRange { return backend.TimeRange{ From: now.Add(-time.Duration(rtr.From)), To: now.Add(-time.Duration(rtr.To)), } } // AlertQuery represents a single query associated with an alert definition. type AlertQuery struct { // RefID is the unique identifier of the query, set by the frontend call. RefID string `json:"refId"` // QueryType is an optional identifier for the type of query. // It can be used to distinguish different types of queries. QueryType string `json:"queryType"` // RelativeTimeRange is the relative Start and End of the query as sent by the frontend. RelativeTimeRange RelativeTimeRange `json:"relativeTimeRange"` // Grafana data source unique identifier; it should be '-100' for a Server Side Expression operation. DatasourceUID string `json:"datasourceUid"` // JSON is the raw JSON query and includes the above properties as well as custom properties. Model json.RawMessage `json:"model"` modelProps map[string]interface{} } func (aq *AlertQuery) setModelProps() error { aq.modelProps = make(map[string]interface{}) err := json.Unmarshal(aq.Model, &aq.modelProps) if err != nil { return fmt.Errorf("failed to unmarshal query model: %w", err) } return nil } // IsExpression returns true if the alert query is an expression. func (aq *AlertQuery) IsExpression() (bool, error) { return expr.IsDataSource(aq.DatasourceUID), nil } // setMaxDatapoints sets the model maxDataPoints if it's missing or invalid func (aq *AlertQuery) setMaxDatapoints() error { if aq.modelProps == nil { err := aq.setModelProps() if err != nil { return err } } i, ok := aq.modelProps["maxDataPoints"] // GEL requires maxDataPoints inside the query JSON if !ok { aq.modelProps["maxDataPoints"] = defaultMaxDataPoints } maxDataPoints, ok := i.(float64) if !ok || maxDataPoints == 0 { aq.modelProps["maxDataPoints"] = defaultMaxDataPoints } return nil } func (aq *AlertQuery) GetMaxDatapoints() (int64, error) { err := aq.setMaxDatapoints() if err != nil { return 0, err } maxDataPoints, ok := aq.modelProps["maxDataPoints"].(float64) if !ok { return 0, fmt.Errorf("failed to cast maxDataPoints to float64: %v", aq.modelProps["maxDataPoints"]) } return int64(maxDataPoints), nil } // setIntervalMS sets the model IntervalMs if it's missing or invalid func (aq *AlertQuery) setIntervalMS() error { if aq.modelProps == nil { err := aq.setModelProps() if err != nil { return err } } i, ok := aq.modelProps["intervalMs"] // GEL requires intervalMs inside the query JSON if !ok { aq.modelProps["intervalMs"] = defaultIntervalMS } intervalMs, ok := i.(float64) if !ok || intervalMs == 0 { aq.modelProps["intervalMs"] = defaultIntervalMS } return nil } func (aq *AlertQuery) getIntervalMS() (int64, error) { err := aq.setIntervalMS() if err != nil { return 0, err } intervalMs, ok := aq.modelProps["intervalMs"].(float64) if !ok { return 0, fmt.Errorf("failed to cast intervalMs to float64: %v", aq.modelProps["intervalMs"]) } return int64(intervalMs), nil } func (aq *AlertQuery) GetIntervalDuration() (time.Duration, error) { err := aq.setIntervalMS() if err != nil { return 0, err } intervalMs, ok := aq.modelProps["intervalMs"].(float64) if !ok { return 0, fmt.Errorf("failed to cast intervalMs to float64: %v", aq.modelProps["intervalMs"]) } return time.Duration(intervalMs) * time.Millisecond, nil } // GetDatasource returns the query datasource identifier. func (aq *AlertQuery) GetDatasource() (string, error) { return aq.DatasourceUID, nil } func (aq *AlertQuery) GetModel() ([]byte, error) { err := aq.setMaxDatapoints() if err != nil { return nil, err } err = aq.setIntervalMS() if err != nil { return nil, err } model, err := json.Marshal(aq.modelProps) if err != nil { return nil, fmt.Errorf("unable to marshal query model: %w", err) } return model, nil } func (aq *AlertQuery) setQueryType() error { if aq.modelProps == nil { err := aq.setModelProps() if err != nil { return err } } i, ok := aq.modelProps["queryType"] if !ok { return nil } queryType, ok := i.(string) if !ok { return fmt.Errorf("failed to get queryType from query model: %v", i) } aq.QueryType = queryType return nil } // PreSave sets query's properties. // It should be called before being saved. func (aq *AlertQuery) PreSave() error { if err := aq.setQueryType(); err != nil { return fmt.Errorf("failed to set query type to query model: %w", err) } // override model model, err := aq.GetModel() if err != nil { return err } aq.Model = model isExpression, err := aq.IsExpression() if err != nil { return err } if ok := isExpression || aq.RelativeTimeRange.isValid(); !ok { return fmt.Errorf("invalid relative time range: %+v", aq.RelativeTimeRange) } return nil }
pkg/services/ngalert/models/alert_query.go
0
https://github.com/grafana/grafana/commit/a1b8b5d123bde86fcfd7195c01b43d83a687d0ad
[ 0.0051238699816167355, 0.00048045816947706044, 0.00016299699200317264, 0.0001703675661701709, 0.0010141964303329587 ]
{ "id": 0, "code_window": [ "\t\tmimetype?: string;\n", "\t\tpygments_lexer?: string;\n", "\t\t[propName: string]: unknown;\n", "\t};\n", "\torig_nbformat: number;\n", "\t[propName: string]: unknown;\n", "};\n", "\n", "export function activate(context: vscode.ExtensionContext) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\torig_nbformat?: number;\n" ], "file_path": "extensions/ipynb/src/ipynbMain.ts", "type": "replace", "edit_start_line_idx": 26 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import type * as nbformat from '@jupyterlab/nbformat'; import * as detectIndent from 'detect-indent'; import * as vscode from 'vscode'; import { defaultNotebookFormat } from './constants'; import { getPreferredLanguage, jupyterNotebookModelToNotebookData } from './deserializers'; import { createJupyterCellFromNotebookCell, pruneCell, sortObjectPropertiesRecursively } from './serializers'; import * as fnv from '@enonic/fnv-plus'; export class NotebookSerializer implements vscode.NotebookSerializer { constructor(readonly context: vscode.ExtensionContext) { } public async deserializeNotebook(content: Uint8Array, _token: vscode.CancellationToken): Promise<vscode.NotebookData> { let contents = ''; try { contents = new TextDecoder().decode(content); } catch { } let json = contents && /\S/.test(contents) ? (JSON.parse(contents) as Partial<nbformat.INotebookContent>) : {}; if (json.__webview_backup) { const backupId = json.__webview_backup; const uri = this.context.globalStorageUri; const folder = uri.with({ path: this.context.globalStorageUri.path.replace('vscode.ipynb', 'ms-toolsai.jupyter') }); const fileHash = fnv.fast1a32hex(backupId) as string; const fileName = `${fileHash}.ipynb`; const file = vscode.Uri.joinPath(folder, fileName); const data = await vscode.workspace.fs.readFile(file); json = data ? JSON.parse(data.toString()) : {}; if (json.contents && typeof json.contents === 'string') { contents = json.contents; json = JSON.parse(contents) as Partial<nbformat.INotebookContent>; } } if (json.nbformat && json.nbformat < 4) { throw new Error('Only Jupyter notebooks version 4+ are supported'); } // Then compute indent from the contents (only use first 1K characters as a perf optimization) const indentAmount = contents ? detectIndent(contents.substring(0, 1_000)).indent : ' '; const preferredCellLanguage = getPreferredLanguage(json.metadata); // Ensure we always have a blank cell. if ((json.cells || []).length === 0) { json.cells = [ { cell_type: 'code', execution_count: null, metadata: {}, outputs: [], source: '' } ]; } // For notebooks without metadata default the language in metadata to the preferred language. if (!json.metadata || (!json.metadata.kernelspec && !json.metadata.language_info)) { json.metadata = json.metadata || { orig_nbformat: defaultNotebookFormat.major }; json.metadata.language_info = json.metadata.language_info || { name: preferredCellLanguage }; } const data = jupyterNotebookModelToNotebookData( json, preferredCellLanguage ); data.metadata = data.metadata || {}; data.metadata.indentAmount = indentAmount; return data; } public serializeNotebook(data: vscode.NotebookData, _token: vscode.CancellationToken): Uint8Array { return new TextEncoder().encode(this.serializeNotebookToString(data)); } public serializeNotebookToString(data: vscode.NotebookData): string { const notebookContent = getNotebookMetadata(data); // use the preferred language from document metadata or the first cell language as the notebook preferred cell language const preferredCellLanguage = notebookContent.metadata?.language_info?.name ?? data.cells.find(cell => cell.kind === vscode.NotebookCellKind.Code)?.languageId; notebookContent.cells = data.cells .map(cell => createJupyterCellFromNotebookCell(cell, preferredCellLanguage)) .map(pruneCell); const indentAmount = data.metadata && 'indentAmount' in data.metadata && typeof data.metadata.indentAmount === 'string' ? data.metadata.indentAmount : ' '; // ipynb always ends with a trailing new line (we add this so that SCMs do not show unnecessary changes, resulting from a missing trailing new line). return JSON.stringify(sortObjectPropertiesRecursively(notebookContent), undefined, indentAmount) + '\n'; } } export function getNotebookMetadata(document: vscode.NotebookDocument | vscode.NotebookData) { const notebookContent: Partial<nbformat.INotebookContent> = document.metadata?.custom || {}; notebookContent.cells = notebookContent.cells || []; notebookContent.nbformat = notebookContent.nbformat || 4; notebookContent.nbformat_minor = notebookContent.nbformat_minor ?? 2; notebookContent.metadata = notebookContent.metadata || { orig_nbformat: 4 }; return notebookContent; }
extensions/ipynb/src/notebookSerializer.ts
1
https://github.com/microsoft/vscode/commit/9c17df54bd27cf9976e30a09749519bfc4e3a815
[ 0.0020847010891884565, 0.0003446605696808547, 0.00016358461289200932, 0.0001693167578196153, 0.0005502674030140042 ]
{ "id": 0, "code_window": [ "\t\tmimetype?: string;\n", "\t\tpygments_lexer?: string;\n", "\t\t[propName: string]: unknown;\n", "\t};\n", "\torig_nbformat: number;\n", "\t[propName: string]: unknown;\n", "};\n", "\n", "export function activate(context: vscode.ExtensionContext) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\torig_nbformat?: number;\n" ], "file_path": "extensions/ipynb/src/ipynbMain.ts", "type": "replace", "edit_start_line_idx": 26 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { CancellationTokenSource } from 'vs/base/common/cancellation'; import { dispose, IDisposable } from 'vs/base/common/lifecycle'; import { URI, UriComponents } from 'vs/base/common/uri'; import { ExtHostContext, ExtHostQuickDiffShape, IDocumentFilterDto, MainContext, MainThreadQuickDiffShape } from 'vs/workbench/api/common/extHost.protocol'; import { IQuickDiffService, QuickDiffProvider } from 'vs/workbench/contrib/scm/common/quickDiff'; import { extHostNamedCustomer, IExtHostContext } from 'vs/workbench/services/extensions/common/extHostCustomers'; @extHostNamedCustomer(MainContext.MainThreadQuickDiff) export class MainThreadQuickDiff implements MainThreadQuickDiffShape { private readonly proxy: ExtHostQuickDiffShape; private providers = new Map<number, QuickDiffProvider>(); private providerDisposables = new Map<number, IDisposable>(); constructor( extHostContext: IExtHostContext, @IQuickDiffService private readonly quickDiffService: IQuickDiffService ) { this.proxy = extHostContext.getProxy(ExtHostContext.ExtHostQuickDiff); } async $registerQuickDiffProvider(handle: number, selector: IDocumentFilterDto[], label: string, rootUri: UriComponents | undefined): Promise<void> { const provider: QuickDiffProvider = { label, rootUri: URI.revive(rootUri), selector, isSCM: false, getOriginalResource: async (uri: URI) => { return URI.revive(await this.proxy.$provideOriginalResource(handle, uri, new CancellationTokenSource().token)); } }; this.providers.set(handle, provider); const disposable = this.quickDiffService.addQuickDiffProvider(provider); this.providerDisposables.set(handle, disposable); } async $unregisterQuickDiffProvider(handle: number): Promise<void> { if (this.providers.has(handle)) { this.providers.delete(handle); } if (this.providerDisposables.has(handle)) { this.providerDisposables.delete(handle); } } dispose(): void { this.providers.clear(); dispose(this.providerDisposables.values()); this.providerDisposables.clear(); } }
src/vs/workbench/api/browser/mainThreadQuickDiff.ts
0
https://github.com/microsoft/vscode/commit/9c17df54bd27cf9976e30a09749519bfc4e3a815
[ 0.00017799530178308487, 0.00017169688362628222, 0.0001640535338083282, 0.00017279686289839447, 0.000005551213689614087 ]
{ "id": 0, "code_window": [ "\t\tmimetype?: string;\n", "\t\tpygments_lexer?: string;\n", "\t\t[propName: string]: unknown;\n", "\t};\n", "\torig_nbformat: number;\n", "\t[propName: string]: unknown;\n", "};\n", "\n", "export function activate(context: vscode.ExtensionContext) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\torig_nbformat?: number;\n" ], "file_path": "extensions/ipynb/src/ipynbMain.ts", "type": "replace", "edit_start_line_idx": 26 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import 'mocha'; import * as vscode from 'vscode'; import { onChangedDocument, retryUntilDocumentChanges, wait } from './testUtils'; export async function acceptFirstSuggestion(uri: vscode.Uri, _disposables: vscode.Disposable[]) { return retryUntilDocumentChanges(uri, { retries: 10, timeout: 0 }, _disposables, async () => { await vscode.commands.executeCommand('editor.action.triggerSuggest'); await wait(1000); await vscode.commands.executeCommand('acceptSelectedSuggestion'); }); } export async function typeCommitCharacter(uri: vscode.Uri, character: string, _disposables: vscode.Disposable[]) { const didChangeDocument = onChangedDocument(uri, _disposables); await vscode.commands.executeCommand('editor.action.triggerSuggest'); await wait(3000); // Give time for suggestions to show await vscode.commands.executeCommand('type', { text: character }); return await didChangeDocument; }
extensions/typescript-language-features/src/test/suggestTestHelpers.ts
0
https://github.com/microsoft/vscode/commit/9c17df54bd27cf9976e30a09749519bfc4e3a815
[ 0.00017241433670278639, 0.0001690356875769794, 0.0001670838100835681, 0.00016760893049649894, 0.0000023986615360627184 ]
{ "id": 0, "code_window": [ "\t\tmimetype?: string;\n", "\t\tpygments_lexer?: string;\n", "\t\t[propName: string]: unknown;\n", "\t};\n", "\torig_nbformat: number;\n", "\t[propName: string]: unknown;\n", "};\n", "\n", "export function activate(context: vscode.ExtensionContext) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\torig_nbformat?: number;\n" ], "file_path": "extensions/ipynb/src/ipynbMain.ts", "type": "replace", "edit_start_line_idx": 26 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ export const enum Constants { /** * MAX SMI (SMall Integer) as defined in v8. * one bit is lost for boxing/unboxing flag. * one bit is lost for sign flag. * See https://thibaultlaurens.github.io/javascript/2013/04/29/how-the-v8-engine-works/#tagged-values */ MAX_SAFE_SMALL_INTEGER = 1 << 30, /** * MIN SMI (SMall Integer) as defined in v8. * one bit is lost for boxing/unboxing flag. * one bit is lost for sign flag. * See https://thibaultlaurens.github.io/javascript/2013/04/29/how-the-v8-engine-works/#tagged-values */ MIN_SAFE_SMALL_INTEGER = -(1 << 30), /** * Max unsigned integer that fits on 8 bits. */ MAX_UINT_8 = 255, // 2^8 - 1 /** * Max unsigned integer that fits on 16 bits. */ MAX_UINT_16 = 65535, // 2^16 - 1 /** * Max unsigned integer that fits on 32 bits. */ MAX_UINT_32 = 4294967295, // 2^32 - 1 UNICODE_SUPPLEMENTARY_PLANE_BEGIN = 0x010000 } export function toUint8(v: number): number { if (v < 0) { return 0; } if (v > Constants.MAX_UINT_8) { return Constants.MAX_UINT_8; } return v | 0; } export function toUint32(v: number): number { if (v < 0) { return 0; } if (v > Constants.MAX_UINT_32) { return Constants.MAX_UINT_32; } return v | 0; }
src/vs/base/common/uint.ts
0
https://github.com/microsoft/vscode/commit/9c17df54bd27cf9976e30a09749519bfc4e3a815
[ 0.00034086109371855855, 0.0002285502851009369, 0.0001683282171143219, 0.00022137226187624037, 0.00005806159970234148 ]
{ "id": 1, "code_window": [ "\t\tdata.metadata = {\n", "\t\t\tcustom: {\n", "\t\t\t\tcells: [],\n", "\t\t\t\tmetadata: {\n", "\t\t\t\t\torig_nbformat: 4\n", "\t\t\t\t},\n", "\t\t\t\tnbformat: 4,\n", "\t\t\t\tnbformat_minor: 2\n", "\t\t\t}\n", "\t\t};\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tmetadata: {},\n" ], "file_path": "extensions/ipynb/src/ipynbMain.ts", "type": "replace", "edit_start_line_idx": 78 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import type * as nbformat from '@jupyterlab/nbformat'; import * as detectIndent from 'detect-indent'; import * as vscode from 'vscode'; import { defaultNotebookFormat } from './constants'; import { getPreferredLanguage, jupyterNotebookModelToNotebookData } from './deserializers'; import { createJupyterCellFromNotebookCell, pruneCell, sortObjectPropertiesRecursively } from './serializers'; import * as fnv from '@enonic/fnv-plus'; export class NotebookSerializer implements vscode.NotebookSerializer { constructor(readonly context: vscode.ExtensionContext) { } public async deserializeNotebook(content: Uint8Array, _token: vscode.CancellationToken): Promise<vscode.NotebookData> { let contents = ''; try { contents = new TextDecoder().decode(content); } catch { } let json = contents && /\S/.test(contents) ? (JSON.parse(contents) as Partial<nbformat.INotebookContent>) : {}; if (json.__webview_backup) { const backupId = json.__webview_backup; const uri = this.context.globalStorageUri; const folder = uri.with({ path: this.context.globalStorageUri.path.replace('vscode.ipynb', 'ms-toolsai.jupyter') }); const fileHash = fnv.fast1a32hex(backupId) as string; const fileName = `${fileHash}.ipynb`; const file = vscode.Uri.joinPath(folder, fileName); const data = await vscode.workspace.fs.readFile(file); json = data ? JSON.parse(data.toString()) : {}; if (json.contents && typeof json.contents === 'string') { contents = json.contents; json = JSON.parse(contents) as Partial<nbformat.INotebookContent>; } } if (json.nbformat && json.nbformat < 4) { throw new Error('Only Jupyter notebooks version 4+ are supported'); } // Then compute indent from the contents (only use first 1K characters as a perf optimization) const indentAmount = contents ? detectIndent(contents.substring(0, 1_000)).indent : ' '; const preferredCellLanguage = getPreferredLanguage(json.metadata); // Ensure we always have a blank cell. if ((json.cells || []).length === 0) { json.cells = [ { cell_type: 'code', execution_count: null, metadata: {}, outputs: [], source: '' } ]; } // For notebooks without metadata default the language in metadata to the preferred language. if (!json.metadata || (!json.metadata.kernelspec && !json.metadata.language_info)) { json.metadata = json.metadata || { orig_nbformat: defaultNotebookFormat.major }; json.metadata.language_info = json.metadata.language_info || { name: preferredCellLanguage }; } const data = jupyterNotebookModelToNotebookData( json, preferredCellLanguage ); data.metadata = data.metadata || {}; data.metadata.indentAmount = indentAmount; return data; } public serializeNotebook(data: vscode.NotebookData, _token: vscode.CancellationToken): Uint8Array { return new TextEncoder().encode(this.serializeNotebookToString(data)); } public serializeNotebookToString(data: vscode.NotebookData): string { const notebookContent = getNotebookMetadata(data); // use the preferred language from document metadata or the first cell language as the notebook preferred cell language const preferredCellLanguage = notebookContent.metadata?.language_info?.name ?? data.cells.find(cell => cell.kind === vscode.NotebookCellKind.Code)?.languageId; notebookContent.cells = data.cells .map(cell => createJupyterCellFromNotebookCell(cell, preferredCellLanguage)) .map(pruneCell); const indentAmount = data.metadata && 'indentAmount' in data.metadata && typeof data.metadata.indentAmount === 'string' ? data.metadata.indentAmount : ' '; // ipynb always ends with a trailing new line (we add this so that SCMs do not show unnecessary changes, resulting from a missing trailing new line). return JSON.stringify(sortObjectPropertiesRecursively(notebookContent), undefined, indentAmount) + '\n'; } } export function getNotebookMetadata(document: vscode.NotebookDocument | vscode.NotebookData) { const notebookContent: Partial<nbformat.INotebookContent> = document.metadata?.custom || {}; notebookContent.cells = notebookContent.cells || []; notebookContent.nbformat = notebookContent.nbformat || 4; notebookContent.nbformat_minor = notebookContent.nbformat_minor ?? 2; notebookContent.metadata = notebookContent.metadata || { orig_nbformat: 4 }; return notebookContent; }
extensions/ipynb/src/notebookSerializer.ts
1
https://github.com/microsoft/vscode/commit/9c17df54bd27cf9976e30a09749519bfc4e3a815
[ 0.0049203247763216496, 0.0012398179387673736, 0.00016646839503664523, 0.000744494260288775, 0.001348316203802824 ]
{ "id": 1, "code_window": [ "\t\tdata.metadata = {\n", "\t\t\tcustom: {\n", "\t\t\t\tcells: [],\n", "\t\t\t\tmetadata: {\n", "\t\t\t\t\torig_nbformat: 4\n", "\t\t\t\t},\n", "\t\t\t\tnbformat: 4,\n", "\t\t\t\tnbformat_minor: 2\n", "\t\t\t}\n", "\t\t};\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tmetadata: {},\n" ], "file_path": "extensions/ipynb/src/ipynbMain.ts", "type": "replace", "edit_start_line_idx": 78 }
{ "information_for_contributors": [ "This file has been converted from https://github.com/microsoft/vscode-mssql/blob/master/syntaxes/SQL.plist", "If you want to provide a fix or improvement, please create a pull request against the original repository.", "Once accepted there, we are happy to receive an update request." ], "version": "https://github.com/microsoft/vscode-mssql/commit/9cb3529a978ddf599bf5bdd228f21bbcfe2914f5", "name": "SQL", "scopeName": "source.sql", "patterns": [ { "match": "((?<!@)@)\\b(\\w+)\\b", "name": "text.variable" }, { "match": "(\\[)[^\\]]*(\\])", "name": "text.bracketed" }, { "include": "#comments" }, { "captures": { "1": { "name": "keyword.other.create.sql" }, "2": { "name": "keyword.other.sql" }, "5": { "name": "entity.name.function.sql" } }, "match": "(?i:^\\s*(create(?:\\s+or\\s+replace)?)\\s+(aggregate|conversion|database|domain|function|group|(unique\\s+)?index|language|operator class|operator|rule|schema|sequence|table|tablespace|trigger|type|user|view)\\s+)(['\"`]?)(\\w+)\\4", "name": "meta.create.sql" }, { "captures": { "1": { "name": "keyword.other.create.sql" }, "2": { "name": "keyword.other.sql" } }, "match": "(?i:^\\s*(drop)\\s+(aggregate|conversion|database|domain|function|group|index|language|operator class|operator|rule|schema|sequence|table|tablespace|trigger|type|user|view))", "name": "meta.drop.sql" }, { "captures": { "1": { "name": "keyword.other.create.sql" }, "2": { "name": "keyword.other.table.sql" }, "3": { "name": "entity.name.function.sql" }, "4": { "name": "keyword.other.cascade.sql" } }, "match": "(?i:\\s*(drop)\\s+(table)\\s+(\\w+)(\\s+cascade)?\\b)", "name": "meta.drop.sql" }, { "captures": { "1": { "name": "keyword.other.create.sql" }, "2": { "name": "keyword.other.table.sql" } }, "match": "(?i:^\\s*(alter)\\s+(aggregate|conversion|database|domain|function|group|index|language|operator class|operator|proc(edure)?|rule|schema|sequence|table|tablespace|trigger|type|user|view)\\s+)", "name": "meta.alter.sql" }, { "captures": { "1": { "name": "storage.type.sql" }, "2": { "name": "storage.type.sql" }, "3": { "name": "constant.numeric.sql" }, "4": { "name": "storage.type.sql" }, "5": { "name": "constant.numeric.sql" }, "6": { "name": "storage.type.sql" }, "7": { "name": "constant.numeric.sql" }, "8": { "name": "constant.numeric.sql" }, "9": { "name": "storage.type.sql" }, "10": { "name": "constant.numeric.sql" }, "11": { "name": "storage.type.sql" }, "12": { "name": "storage.type.sql" }, "13": { "name": "storage.type.sql" }, "14": { "name": "constant.numeric.sql" }, "15": { "name": "storage.type.sql" } }, "match": "(?xi)\n\n\t\t\t\t# normal stuff, capture 1\n\t\t\t\t \\b(bigint|bigserial|bit|boolean|box|bytea|cidr|circle|date|double\\sprecision|inet|int|integer|line|lseg|macaddr|money|oid|path|point|polygon|real|serial|smallint|sysdate|text)\\b\n\n\t\t\t\t# numeric suffix, capture 2 + 3i\n\t\t\t\t|\\b(bit\\svarying|character\\s(?:varying)?|tinyint|var\\schar|float|interval)\\((\\d+)\\)\n\n\t\t\t\t# optional numeric suffix, capture 4 + 5i\n\t\t\t\t|\\b(char|number|varchar\\d?)\\b(?:\\((\\d+)\\))?\n\n\t\t\t\t# special case, capture 6 + 7i + 8i\n\t\t\t\t|\\b(numeric|decimal)\\b(?:\\((\\d+),(\\d+)\\))?\n\n\t\t\t\t# special case, captures 9, 10i, 11\n\t\t\t\t|\\b(times?)\\b(?:\\((\\d+)\\))?(\\swith(?:out)?\\stime\\szone\\b)?\n\n\t\t\t\t# special case, captures 12, 13, 14i, 15\n\t\t\t\t|\\b(timestamp)(?:(s|tz))?\\b(?:\\((\\d+)\\))?(\\s(with|without)\\stime\\szone\\b)?\n\n\t\t\t" }, { "match": "(?i:\\b((?:primary|foreign)\\s+key|references|on\\sdelete(\\s+cascade)?|nocheck|check|constraint|collate|default)\\b)", "name": "storage.modifier.sql" }, { "match": "\\b\\d+\\b", "name": "constant.numeric.sql" }, { "match": "(?i:\\b(select(\\s+(all|distinct))?|insert\\s+(ignore\\s+)?into|update|delete|from|set|where|group\\s+by|or|like|and|union(\\s+all)?|having|order\\s+by|limit|cross\\s+join|join|straight_join|(inner|(left|right|full)(\\s+outer)?)\\s+join|natural(\\s+(inner|(left|right|full)(\\s+outer)?))?\\s+join)\\b)", "name": "keyword.other.DML.sql" }, { "match": "(?i:\\b(on|off|((is\\s+)?not\\s+)?null)\\b)", "name": "keyword.other.DDL.create.II.sql" }, { "match": "(?i:\\bvalues\\b)", "name": "keyword.other.DML.II.sql" }, { "match": "(?i:\\b(begin(\\s+work)?|start\\s+transaction|commit(\\s+work)?|rollback(\\s+work)?)\\b)", "name": "keyword.other.LUW.sql" }, { "match": "(?i:\\b(grant(\\swith\\sgrant\\soption)?|revoke)\\b)", "name": "keyword.other.authorization.sql" }, { "match": "(?i:\\bin\\b)", "name": "keyword.other.data-integrity.sql" }, { "match": "(?i:^\\s*(comment\\s+on\\s+(table|column|aggregate|constraint|database|domain|function|index|operator|rule|schema|sequence|trigger|type|view))\\s+.*?\\s+(is)\\s+)", "name": "keyword.other.object-comments.sql" }, { "match": "(?i)\\bAS\\b", "name": "keyword.other.alias.sql" }, { "match": "(?i)\\b(DESC|ASC)\\b", "name": "keyword.other.order.sql" }, { "match": "\\*", "name": "keyword.operator.star.sql" }, { "match": "[!<>]?=|<>|<|>", "name": "keyword.operator.comparison.sql" }, { "match": "-|\\+|/", "name": "keyword.operator.math.sql" }, { "match": "\\|\\|", "name": "keyword.operator.concatenator.sql" }, { "match": "(?i)\\b(approx_count_distinct|approx_percentile_cont|approx_percentile_disc|avg|checksum_agg|count|count_big|group|grouping|grouping_id|max|min|sum|stdev|stdevp|var|varp)\\b\\s*\\(", "captures": { "1": { "name": "support.function.aggregate.sql" } } }, { "match": "(?i)\\b(cume_dist|first_value|lag|last_value|lead|percent_rank|percentile_cont|percentile_disc)\\b\\s*\\(", "captures": { "1": { "name": "support.function.analytic.sql" } } }, { "match": "(?i)\\b(bit_count|get_bit|left_shift|right_shift|set_bit)\\b\\s*\\(", "captures": { "1": { "name": "support.function.bitmanipulation.sql" } } }, { "match": "(?i)\\b(cast|convert|parse|try_cast|try_convert|try_parse)\\b\\s*\\(", "captures": { "1": { "name": "support.function.conversion.sql" } } }, { "match": "(?i)\\b(collationproperty|tertiary_weights)\\b\\s*\\(", "captures": { "1": { "name": "support.function.collation.sql" } } }, { "match": "(?i)\\b(asymkey_id|asymkeyproperty|certproperty|cert_id|crypt_gen_random|decryptbyasymkey|decryptbycert|decryptbykey|decryptbykeyautoasymkey|decryptbykeyautocert|decryptbypassphrase|encryptbyasymkey|encryptbycert|encryptbykey|encryptbypassphrase|hashbytes|is_objectsigned|key_guid|key_id|key_name|signbyasymkey|signbycert|symkeyproperty|verifysignedbycert|verifysignedbyasymkey)\\b\\s*\\(", "captures": { "1": { "name": "support.function.cryptographic.sql" } } }, { "match": "(?i)\\b(cursor_status)\\b\\s*\\(", "captures": { "1": { "name": "support.function.cursor.sql" } } }, { "match": "(?i)\\b(sysdatetime|sysdatetimeoffset|sysutcdatetime|current_time(stamp)?|getdate|getutcdate|datename|datepart|day|month|year|datefromparts|datetime2fromparts|datetimefromparts|datetimeoffsetfromparts|smalldatetimefromparts|timefromparts|datediff|dateadd|datetrunc|eomonth|switchoffset|todatetimeoffset|isdate|date_bucket)\\b\\s*\\(", "captures": { "1": { "name": "support.function.datetime.sql" } } }, { "match": "(?i)\\b(datalength|ident_current|ident_incr|ident_seed|identity|sql_variant_property)\\b\\s*\\(", "captures": { "1": { "name": "support.function.datatype.sql" } } }, { "match": "(?i)\\b(coalesce|nullif)\\b\\s*\\(", "captures": { "1": { "name": "support.function.expression.sql" } } }, { "match": "(?<!@)@@(?i)\\b(cursor_rows|connections|cpu_busy|datefirst|dbts|error|fetch_status|identity|idle|io_busy|langid|language|lock_timeout|max_connections|max_precision|nestlevel|options|packet_errors|pack_received|pack_sent|procid|remserver|rowcount|servername|servicename|spid|textsize|timeticks|total_errors|total_read|total_write|trancount|version)\\b\\s*\\(", "captures": { "1": { "name": "support.function.globalvar.sql" } } }, { "match": "(?i)\\b(json|isjson|json_object|json_array|json_value|json_query|json_modify|json_path_exists)\\b\\s*\\(", "captures": { "1": { "name": "support.function.json.sql" } } }, { "match": "(?i)\\b(choose|iif|greatest|least)\\b\\s*\\(", "captures": { "1": { "name": "support.function.logical.sql" } } }, { "match": "(?i)\\b(abs|acos|asin|atan|atn2|ceiling|cos|cot|degrees|exp|floor|log|log10|pi|power|radians|rand|round|sign|sin|sqrt|square|tan)\\b\\s*\\(", "captures": { "1": { "name": "support.function.mathematical.sql" } } }, { "match": "(?i)\\b(app_name|applock_mode|applock_test|assemblyproperty|col_length|col_name|columnproperty|database_principal_id|databasepropertyex|db_id|db_name|file_id|file_idex|file_name|filegroup_id|filegroup_name|filegroupproperty|fileproperty|fulltextcatalogproperty|fulltextserviceproperty|index_col|indexkey_property|indexproperty|object_definition|object_id|object_name|object_schema_name|objectproperty|objectpropertyex|original_db_name|parsename|schema_id|schema_name|scope_identity|serverproperty|stats_date|type_id|type_name|typeproperty)\\b\\s*\\(", "captures": { "1": { "name": "support.function.metadata.sql" } } }, { "match": "(?i)\\b(rank|dense_rank|ntile|row_number)\\b\\s*\\(", "captures": { "1": { "name": "support.function.ranking.sql" } } }, { "match": "(?i)\\b(generate_series|opendatasource|openjson|openrowset|openquery|openxml|predict|string_split)\\b\\s*\\(", "captures": { "1": { "name": "support.function.rowset.sql" } } }, { "match": "(?i)\\b(certencoded|certprivatekey|current_user|database_principal_id|has_perms_by_name|is_member|is_rolemember|is_srvrolemember|original_login|permissions|pwdcompare|pwdencrypt|schema_id|schema_name|session_user|suser_id|suser_sid|suser_sname|system_user|suser_name|user_id|user_name)\\b\\s*\\(", "captures": { "1": { "name": "support.function.security.sql" } } }, { "match": "(?i)\\b(ascii|char|charindex|concat|difference|format|left|len|lower|ltrim|nchar|nodes|patindex|quotename|replace|replicate|reverse|right|rtrim|soundex|space|str|string_agg|string_escape|string_split|stuff|substring|translate|trim|unicode|upper)\\b\\s*\\(", "captures": { "1": { "name": "support.function.string.sql" } } }, { "match": "(?i)\\b(binary_checksum|checksum|compress|connectionproperty|context_info|current_request_id|current_transaction_id|decompress|error_line|error_message|error_number|error_procedure|error_severity|error_state|formatmessage|get_filestream_transaction_context|getansinull|host_id|host_name|isnull|isnumeric|min_active_rowversion|newid|newsequentialid|rowcount_big|session_context|session_id|xact_state)\\b\\s*\\(", "captures": { "1": { "name": "support.function.system.sql" } } }, { "match": "(?i)\\b(patindex|textptr|textvalid)\\b\\s*\\(", "captures": { "1": { "name": "support.function.textimage.sql" } } }, { "captures": { "1": { "name": "constant.other.database-name.sql" }, "2": { "name": "constant.other.table-name.sql" } }, "match": "(\\w+?)\\.(\\w+)" }, { "include": "#strings" }, { "include": "#regexps" }, { "match": "\\b(?i)(abort|abort_after_wait|absent|absolute|accent_sensitivity|acceptable_cursopt|acp|action|activation|add|address|admin|aes_128|aes_192|aes_256|affinity|after|aggregate|algorithm|all_constraints|all_errormsgs|all_indexes|all_levels|all_results|allow_connections|allow_dup_row|allow_encrypted_value_modifications|allow_page_locks|allow_row_locks|allow_snapshot_isolation|alter|altercolumn|always|anonymous|ansi_defaults|ansi_null_default|ansi_null_dflt_off|ansi_null_dflt_on|ansi_nulls|ansi_padding|ansi_warnings|appdomain|append|application|apply|arithabort|arithignore|array|assembly|asymmetric|asynchronous_commit|at|atan2|atomic|attach|attach_force_rebuild_log|attach_rebuild_log|audit|auth_realm|authentication|auto|auto_cleanup|auto_close|auto_create_statistics|auto_drop|auto_shrink|auto_update_statistics|auto_update_statistics_async|automated_backup_preference|automatic|autopilot|availability|availability_mode|backup|backup_priority|base64|basic|batches|batchsize|before|between|bigint|binary|binding|bit|block|blockers|blocksize|bmk|both|break|broker|broker_instance|bucket_count|buffer|buffercount|bulk_logged|by|call|caller|card|case|catalog|catch|cert|certificate|change_retention|change_tracking|change_tracking_context|changes|char|character|character_set|check_expiration|check_policy|checkconstraints|checkindex|checkpoint|checksum|cleanup_policy|clear|clear_port|close|clustered|codepage|collection|column_encryption_key|column_master_key|columnstore|columnstore_archive|colv_80_to_100|colv_100_to_80|commit_differential_base|committed|compatibility_level|compress_all_row_groups|compression|compression_delay|concat_null_yields_null|concatenate|configuration|connect|containment|continue|continue_after_error|contract|contract_name|control|conversation|conversation_group_id|conversation_handle|copy|copy_only|count_rows|counter|create(\\\\s+or\\\\s+alter)?|credential|cross|cryptographic|cryptographic_provider|cube|cursor|cursor_close_on_commit|cursor_default|data|data_compression|data_flush_interval_seconds|data_mirroring|data_purity|data_source|database|database_name|database_snapshot|datafiletype|date_correlation_optimization|date|datefirst|dateformat|date_format|datetime|datetime2|datetimeoffset|day(s)?|db_chaining|dbid|dbidexec|dbo_only|deadlock_priority|deallocate|dec|decimal|declare|decrypt|decrypt_a|decryption|default_database|default_fulltext_language|default_language|default_logon_domain|default_schema|definition|delay|delayed_durability|delimitedtext|density_vector|dependent|des|description|desired_state|desx|differential|digest|disable|disable_broker|disable_def_cnst_chk|disabled|disk|distinct|distributed|distribution|drop|drop_existing|dts_buffers|dump|durability|dynamic|edition|elements|else|emergency|empty|enable|enable_broker|enabled|encoding|encrypted|encrypted_value|encryption|encryption_type|end|endpoint|endpoint_url|enhancedintegrity|entry|error_broker_conversations|errorfile|estimateonly|event|except|exec|executable|execute|exists|expand|expiredate|expiry_date|explicit|external|external_access|failover|failover_mode|failure_condition_level|fast|fast_forward|fastfirstrow|federated_service_account|fetch|field_terminator|fieldterminator|file|filelistonly|filegroup|filegrowth|filename|filestream|filestream_log|filestream_on|filetable|file_format|filter|first_row|fips_flagger|fire_triggers|first|firstrow|float|flush_interval_seconds|fmtonly|following|for|force|force_failover_allow_data_loss|force_service_allow_data_loss|forced|forceplan|formatfile|format_options|format_type|formsof|forward_only|free_cursors|free_exec_context|fullscan|fulltext|fulltextall|fulltextkey|function|generated|get|geography|geometry|global|go|goto|governor|guid|hadoop|hardening|hash|hashed|header_limit|headeronly|health_check_timeout|hidden|hierarchyid|histogram|histogram_steps|hits_cursors|hits_exec_context|hour(s)?|http|identity|identity_value|if|ifnull|ignore|ignore_constraints|ignore_dup_key|ignore_dup_row|ignore_triggers|image|immediate|implicit_transactions|include|include_null_values|incremental|index|inflectional|init|initiator|insensitive|insert|instead|int|integer|integrated|intersect|intermediate|interval_length_minutes|into|inuse_cursors|inuse_exec_context|io|is|isabout|iso_week|isolation|job_tracker_location|json|keep|keep_nulls|keep_replication|keepdefaults|keepfixed|keepidentity|keepnulls|kerberos|key|key_path|key_source|key_store_provider_name|keyset|kill|kilobytes_per_batch|labelonly|langid|language|last|lastrow|leading|legacy_cardinality_estimation|length|level|lifetime|lineage_80_to_100|lineage_100_to_80|listener_ip|listener_port|load|loadhistory|lob_compaction|local|local_service_name|locate|location|lock_escalation|lock_timeout|lockres|log|login|login_type|loop|manual|mark_in_use_for_removal|masked|master|matched|max_queue_readers|max_duration|max_outstanding_io_per_volume|maxdop|maxerrors|maxlength|maxtransfersize|max_plans_per_query|max_storage_size_mb|mediadescription|medianame|mediapassword|memogroup|memory_optimized|merge|message|message_forward_size|message_forwarding|microsecond|millisecond|minute(s)?|mirror_address|misses_cursors|misses_exec_context|mixed|modify|money|month|move|multi_user|must_change|name|namespace|nanosecond|native|native_compilation|nchar|ncharacter|nested_triggers|never|new_account|new_broker|newname|next|no|no_browsetable|no_checksum|no_compression|no_infomsgs|no_triggers|no_truncate|nocount|noexec|noexpand|noformat|noinit|nolock|nonatomic|nonclustered|nondurable|none|norecompute|norecovery|noreset|norewind|noskip|not|notification|nounload|now|nowait|ntext|ntlm|nulls|numeric|numeric_roundabort|nvarchar|object|objid|oem|offline|old_account|online|operation_mode|open|openjson|optimistic|option|orc|out|outer|output|over|override|owner|ownership|pad_index|page|page_checksum|page_verify|pagecount|paglock|param|parameter_sniffing|parameter_type_expansion|parameterization|parquet|parseonly|partial|partition|partner|password|path|pause|percentage|permission_set|persisted|period|physical_only|plan_forcing_mode|policy|pool|population|ports|preceding|precision|predicate|presume_abort|primary|primary_role|print|prior|priority |priority_level|private|proc(edure)?|procedure_name|profile|provider|quarter|query_capture_mode|query_governor_cost_limit|query_optimizer_hotfixes|query_store|queue|quoted_identifier|raiserror|range|raw|rcfile|rc2|rc4|rc4_128|rdbms|read_committed_snapshot|read|read_only|read_write|readcommitted|readcommittedlock|readonly|readpast|readuncommitted|readwrite|real|rebuild|receive|recmodel_70backcomp|recompile|reconfigure|recovery|recursive|recursive_triggers|redo_queue|reject_sample_value|reject_type|reject_value|relative|remote|remote_data_archive|remote_proc_transactions|remote_service_name|remove|removed_cursors|removed_exec_context|reorganize|repeat|repeatable|repeatableread|replace|replica|replicated|replnick_100_to_80|replnickarray_80_to_100|replnickarray_100_to_80|required|required_cursopt|resample|reset|resource|resource_manager_location|respect|restart|restore|restricted_user|resume|retaindays|retention|return|revert|rewind|rewindonly|returns|robust|role|rollup|root|round_robin|route|row|rowdump|rowguidcol|rowlock|row_terminator|rows|rows_per_batch|rowsets_only|rowterminator|rowversion|rsa_1024|rsa_2048|rsa_3072|rsa_4096|rsa_512|safe|safety|sample|save|scalar|schema|schemabinding|scoped|scroll|scroll_locks|sddl|second|secexpr|seconds|secondary|secondary_only|secondary_role|secret|security|securityaudit|selective|self|send|sent|sequence|serde_method|serializable|server|service|service_broker|service_name|service_objective|session_timeout|session|sessions|seterror|setopts|sets|shard_map_manager|shard_map_name|sharded|shared_memory|show_statistics|showplan_all|showplan_text|showplan_xml|showplan_xml_with_recompile|shrinkdb|shutdown|sid|signature|simple|single_blob|single_clob|single_nclob|single_user|singleton|site|size|size_based_cleanup_mode|skip|smalldatetime|smallint|smallmoney|snapshot|snapshot_import|snapshotrestorephase|soap|softnuma|sort_in_tempdb|sorted_data|sorted_data_reorg|spatial|sql|sql_bigint|sql_binary|sql_bit|sql_char|sql_date|sql_decimal|sql_double|sql_float|sql_guid|sql_handle|sql_longvarbinary|sql_longvarchar|sql_numeric|sql_real|sql_smallint|sql_time|sql_timestamp|sql_tinyint|sql_tsi_day|sql_tsi_frac_second|sql_tsi_hour|sql_tsi_minute|sql_tsi_month|sql_tsi_quarter|sql_tsi_second|sql_tsi_week|sql_tsi_year|sql_type_date|sql_type_time|sql_type_timestamp|sql_varbinary|sql_varchar|sql_variant|sql_wchar|sql_wlongvarchar|ssl|ssl_port|standard|standby|start|start_date|started|stat_header|state|statement|static|statistics|statistics_incremental|statistics_norecompute|statistics_only|statman|stats|stats_stream|status|stop|stop_on_error|stopat|stopatmark|stopbeforemark|stoplist|stopped|string_delimiter|subject|supplemental_logging|supported|suspend|symmetric|synchronous_commit|synonym|sysname|system|system_time|system_versioning|table|tableresults|tablock|tablockx|take|tape|target|target_index|target_partition|target_recovery_time|tcp|temporal_history_retention|text|textimage_on|then|thesaurus|throw|time|timeout|timestamp|tinyint|to|top|torn_page_detection|track_columns_updated|trailing|tran|transaction|transfer|transform_noise_words|triple_des|triple_des_3key|truncate|trustworthy|try|tsql|two_digit_year_cutoff|type|type_desc|type_warning|tzoffset|uid|unbounded|uncommitted|unique|uniqueidentifier|unlimited|unload|unlock|unsafe|updlock|url|use|useplan|useroptions|use_type_default|using|utcdatetime|valid_xml|validation|value|values|varbinary|varchar|verbose|verifyonly|version|view_metadata|virtual_device|visiblity|wait_at_low_priority|waitfor|webmethod|week|weekday|weight|well_formed_xml|when|while|widechar|widechar_ansi|widenative|window|windows|with|within|within group|witness|without|without_array_wrapper|workload|wsdl|xact_abort|xlock|xml|xmlschema|xquery|xsinil|year|zone)\\b", "name": "keyword.other.sql" }, { "captures": { "1": { "name": "punctuation.section.scope.begin.sql" }, "2": { "name": "punctuation.section.scope.end.sql" } }, "comment": "Allow for special ↩ behavior", "match": "(\\()(\\))", "name": "meta.block.sql" } ], "repository": { "comments": { "patterns": [ { "begin": "(^[ \\t]+)?(?=--)", "beginCaptures": { "1": { "name": "punctuation.whitespace.comment.leading.sql" } }, "end": "(?!\\G)", "patterns": [ { "begin": "--", "beginCaptures": { "0": { "name": "punctuation.definition.comment.sql" } }, "end": "\\n", "name": "comment.line.double-dash.sql" } ] }, { "begin": "(^[ \\t]+)?(?=#)", "beginCaptures": { "1": { "name": "punctuation.whitespace.comment.leading.sql" } }, "end": "(?!\\G)", "patterns": [] }, { "include": "#comment-block" } ] }, "comment-block": { "begin": "/\\*", "captures": { "0": { "name": "punctuation.definition.comment.sql" } }, "end": "\\*/", "name": "comment.block", "patterns": [ { "include": "#comment-block" } ] }, "regexps": { "patterns": [ { "begin": "/(?=\\S.*/)", "beginCaptures": { "0": { "name": "punctuation.definition.string.begin.sql" } }, "end": "/", "endCaptures": { "0": { "name": "punctuation.definition.string.end.sql" } }, "name": "string.regexp.sql", "patterns": [ { "include": "#string_interpolation" }, { "match": "\\\\/", "name": "constant.character.escape.slash.sql" } ] }, { "begin": "%r\\{", "beginCaptures": { "0": { "name": "punctuation.definition.string.begin.sql" } }, "comment": "We should probably handle nested bracket pairs!?! -- Allan", "end": "\\}", "endCaptures": { "0": { "name": "punctuation.definition.string.end.sql" } }, "name": "string.regexp.modr.sql", "patterns": [ { "include": "#string_interpolation" } ] } ] }, "string_escape": { "match": "\\\\.", "name": "constant.character.escape.sql" }, "string_interpolation": { "captures": { "1": { "name": "punctuation.definition.string.begin.sql" }, "3": { "name": "punctuation.definition.string.end.sql" } }, "match": "(#\\{)([^\\}]*)(\\})", "name": "string.interpolated.sql" }, "strings": { "patterns": [ { "captures": { "2": { "name": "punctuation.definition.string.begin.sql" }, "3": { "name": "punctuation.definition.string.end.sql" } }, "comment": "this is faster than the next begin/end rule since sub-pattern will match till end-of-line and SQL files tend to have very long lines.", "match": "(N)?(')[^']*(')", "name": "string.quoted.single.sql" }, { "begin": "'", "beginCaptures": { "0": { "name": "punctuation.definition.string.begin.sql" } }, "end": "'", "endCaptures": { "0": { "name": "punctuation.definition.string.end.sql" } }, "name": "string.quoted.single.sql", "patterns": [ { "include": "#string_escape" } ] }, { "captures": { "1": { "name": "punctuation.definition.string.begin.sql" }, "2": { "name": "punctuation.definition.string.end.sql" } }, "comment": "this is faster than the next begin/end rule since sub-pattern will match till end-of-line and SQL files tend to have very long lines.", "match": "(`)[^`\\\\]*(`)", "name": "string.quoted.other.backtick.sql" }, { "begin": "`", "beginCaptures": { "0": { "name": "punctuation.definition.string.begin.sql" } }, "end": "`", "endCaptures": { "0": { "name": "punctuation.definition.string.end.sql" } }, "name": "string.quoted.other.backtick.sql", "patterns": [ { "include": "#string_escape" } ] }, { "captures": { "1": { "name": "punctuation.definition.string.begin.sql" }, "2": { "name": "punctuation.definition.string.end.sql" } }, "comment": "this is faster than the next begin/end rule since sub-pattern will match till end-of-line and SQL files tend to have very long lines.", "match": "(\")[^\"#]*(\")", "name": "string.quoted.double.sql" }, { "begin": "\"", "beginCaptures": { "0": { "name": "punctuation.definition.string.begin.sql" } }, "end": "\"", "endCaptures": { "0": { "name": "punctuation.definition.string.end.sql" } }, "name": "string.quoted.double.sql", "patterns": [ { "include": "#string_interpolation" } ] }, { "begin": "%\\{", "beginCaptures": { "0": { "name": "punctuation.definition.string.begin.sql" } }, "end": "\\}", "endCaptures": { "0": { "name": "punctuation.definition.string.end.sql" } }, "name": "string.other.quoted.brackets.sql", "patterns": [ { "include": "#string_interpolation" } ] } ] } } }
extensions/sql/syntaxes/sql.tmLanguage.json
0
https://github.com/microsoft/vscode/commit/9c17df54bd27cf9976e30a09749519bfc4e3a815
[ 0.0001782968029147014, 0.0001715903345029801, 0.00016723395674489439, 0.0001719100255286321, 0.0000019154801975673763 ]
{ "id": 1, "code_window": [ "\t\tdata.metadata = {\n", "\t\t\tcustom: {\n", "\t\t\t\tcells: [],\n", "\t\t\t\tmetadata: {\n", "\t\t\t\t\torig_nbformat: 4\n", "\t\t\t\t},\n", "\t\t\t\tnbformat: 4,\n", "\t\t\t\tnbformat_minor: 2\n", "\t\t\t}\n", "\t\t};\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tmetadata: {},\n" ], "file_path": "extensions/ipynb/src/ipynbMain.ts", "type": "replace", "edit_start_line_idx": 78 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as assert from 'assert'; import { URI } from 'vs/base/common/uri'; import { originalFSPath } from 'vs/base/common/resources'; import { isWindows } from 'vs/base/common/platform'; suite('ExtHost API', function () { test('issue #51387: originalFSPath', function () { if (isWindows) { assert.strictEqual(originalFSPath(URI.file('C:\\test')).charAt(0), 'C'); assert.strictEqual(originalFSPath(URI.file('c:\\test')).charAt(0), 'c'); assert.strictEqual(originalFSPath(URI.revive(JSON.parse(JSON.stringify(URI.file('C:\\test'))))).charAt(0), 'C'); assert.strictEqual(originalFSPath(URI.revive(JSON.parse(JSON.stringify(URI.file('c:\\test'))))).charAt(0), 'c'); } }); });
src/vs/workbench/api/test/browser/extHost.api.impl.test.ts
0
https://github.com/microsoft/vscode/commit/9c17df54bd27cf9976e30a09749519bfc4e3a815
[ 0.00017715951253194362, 0.0001741321902954951, 0.0001720136497169733, 0.00017322340863756835, 0.0000021968749024381395 ]
{ "id": 1, "code_window": [ "\t\tdata.metadata = {\n", "\t\t\tcustom: {\n", "\t\t\t\tcells: [],\n", "\t\t\t\tmetadata: {\n", "\t\t\t\t\torig_nbformat: 4\n", "\t\t\t\t},\n", "\t\t\t\tnbformat: 4,\n", "\t\t\t\tnbformat_minor: 2\n", "\t\t\t}\n", "\t\t};\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tmetadata: {},\n" ], "file_path": "extensions/ipynb/src/ipynbMain.ts", "type": "replace", "edit_start_line_idx": 78 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // @ts-check const mappings = [ ['bat', 'source.batchfile'], ['c', 'source.c'], ['clj', 'source.clojure'], ['coffee', 'source.coffee'], ['cpp', 'source.cpp', '\\.(?:cpp|c\\+\\+|cc|cxx|hxx|h\\+\\+|hh)'], ['cs', 'source.cs'], ['cshtml', 'text.html.cshtml'], ['css', 'source.css'], ['dart', 'source.dart'], ['diff', 'source.diff'], ['dockerfile', 'source.dockerfile', '(?:dockerfile|Dockerfile|containerfile|Containerfile)'], ['fs', 'source.fsharp'], ['go', 'source.go'], ['groovy', 'source.groovy'], ['h', 'source.objc'], ['handlebars', 'text.html.handlebars', '\\.(?:handlebars|hbs)'], ['hlsl', 'source.hlsl'], ['hpp', 'source.objcpp'], ['html', 'text.html.basic'], ['ini', 'source.ini'], ['java', 'source.java'], ['jl', 'source.julia'], ['js', 'source.js'], ['json', 'source.json.comments'], ['jsx', 'source.js.jsx'], ['less', 'source.css.less'], ['log', 'text.log'], ['lua', 'source.lua'], ['m', 'source.objc'], ['makefile', 'source.makefile', '(?:makefile|Makefile)(?:\\..*)?'], ['md', 'text.html.markdown'], ['mm', 'source.objcpp'], ['p6', 'source.perl.6'], ['perl', 'source.perl', '\\.(?:perl|pl|pm)'], ['php', 'source.php'], ['ps1', 'source.powershell'], ['pug', 'text.pug'], ['py', 'source.python'], ['r', 'source.r'], ['rb', 'source.ruby'], ['rs', 'source.rust'], ['scala', 'source.scala'], ['scss', 'source.css.scss'], ['sh', 'source.shell'], ['sql', 'source.sql'], ['swift', 'source.swift'], ['ts', 'source.ts'], ['tsx', 'source.tsx'], ['vb', 'source.asp.vb.net'], ['xml', 'text.xml'], ['yaml', 'source.yaml', '\\.(?:ya?ml)'], ]; const scopes = { root: 'text.searchResult', header: { meta: 'meta.header.search keyword.operator.word.search', key: 'entity.other.attribute-name', value: 'entity.other.attribute-value string.unquoted', flags: { keyword: 'keyword.other', }, contextLines: { number: 'constant.numeric.integer', invalid: 'invalid.illegal', }, query: { escape: 'constant.character.escape', invalid: 'invalid.illegal', } }, resultBlock: { meta: 'meta.resultBlock.search', path: { meta: 'string meta.path.search', dirname: 'meta.path.dirname.search', basename: 'meta.path.basename.search', colon: 'punctuation.separator', }, result: { meta: 'meta.resultLine.search', metaSingleLine: 'meta.resultLine.singleLine.search', metaMultiLine: 'meta.resultLine.multiLine.search', elision: 'comment meta.resultLine.elision', prefix: { meta: 'constant.numeric.integer meta.resultLinePrefix.search', metaContext: 'meta.resultLinePrefix.contextLinePrefix.search', metaMatch: 'meta.resultLinePrefix.matchLinePrefix.search', lineNumber: 'meta.resultLinePrefix.lineNumber.search', colon: 'punctuation.separator', } } } }; const repository = {}; mappings.forEach(([ext, scope, regexp]) => repository[ext] = { name: scopes.resultBlock.meta, begin: `^(?!\\s)(.*?)([^\\\\\\/\\n]*${regexp || `\\.${ext}`})(:)$`, end: '^(?!\\s)', beginCaptures: { '0': { name: scopes.resultBlock.path.meta }, '1': { name: scopes.resultBlock.path.dirname }, '2': { name: scopes.resultBlock.path.basename }, '3': { name: scopes.resultBlock.path.colon }, }, patterns: [ { name: [scopes.resultBlock.result.meta, scopes.resultBlock.result.metaMultiLine].join(' '), begin: '^ (?:\\s*)((\\d+) )', while: '^ (?:\\s*)(?:((\\d+)(:))|((\\d+) ))', beginCaptures: { '0': { name: scopes.resultBlock.result.prefix.meta }, '1': { name: scopes.resultBlock.result.prefix.metaContext }, '2': { name: scopes.resultBlock.result.prefix.lineNumber }, }, whileCaptures: { '0': { name: scopes.resultBlock.result.prefix.meta }, '1': { name: scopes.resultBlock.result.prefix.metaMatch }, '2': { name: scopes.resultBlock.result.prefix.lineNumber }, '3': { name: scopes.resultBlock.result.prefix.colon }, '4': { name: scopes.resultBlock.result.prefix.metaContext }, '5': { name: scopes.resultBlock.result.prefix.lineNumber }, }, patterns: [{ include: scope }] }, { begin: '^ (?:\\s*)((\\d+)(:))', while: '(?=not)possible', name: [scopes.resultBlock.result.meta, scopes.resultBlock.result.metaSingleLine].join(' '), beginCaptures: { '0': { name: scopes.resultBlock.result.prefix.meta }, '1': { name: scopes.resultBlock.result.prefix.metaMatch }, '2': { name: scopes.resultBlock.result.prefix.lineNumber }, '3': { name: scopes.resultBlock.result.prefix.colon }, }, patterns: [{ include: scope }] } ] }); const header = [ { begin: '^(# Query): ', end: '\n', name: scopes.header.meta, beginCaptures: { '1': { name: scopes.header.key }, }, patterns: [ { match: '(\\\\n)|(\\\\\\\\)', name: [scopes.header.value, scopes.header.query.escape].join(' ') }, { match: '\\\\.|\\\\$', name: [scopes.header.value, scopes.header.query.invalid].join(' ') }, { match: '[^\\\\\\\n]+', name: [scopes.header.value].join(' ') }, ] }, { begin: '^(# Flags): ', end: '\n', name: scopes.header.meta, beginCaptures: { '1': { name: scopes.header.key }, }, patterns: [ { match: '(RegExp|CaseSensitive|IgnoreExcludeSettings|WordMatch)', name: [scopes.header.value, 'keyword.other'].join(' ') }, { match: '.' }, ] }, { begin: '^(# ContextLines): ', end: '\n', name: scopes.header.meta, beginCaptures: { '1': { name: scopes.header.key }, }, patterns: [ { match: '\\d', name: [scopes.header.value, scopes.header.contextLines.number].join(' ') }, { match: '.', name: scopes.header.contextLines.invalid }, ] }, { match: '^(# (?:Including|Excluding)): (.*)$', name: scopes.header.meta, captures: { '1': { name: scopes.header.key }, '2': { name: scopes.header.value } } }, ]; const plainText = [ { match: '^(?!\\s)(.*?)([^\\\\\\/\\n]*)(:)$', name: [scopes.resultBlock.meta, scopes.resultBlock.path.meta].join(' '), captures: { '1': { name: scopes.resultBlock.path.dirname }, '2': { name: scopes.resultBlock.path.basename }, '3': { name: scopes.resultBlock.path.colon } } }, { match: '^ (?:\\s*)(?:((\\d+)(:))|((\\d+)( ))(.*))', name: [scopes.resultBlock.meta, scopes.resultBlock.result.meta].join(' '), captures: { '1': { name: [scopes.resultBlock.result.prefix.meta, scopes.resultBlock.result.prefix.metaMatch].join(' ') }, '2': { name: scopes.resultBlock.result.prefix.lineNumber }, '3': { name: scopes.resultBlock.result.prefix.colon }, '4': { name: [scopes.resultBlock.result.prefix.meta, scopes.resultBlock.result.prefix.metaContext].join(' ') }, '5': { name: scopes.resultBlock.result.prefix.lineNumber }, } }, { match: '⟪ [0-9]+ characters skipped ⟫', name: [scopes.resultBlock.meta, scopes.resultBlock.result.elision].join(' '), } ]; const tmLanguage = { 'information_for_contributors': 'This file is generated from ./generateTMLanguage.js.', name: 'Search Results', scopeName: scopes.root, patterns: [ ...header, ...mappings.map(([ext]) => ({ include: `#${ext}` })), ...plainText ], repository }; require('fs').writeFileSync( require('path').join(__dirname, './searchResult.tmLanguage.json'), JSON.stringify(tmLanguage, null, 2));
extensions/search-result/syntaxes/generateTMLanguage.js
0
https://github.com/microsoft/vscode/commit/9c17df54bd27cf9976e30a09749519bfc4e3a815
[ 0.00024818512611091137, 0.0001735502009978518, 0.00016548433632124215, 0.0001699601416476071, 0.000015340468962676823 ]
{ "id": 2, "code_window": [ "\t\t\t];\n", "\t\t}\n", "\n", "\t\t// For notebooks without metadata default the language in metadata to the preferred language.\n", "\t\tif (!json.metadata || (!json.metadata.kernelspec && !json.metadata.language_info)) {\n", "\t\t\tjson.metadata = json.metadata || { orig_nbformat: defaultNotebookFormat.major };\n", "\t\t\tjson.metadata.language_info = json.metadata.language_info || { name: preferredCellLanguage };\n", "\t\t}\n", "\n", "\t\tconst data = jupyterNotebookModelToNotebookData(\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tjson.metadata = json.metadata || {};\n" ], "file_path": "extensions/ipynb/src/notebookSerializer.ts", "type": "replace", "edit_start_line_idx": 65 }
/*--------------------------------------------------------------------------------------------- * 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 { NotebookSerializer } from './notebookSerializer'; import { ensureAllNewCellsHaveCellIds } from './cellIdService'; import { notebookImagePasteSetup } from './notebookImagePaste'; import { AttachmentCleaner } from './notebookAttachmentCleaner'; // From {nbformat.INotebookMetadata} in @jupyterlab/coreutils type NotebookMetadata = { kernelspec?: { name: string; display_name: string; [propName: string]: unknown; }; language_info?: { name: string; codemirror_mode?: string | {}; file_extension?: string; mimetype?: string; pygments_lexer?: string; [propName: string]: unknown; }; orig_nbformat: number; [propName: string]: unknown; }; export function activate(context: vscode.ExtensionContext) { const serializer = new NotebookSerializer(context); ensureAllNewCellsHaveCellIds(context); context.subscriptions.push(vscode.workspace.registerNotebookSerializer('jupyter-notebook', serializer, { transientOutputs: false, transientCellMetadata: { breakpointMargin: true, custom: false, attachments: false }, cellContentMetadata: { attachments: true } } as vscode.NotebookDocumentContentOptions)); context.subscriptions.push(vscode.workspace.registerNotebookSerializer('interactive', serializer, { transientOutputs: false, transientCellMetadata: { breakpointMargin: true, custom: false, attachments: false }, cellContentMetadata: { attachments: true } } as vscode.NotebookDocumentContentOptions)); vscode.languages.registerCodeLensProvider({ pattern: '**/*.ipynb' }, { provideCodeLenses: (document) => { if ( document.uri.scheme === 'vscode-notebook-cell' || document.uri.scheme === 'vscode-notebook-cell-metadata' || document.uri.scheme === 'vscode-notebook-cell-output' ) { return []; } const codelens = new vscode.CodeLens(new vscode.Range(0, 0, 0, 0), { title: 'Open in Notebook Editor', command: 'ipynb.openIpynbInNotebookEditor', arguments: [document.uri] }); return [codelens]; } }); context.subscriptions.push(vscode.commands.registerCommand('ipynb.newUntitledIpynb', async () => { const language = 'python'; const cell = new vscode.NotebookCellData(vscode.NotebookCellKind.Code, '', language); const data = new vscode.NotebookData([cell]); data.metadata = { custom: { cells: [], metadata: { orig_nbformat: 4 }, nbformat: 4, nbformat_minor: 2 } }; const doc = await vscode.workspace.openNotebookDocument('jupyter-notebook', data); await vscode.window.showNotebookDocument(doc); })); context.subscriptions.push(vscode.commands.registerCommand('ipynb.openIpynbInNotebookEditor', async (uri: vscode.Uri) => { if (vscode.window.activeTextEditor?.document.uri.toString() === uri.toString()) { await vscode.commands.executeCommand('workbench.action.closeActiveEditor'); } const document = await vscode.workspace.openNotebookDocument(uri); await vscode.window.showNotebookDocument(document); })); context.subscriptions.push(notebookImagePasteSetup()); const enabled = vscode.workspace.getConfiguration('ipynb').get('pasteImagesAsAttachments.enabled', false); if (enabled) { const cleaner = new AttachmentCleaner(); context.subscriptions.push(cleaner); } // Update new file contribution vscode.extensions.onDidChange(() => { vscode.commands.executeCommand('setContext', 'jupyterEnabled', vscode.extensions.getExtension('ms-toolsai.jupyter')); }); vscode.commands.executeCommand('setContext', 'jupyterEnabled', vscode.extensions.getExtension('ms-toolsai.jupyter')); return { exportNotebook: (notebook: vscode.NotebookData): string => { return exportNotebook(notebook, serializer); }, setNotebookMetadata: async (resource: vscode.Uri, metadata: Partial<NotebookMetadata>): Promise<boolean> => { const document = vscode.workspace.notebookDocuments.find(doc => doc.uri.toString() === resource.toString()); if (!document) { return false; } const edit = new vscode.WorkspaceEdit(); edit.set(resource, [vscode.NotebookEdit.updateNotebookMetadata({ ...document.metadata, custom: { ...(document.metadata.custom ?? {}), metadata: <NotebookMetadata>{ ...(document.metadata.custom?.metadata ?? {}), ...metadata }, } })]); return vscode.workspace.applyEdit(edit); }, }; } function exportNotebook(notebook: vscode.NotebookData, serializer: NotebookSerializer): string { return serializer.serializeNotebookToString(notebook); } export function deactivate() { }
extensions/ipynb/src/ipynbMain.ts
1
https://github.com/microsoft/vscode/commit/9c17df54bd27cf9976e30a09749519bfc4e3a815
[ 0.07503392547369003, 0.00518870260566473, 0.0001652325299801305, 0.00017360968922730535, 0.018667072057724 ]
{ "id": 2, "code_window": [ "\t\t\t];\n", "\t\t}\n", "\n", "\t\t// For notebooks without metadata default the language in metadata to the preferred language.\n", "\t\tif (!json.metadata || (!json.metadata.kernelspec && !json.metadata.language_info)) {\n", "\t\t\tjson.metadata = json.metadata || { orig_nbformat: defaultNotebookFormat.major };\n", "\t\t\tjson.metadata.language_info = json.metadata.language_info || { name: preferredCellLanguage };\n", "\t\t}\n", "\n", "\t\tconst data = jupyterNotebookModelToNotebookData(\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tjson.metadata = json.metadata || {};\n" ], "file_path": "extensions/ipynb/src/notebookSerializer.ts", "type": "replace", "edit_start_line_idx": 65 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // NOTE: THIS FILE WILL BE OVERWRITTEN DURING BUILD TIME, DO NOT EDIT
src/vs/workbench/workbench.web.main.nls.js
0
https://github.com/microsoft/vscode/commit/9c17df54bd27cf9976e30a09749519bfc4e3a815
[ 0.00017510293400846422, 0.00017510293400846422, 0.00017510293400846422, 0.00017510293400846422, 0 ]
{ "id": 2, "code_window": [ "\t\t\t];\n", "\t\t}\n", "\n", "\t\t// For notebooks without metadata default the language in metadata to the preferred language.\n", "\t\tif (!json.metadata || (!json.metadata.kernelspec && !json.metadata.language_info)) {\n", "\t\t\tjson.metadata = json.metadata || { orig_nbformat: defaultNotebookFormat.major };\n", "\t\t\tjson.metadata.language_info = json.metadata.language_info || { name: preferredCellLanguage };\n", "\t\t}\n", "\n", "\t\tconst data = jupyterNotebookModelToNotebookData(\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tjson.metadata = json.metadata || {};\n" ], "file_path": "extensions/ipynb/src/notebookSerializer.ts", "type": "replace", "edit_start_line_idx": 65 }
{ "name": "make", "displayName": "%displayName%", "description": "%description%", "version": "1.0.0", "publisher": "vscode", "license": "MIT", "engines": { "vscode": "*" }, "scripts": { "update-grammar": "node ../node_modules/vscode-grammar-updater/bin fadeevab/make.tmbundle Syntaxes/Makefile.plist ./syntaxes/make.tmLanguage.json" }, "contributes": { "languages": [ { "id": "makefile", "aliases": [ "Makefile", "makefile" ], "extensions": [ ".mak", ".mk" ], "filenames": [ "Makefile", "makefile", "GNUmakefile", "OCamlMakefile" ], "firstLine": "^#!\\s*/usr/bin/make", "configuration": "./language-configuration.json" } ], "grammars": [ { "language": "makefile", "scopeName": "source.makefile", "path": "./syntaxes/make.tmLanguage.json", "tokenTypes": { "string.interpolated": "other" } } ], "configurationDefaults": { "[makefile]": { "editor.insertSpaces": false } } }, "repository": { "type": "git", "url": "https://github.com/microsoft/vscode.git" } }
extensions/make/package.json
0
https://github.com/microsoft/vscode/commit/9c17df54bd27cf9976e30a09749519bfc4e3a815
[ 0.000176854882738553, 0.00017405995458830148, 0.00017100870900321752, 0.00017439083603676409, 0.000002213029802078381 ]
{ "id": 2, "code_window": [ "\t\t\t];\n", "\t\t}\n", "\n", "\t\t// For notebooks without metadata default the language in metadata to the preferred language.\n", "\t\tif (!json.metadata || (!json.metadata.kernelspec && !json.metadata.language_info)) {\n", "\t\t\tjson.metadata = json.metadata || { orig_nbformat: defaultNotebookFormat.major };\n", "\t\t\tjson.metadata.language_info = json.metadata.language_info || { name: preferredCellLanguage };\n", "\t\t}\n", "\n", "\t\tconst data = jupyterNotebookModelToNotebookData(\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tjson.metadata = json.metadata || {};\n" ], "file_path": "extensions/ipynb/src/notebookSerializer.ts", "type": "replace", "edit_start_line_idx": 65 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { ICellOutputViewModel, ICellViewModel } from 'vs/workbench/contrib/notebook/browser/notebookBrowser'; import { mock } from 'vs/base/test/common/mock'; import { IClipboardService } from 'vs/platform/clipboard/common/clipboardService'; import { ILogService } from 'vs/platform/log/common/log'; import * as assert from 'assert'; import { VSBuffer } from 'vs/base/common/buffer'; import { IOutputItemDto } from 'vs/workbench/contrib/notebook/common/notebookCommon'; import { copyCellOutput } from 'vs/workbench/contrib/notebook/browser/contrib/clipboard/cellOutputClipboard'; suite('Cell Output Clipboard Tests', () => { class ClipboardService { private _clipboardContent = ''; public get clipboardContent() { return this._clipboardContent; } public async writeText(value: string) { this._clipboardContent = value; } } const logService = new class extends mock<ILogService>() { }; function createOutputViewModel(outputs: IOutputItemDto[], cellViewModel?: ICellViewModel) { const outputViewModel = { model: { outputs: outputs } } as ICellOutputViewModel; if (cellViewModel) { cellViewModel.outputsViewModels.push(outputViewModel); cellViewModel.model.outputs.push(outputViewModel.model); } else { cellViewModel = { outputsViewModels: [outputViewModel], model: { outputs: [outputViewModel.model] } } as ICellViewModel; } outputViewModel.cellViewModel = cellViewModel; return outputViewModel; } test('Copy text/plain output', async () => { const mimeType = 'text/plain'; const clipboard = new ClipboardService(); const outputDto = { data: VSBuffer.fromString('output content'), mime: 'text/plain' }; const output = createOutputViewModel([outputDto]); await copyCellOutput(mimeType, output, clipboard as unknown as IClipboardService, logService); assert.strictEqual(clipboard.clipboardContent, 'output content'); }); test('Nothing copied for invalid mimetype', async () => { const clipboard = new ClipboardService(); const outputDtos = [ { data: VSBuffer.fromString('output content'), mime: 'bad' }, { data: VSBuffer.fromString('output 2'), mime: 'unknown' }]; const output = createOutputViewModel(outputDtos); await copyCellOutput('bad', output, clipboard as unknown as IClipboardService, logService); assert.strictEqual(clipboard.clipboardContent, ''); }); test('Text copied if available instead of invalid mime type', async () => { const clipboard = new ClipboardService(); const outputDtos = [ { data: VSBuffer.fromString('output content'), mime: 'bad' }, { data: VSBuffer.fromString('text content'), mime: 'text/plain' }]; const output = createOutputViewModel(outputDtos); await copyCellOutput('bad', output, clipboard as unknown as IClipboardService, logService); assert.strictEqual(clipboard.clipboardContent, 'text content'); }); test('Selected mimetype is preferred', async () => { const clipboard = new ClipboardService(); const outputDtos = [ { data: VSBuffer.fromString('plain text'), mime: 'text/plain' }, { data: VSBuffer.fromString('html content'), mime: 'text/html' }]; const output = createOutputViewModel(outputDtos); await copyCellOutput('text/html', output, clipboard as unknown as IClipboardService, logService); assert.strictEqual(clipboard.clipboardContent, 'html content'); }); test('copy subsequent output', async () => { const clipboard = new ClipboardService(); const output = createOutputViewModel([{ data: VSBuffer.fromString('first'), mime: 'text/plain' }]); const output2 = createOutputViewModel([{ data: VSBuffer.fromString('second'), mime: 'text/plain' }], output.cellViewModel as ICellViewModel); const output3 = createOutputViewModel([{ data: VSBuffer.fromString('third'), mime: 'text/plain' }], output.cellViewModel as ICellViewModel); await copyCellOutput('text/plain', output2, clipboard as unknown as IClipboardService, logService); assert.strictEqual(clipboard.clipboardContent, 'second'); await copyCellOutput('text/plain', output3, clipboard as unknown as IClipboardService, logService); assert.strictEqual(clipboard.clipboardContent, 'third'); }); test('adjacent stream outputs are concanented', async () => { const clipboard = new ClipboardService(); const output = createOutputViewModel([{ data: VSBuffer.fromString('stdout'), mime: 'application/vnd.code.notebook.stdout' }]); createOutputViewModel([{ data: VSBuffer.fromString('stderr'), mime: 'application/vnd.code.notebook.stderr' }], output.cellViewModel as ICellViewModel); createOutputViewModel([{ data: VSBuffer.fromString('text content'), mime: 'text/plain' }], output.cellViewModel as ICellViewModel); createOutputViewModel([{ data: VSBuffer.fromString('non-adjacent'), mime: 'application/vnd.code.notebook.stdout' }], output.cellViewModel as ICellViewModel); await copyCellOutput('application/vnd.code.notebook.stdout', output, clipboard as unknown as IClipboardService, logService); assert.strictEqual(clipboard.clipboardContent, 'stdoutstderr'); }); });
src/vs/workbench/contrib/notebook/test/browser/contrib/outputCopyTests.test.ts
0
https://github.com/microsoft/vscode/commit/9c17df54bd27cf9976e30a09749519bfc4e3a815
[ 0.00017465054406784475, 0.00017060876416508108, 0.00016684866568539292, 0.0001696616382105276, 0.000002768987314993865 ]
{ "id": 3, "code_window": [ "export function getNotebookMetadata(document: vscode.NotebookDocument | vscode.NotebookData) {\n", "\tconst notebookContent: Partial<nbformat.INotebookContent> = document.metadata?.custom || {};\n", "\tnotebookContent.cells = notebookContent.cells || [];\n", "\tnotebookContent.nbformat = notebookContent.nbformat || 4;\n", "\tnotebookContent.nbformat_minor = notebookContent.nbformat_minor ?? 2;\n", "\tnotebookContent.metadata = notebookContent.metadata || { orig_nbformat: 4 };\n", "\treturn notebookContent;\n", "}" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep" ], "after_edit": [ "\tnotebookContent.nbformat = notebookContent.nbformat || defaultNotebookFormat.major;\n", "\tnotebookContent.nbformat_minor = notebookContent.nbformat_minor ?? defaultNotebookFormat.minor;\n", "\tnotebookContent.metadata = notebookContent.metadata || {};\n" ], "file_path": "extensions/ipynb/src/notebookSerializer.ts", "type": "replace", "edit_start_line_idx": 103 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as vscode from 'vscode'; import { NotebookSerializer } from './notebookSerializer'; import { ensureAllNewCellsHaveCellIds } from './cellIdService'; import { notebookImagePasteSetup } from './notebookImagePaste'; import { AttachmentCleaner } from './notebookAttachmentCleaner'; // From {nbformat.INotebookMetadata} in @jupyterlab/coreutils type NotebookMetadata = { kernelspec?: { name: string; display_name: string; [propName: string]: unknown; }; language_info?: { name: string; codemirror_mode?: string | {}; file_extension?: string; mimetype?: string; pygments_lexer?: string; [propName: string]: unknown; }; orig_nbformat: number; [propName: string]: unknown; }; export function activate(context: vscode.ExtensionContext) { const serializer = new NotebookSerializer(context); ensureAllNewCellsHaveCellIds(context); context.subscriptions.push(vscode.workspace.registerNotebookSerializer('jupyter-notebook', serializer, { transientOutputs: false, transientCellMetadata: { breakpointMargin: true, custom: false, attachments: false }, cellContentMetadata: { attachments: true } } as vscode.NotebookDocumentContentOptions)); context.subscriptions.push(vscode.workspace.registerNotebookSerializer('interactive', serializer, { transientOutputs: false, transientCellMetadata: { breakpointMargin: true, custom: false, attachments: false }, cellContentMetadata: { attachments: true } } as vscode.NotebookDocumentContentOptions)); vscode.languages.registerCodeLensProvider({ pattern: '**/*.ipynb' }, { provideCodeLenses: (document) => { if ( document.uri.scheme === 'vscode-notebook-cell' || document.uri.scheme === 'vscode-notebook-cell-metadata' || document.uri.scheme === 'vscode-notebook-cell-output' ) { return []; } const codelens = new vscode.CodeLens(new vscode.Range(0, 0, 0, 0), { title: 'Open in Notebook Editor', command: 'ipynb.openIpynbInNotebookEditor', arguments: [document.uri] }); return [codelens]; } }); context.subscriptions.push(vscode.commands.registerCommand('ipynb.newUntitledIpynb', async () => { const language = 'python'; const cell = new vscode.NotebookCellData(vscode.NotebookCellKind.Code, '', language); const data = new vscode.NotebookData([cell]); data.metadata = { custom: { cells: [], metadata: { orig_nbformat: 4 }, nbformat: 4, nbformat_minor: 2 } }; const doc = await vscode.workspace.openNotebookDocument('jupyter-notebook', data); await vscode.window.showNotebookDocument(doc); })); context.subscriptions.push(vscode.commands.registerCommand('ipynb.openIpynbInNotebookEditor', async (uri: vscode.Uri) => { if (vscode.window.activeTextEditor?.document.uri.toString() === uri.toString()) { await vscode.commands.executeCommand('workbench.action.closeActiveEditor'); } const document = await vscode.workspace.openNotebookDocument(uri); await vscode.window.showNotebookDocument(document); })); context.subscriptions.push(notebookImagePasteSetup()); const enabled = vscode.workspace.getConfiguration('ipynb').get('pasteImagesAsAttachments.enabled', false); if (enabled) { const cleaner = new AttachmentCleaner(); context.subscriptions.push(cleaner); } // Update new file contribution vscode.extensions.onDidChange(() => { vscode.commands.executeCommand('setContext', 'jupyterEnabled', vscode.extensions.getExtension('ms-toolsai.jupyter')); }); vscode.commands.executeCommand('setContext', 'jupyterEnabled', vscode.extensions.getExtension('ms-toolsai.jupyter')); return { exportNotebook: (notebook: vscode.NotebookData): string => { return exportNotebook(notebook, serializer); }, setNotebookMetadata: async (resource: vscode.Uri, metadata: Partial<NotebookMetadata>): Promise<boolean> => { const document = vscode.workspace.notebookDocuments.find(doc => doc.uri.toString() === resource.toString()); if (!document) { return false; } const edit = new vscode.WorkspaceEdit(); edit.set(resource, [vscode.NotebookEdit.updateNotebookMetadata({ ...document.metadata, custom: { ...(document.metadata.custom ?? {}), metadata: <NotebookMetadata>{ ...(document.metadata.custom?.metadata ?? {}), ...metadata }, } })]); return vscode.workspace.applyEdit(edit); }, }; } function exportNotebook(notebook: vscode.NotebookData, serializer: NotebookSerializer): string { return serializer.serializeNotebookToString(notebook); } export function deactivate() { }
extensions/ipynb/src/ipynbMain.ts
1
https://github.com/microsoft/vscode/commit/9c17df54bd27cf9976e30a09749519bfc4e3a815
[ 0.00978463888168335, 0.0033324798569083214, 0.00016660097753629088, 0.0029122752603143454, 0.003475598990917206 ]
{ "id": 3, "code_window": [ "export function getNotebookMetadata(document: vscode.NotebookDocument | vscode.NotebookData) {\n", "\tconst notebookContent: Partial<nbformat.INotebookContent> = document.metadata?.custom || {};\n", "\tnotebookContent.cells = notebookContent.cells || [];\n", "\tnotebookContent.nbformat = notebookContent.nbformat || 4;\n", "\tnotebookContent.nbformat_minor = notebookContent.nbformat_minor ?? 2;\n", "\tnotebookContent.metadata = notebookContent.metadata || { orig_nbformat: 4 };\n", "\treturn notebookContent;\n", "}" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep" ], "after_edit": [ "\tnotebookContent.nbformat = notebookContent.nbformat || defaultNotebookFormat.major;\n", "\tnotebookContent.nbformat_minor = notebookContent.nbformat_minor ?? defaultNotebookFormat.minor;\n", "\tnotebookContent.metadata = notebookContent.metadata || {};\n" ], "file_path": "extensions/ipynb/src/notebookSerializer.ts", "type": "replace", "edit_start_line_idx": 103 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ export interface NLSConfiguration { locale: string; osLocale: string; availableLanguages: { [key: string]: string; }; pseudo?: boolean; _languagePackSupport?: boolean; } export interface InternalNLSConfiguration extends NLSConfiguration { _languagePackId: string; _translationsConfigFile: string; _cacheRoot: string; _resolvedLanguagePackCoreLocation: string; _corruptedFile: string; _languagePackSupport?: boolean; } export function getNLSConfiguration(commit: string | undefined, userDataPath: string, metaDataFile: string, locale: string, osLocale: string): Promise<NLSConfiguration>;
src/vs/base/node/languagePacks.d.ts
0
https://github.com/microsoft/vscode/commit/9c17df54bd27cf9976e30a09749519bfc4e3a815
[ 0.00017621138249523938, 0.0001712454977678135, 0.00016412754484917969, 0.0001733975950628519, 0.000005162582965567708 ]
{ "id": 3, "code_window": [ "export function getNotebookMetadata(document: vscode.NotebookDocument | vscode.NotebookData) {\n", "\tconst notebookContent: Partial<nbformat.INotebookContent> = document.metadata?.custom || {};\n", "\tnotebookContent.cells = notebookContent.cells || [];\n", "\tnotebookContent.nbformat = notebookContent.nbformat || 4;\n", "\tnotebookContent.nbformat_minor = notebookContent.nbformat_minor ?? 2;\n", "\tnotebookContent.metadata = notebookContent.metadata || { orig_nbformat: 4 };\n", "\treturn notebookContent;\n", "}" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep" ], "after_edit": [ "\tnotebookContent.nbformat = notebookContent.nbformat || defaultNotebookFormat.major;\n", "\tnotebookContent.nbformat_minor = notebookContent.nbformat_minor ?? defaultNotebookFormat.minor;\n", "\tnotebookContent.metadata = notebookContent.metadata || {};\n" ], "file_path": "extensions/ipynb/src/notebookSerializer.ts", "type": "replace", "edit_start_line_idx": 103 }
extensions/markdown-language-features/test-workspace/sub/d.md
0
https://github.com/microsoft/vscode/commit/9c17df54bd27cf9976e30a09749519bfc4e3a815
[ 0.00017478650261182338, 0.00017478650261182338, 0.00017478650261182338, 0.00017478650261182338, 0 ]
{ "id": 3, "code_window": [ "export function getNotebookMetadata(document: vscode.NotebookDocument | vscode.NotebookData) {\n", "\tconst notebookContent: Partial<nbformat.INotebookContent> = document.metadata?.custom || {};\n", "\tnotebookContent.cells = notebookContent.cells || [];\n", "\tnotebookContent.nbformat = notebookContent.nbformat || 4;\n", "\tnotebookContent.nbformat_minor = notebookContent.nbformat_minor ?? 2;\n", "\tnotebookContent.metadata = notebookContent.metadata || { orig_nbformat: 4 };\n", "\treturn notebookContent;\n", "}" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep" ], "after_edit": [ "\tnotebookContent.nbformat = notebookContent.nbformat || defaultNotebookFormat.major;\n", "\tnotebookContent.nbformat_minor = notebookContent.nbformat_minor ?? defaultNotebookFormat.minor;\n", "\tnotebookContent.metadata = notebookContent.metadata || {};\n" ], "file_path": "extensions/ipynb/src/notebookSerializer.ts", "type": "replace", "edit_start_line_idx": 103 }
<script type="text/javascript"> window.alert('hello'); </script> <script> window.alert('hello'); </script>
extensions/vscode-colorize-tests/test/colorize-fixtures/12750.html
0
https://github.com/microsoft/vscode/commit/9c17df54bd27cf9976e30a09749519bfc4e3a815
[ 0.00017446595302317291, 0.00017446595302317291, 0.00017446595302317291, 0.00017446595302317291, 0 ]
{ "id": 0, "code_window": [ "export interface LoadExploreDataSourcesPayload {\n", " exploreId: ExploreId;\n", " exploreDatasources: DataSourceSelectItem[];\n", "}\n", "\n", "/**\n", " * Adds a query row after the row with the given index.\n", " */\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "export interface RunQueriesPayload {\n", " exploreId: ExploreId;\n", "}\n", "\n" ], "file_path": "public/app/features/explore/state/actionTypes.ts", "type": "add", "edit_start_line_idx": 211 }
// Types import { Emitter } from 'app/core/core'; import { RawTimeRange, TimeRange, DataQuery, DataSourceSelectItem, DataSourceApi, QueryFixAction, LogLevel, } from '@grafana/ui/src/types'; import { ExploreId, ExploreItemState, HistoryItem, RangeScanner, ResultType, QueryTransaction, ExploreUIState, } from 'app/types/explore'; import { actionCreatorFactory, noPayloadActionCreatorFactory, ActionOf } from 'app/core/redux/actionCreatorFactory'; /** Higher order actions * */ export enum ActionTypes { SplitOpen = 'explore/SPLIT_OPEN', ResetExplore = 'explore/RESET_EXPLORE', } export interface SplitOpenAction { type: ActionTypes.SplitOpen; payload: { itemState: ExploreItemState; }; } export interface ResetExploreAction { type: ActionTypes.ResetExplore; payload: {}; } /** Lower order actions * */ export interface AddQueryRowPayload { exploreId: ExploreId; index: number; query: DataQuery; } export interface ChangeQueryPayload { exploreId: ExploreId; query: DataQuery; index: number; override: boolean; } export interface ChangeSizePayload { exploreId: ExploreId; width: number; height: number; } export interface ChangeTimePayload { exploreId: ExploreId; range: TimeRange; } export interface ClearQueriesPayload { exploreId: ExploreId; } export interface HighlightLogsExpressionPayload { exploreId: ExploreId; expressions: string[]; } export interface InitializeExplorePayload { exploreId: ExploreId; containerWidth: number; eventBridge: Emitter; queries: DataQuery[]; range: RawTimeRange; ui: ExploreUIState; } export interface LoadDatasourceFailurePayload { exploreId: ExploreId; error: string; } export interface LoadDatasourceMissingPayload { exploreId: ExploreId; } export interface LoadDatasourcePendingPayload { exploreId: ExploreId; requestedDatasourceName: string; } export interface LoadDatasourceReadyPayload { exploreId: ExploreId; history: HistoryItem[]; } export interface TestDatasourcePendingPayload { exploreId: ExploreId; } export interface TestDatasourceFailurePayload { exploreId: ExploreId; error: string; } export interface TestDatasourceSuccessPayload { exploreId: ExploreId; } export interface ModifyQueriesPayload { exploreId: ExploreId; modification: QueryFixAction; index: number; modifier: (query: DataQuery, modification: QueryFixAction) => DataQuery; } export interface QueryTransactionFailurePayload { exploreId: ExploreId; queryTransactions: QueryTransaction[]; } export interface QueryTransactionStartPayload { exploreId: ExploreId; resultType: ResultType; rowIndex: number; transaction: QueryTransaction; } export interface QueryTransactionSuccessPayload { exploreId: ExploreId; history: HistoryItem[]; queryTransactions: QueryTransaction[]; } export interface RemoveQueryRowPayload { exploreId: ExploreId; index: number; } export interface ScanStartPayload { exploreId: ExploreId; scanner: RangeScanner; } export interface ScanRangePayload { exploreId: ExploreId; range: RawTimeRange; } export interface ScanStopPayload { exploreId: ExploreId; } export interface SetQueriesPayload { exploreId: ExploreId; queries: DataQuery[]; } export interface SplitCloseActionPayload { itemId: ExploreId; } export interface SplitOpenPayload { itemState: ExploreItemState; } export interface ToggleTablePayload { exploreId: ExploreId; } export interface ToggleGraphPayload { exploreId: ExploreId; } export interface ToggleLogsPayload { exploreId: ExploreId; } export interface UpdateUIStatePayload extends Partial<ExploreUIState> { exploreId: ExploreId; } export interface UpdateDatasourceInstancePayload { exploreId: ExploreId; datasourceInstance: DataSourceApi; } export interface ToggleLogLevelPayload { exploreId: ExploreId; hiddenLogLevels: Set<LogLevel>; } export interface QueriesImportedPayload { exploreId: ExploreId; queries: DataQuery[]; } export interface LoadExploreDataSourcesPayload { exploreId: ExploreId; exploreDatasources: DataSourceSelectItem[]; } /** * Adds a query row after the row with the given index. */ export const addQueryRowAction = actionCreatorFactory<AddQueryRowPayload>('explore/ADD_QUERY_ROW').create(); /** * Loads a new datasource identified by the given name. */ export const changeDatasourceAction = noPayloadActionCreatorFactory('explore/CHANGE_DATASOURCE').create(); /** * Query change handler for the query row with the given index. * If `override` is reset the query modifications and run the queries. Use this to set queries via a link. */ export const changeQueryAction = actionCreatorFactory<ChangeQueryPayload>('explore/CHANGE_QUERY').create(); /** * Keep track of the Explore container size, in particular the width. * The width will be used to calculate graph intervals (number of datapoints). */ export const changeSizeAction = actionCreatorFactory<ChangeSizePayload>('explore/CHANGE_SIZE').create(); /** * Change the time range of Explore. Usually called from the Timepicker or a graph interaction. */ export const changeTimeAction = actionCreatorFactory<ChangeTimePayload>('explore/CHANGE_TIME').create(); /** * Clear all queries and results. */ export const clearQueriesAction = actionCreatorFactory<ClearQueriesPayload>('explore/CLEAR_QUERIES').create(); /** * Highlight expressions in the log results */ export const highlightLogsExpressionAction = actionCreatorFactory<HighlightLogsExpressionPayload>( 'explore/HIGHLIGHT_LOGS_EXPRESSION' ).create(); /** * Initialize Explore state with state from the URL and the React component. * Call this only on components for with the Explore state has not been initialized. */ export const initializeExploreAction = actionCreatorFactory<InitializeExplorePayload>( 'explore/INITIALIZE_EXPLORE' ).create(); /** * Display an error when no datasources have been configured */ export const loadDatasourceMissingAction = actionCreatorFactory<LoadDatasourceMissingPayload>( 'explore/LOAD_DATASOURCE_MISSING' ).create(); /** * Start the async process of loading a datasource to display a loading indicator */ export const loadDatasourcePendingAction = actionCreatorFactory<LoadDatasourcePendingPayload>( 'explore/LOAD_DATASOURCE_PENDING' ).create(); /** * Datasource loading was completed. */ export const loadDatasourceReadyAction = actionCreatorFactory<LoadDatasourceReadyPayload>( 'explore/LOAD_DATASOURCE_READY' ).create(); /** * Action to modify a query given a datasource-specific modifier action. * @param exploreId Explore area * @param modification Action object with a type, e.g., ADD_FILTER * @param index Optional query row index. If omitted, the modification is applied to all query rows. * @param modifier Function that executes the modification, typically `datasourceInstance.modifyQueries`. */ export const modifyQueriesAction = actionCreatorFactory<ModifyQueriesPayload>('explore/MODIFY_QUERIES').create(); /** * Mark a query transaction as failed with an error extracted from the query response. * The transaction will be marked as `done`. */ export const queryTransactionFailureAction = actionCreatorFactory<QueryTransactionFailurePayload>( 'explore/QUERY_TRANSACTION_FAILURE' ).create(); /** * Start a query transaction for the given result type. * @param exploreId Explore area * @param transaction Query options and `done` status. * @param resultType Associate the transaction with a result viewer, e.g., Graph * @param rowIndex Index is used to associate latency for this transaction with a query row */ export const queryTransactionStartAction = actionCreatorFactory<QueryTransactionStartPayload>( 'explore/QUERY_TRANSACTION_START' ).create(); /** * Complete a query transaction, mark the transaction as `done` and store query state in URL. * If the transaction was started by a scanner, it keeps on scanning for more results. * Side-effect: the query is stored in localStorage. * @param exploreId Explore area * @param transactionId ID * @param result Response from `datasourceInstance.query()` * @param latency Duration between request and response * @param queries Queries from all query rows * @param datasourceId Origin datasource instance, used to discard results if current datasource is different */ export const queryTransactionSuccessAction = actionCreatorFactory<QueryTransactionSuccessPayload>( 'explore/QUERY_TRANSACTION_SUCCESS' ).create(); /** * Remove query row of the given index, as well as associated query results. */ export const removeQueryRowAction = actionCreatorFactory<RemoveQueryRowPayload>('explore/REMOVE_QUERY_ROW').create(); export const runQueriesAction = noPayloadActionCreatorFactory('explore/RUN_QUERIES').create(); /** * Start a scan for more results using the given scanner. * @param exploreId Explore area * @param scanner Function that a) returns a new time range and b) triggers a query run for the new range */ export const scanStartAction = actionCreatorFactory<ScanStartPayload>('explore/SCAN_START').create(); export const scanRangeAction = actionCreatorFactory<ScanRangePayload>('explore/SCAN_RANGE').create(); /** * Stop any scanning for more results. */ export const scanStopAction = actionCreatorFactory<ScanStopPayload>('explore/SCAN_STOP').create(); /** * Reset queries to the given queries. Any modifications will be discarded. * Use this action for clicks on query examples. Triggers a query run. */ export const setQueriesAction = actionCreatorFactory<SetQueriesPayload>('explore/SET_QUERIES').create(); /** * Close the split view and save URL state. */ export const splitCloseAction = actionCreatorFactory<SplitCloseActionPayload>('explore/SPLIT_CLOSE').create(); /** * Open the split view and copy the left state to be the right state. * The right state is automatically initialized. * The copy keeps all query modifications but wipes the query results. */ export const splitOpenAction = actionCreatorFactory<SplitOpenPayload>('explore/SPLIT_OPEN').create(); export const stateSaveAction = noPayloadActionCreatorFactory('explore/STATE_SAVE').create(); /** * Update state of Explores UI elements (panels visiblity and deduplication strategy) */ export const updateUIStateAction = actionCreatorFactory<UpdateUIStatePayload>('explore/UPDATE_UI_STATE').create(); /** * Expand/collapse the table result viewer. When collapsed, table queries won't be run. */ export const toggleTableAction = actionCreatorFactory<ToggleTablePayload>('explore/TOGGLE_TABLE').create(); /** * Expand/collapse the graph result viewer. When collapsed, graph queries won't be run. */ export const toggleGraphAction = actionCreatorFactory<ToggleGraphPayload>('explore/TOGGLE_GRAPH').create(); /** * Expand/collapse the logs result viewer. When collapsed, log queries won't be run. */ export const toggleLogsAction = actionCreatorFactory<ToggleLogsPayload>('explore/TOGGLE_LOGS').create(); /** * Updates datasource instance before datasouce loading has started */ export const updateDatasourceInstanceAction = actionCreatorFactory<UpdateDatasourceInstancePayload>( 'explore/UPDATE_DATASOURCE_INSTANCE' ).create(); export const toggleLogLevelAction = actionCreatorFactory<ToggleLogLevelPayload>('explore/TOGGLE_LOG_LEVEL').create(); /** * Resets state for explore. */ export const resetExploreAction = noPayloadActionCreatorFactory('explore/RESET_EXPLORE').create(); export const queriesImportedAction = actionCreatorFactory<QueriesImportedPayload>('explore/QueriesImported').create(); export const testDataSourcePendingAction = actionCreatorFactory<TestDatasourcePendingPayload>( 'explore/TEST_DATASOURCE_PENDING' ).create(); export const testDataSourceSuccessAction = actionCreatorFactory<TestDatasourceSuccessPayload>( 'explore/TEST_DATASOURCE_SUCCESS' ).create(); export const testDataSourceFailureAction = actionCreatorFactory<TestDatasourceFailurePayload>( 'explore/TEST_DATASOURCE_FAILURE' ).create(); export const loadExploreDatasources = actionCreatorFactory<LoadExploreDataSourcesPayload>( 'explore/LOAD_EXPLORE_DATASOURCES' ).create(); export type HigherOrderAction = | ActionOf<SplitCloseActionPayload> | SplitOpenAction | ResetExploreAction | ActionOf<any>;
public/app/features/explore/state/actionTypes.ts
1
https://github.com/grafana/grafana/commit/1341f4517a3a67c58c8d4bca2b184fb3dea735f7
[ 0.9394308924674988, 0.032423343509435654, 0.00016630164464004338, 0.0002199930022470653, 0.15465551614761353 ]
{ "id": 0, "code_window": [ "export interface LoadExploreDataSourcesPayload {\n", " exploreId: ExploreId;\n", " exploreDatasources: DataSourceSelectItem[];\n", "}\n", "\n", "/**\n", " * Adds a query row after the row with the given index.\n", " */\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "export interface RunQueriesPayload {\n", " exploreId: ExploreId;\n", "}\n", "\n" ], "file_path": "public/app/features/explore/state/actionTypes.ts", "type": "add", "edit_start_line_idx": 211 }
import React from 'react'; import { FolderSettingsPage, Props } from './FolderSettingsPage'; import { NavModel } from 'app/types'; import { shallow } from 'enzyme'; const setup = (propOverrides?: object) => { const props: Props = { navModel: {} as NavModel, folderUid: '1234', folder: { id: 0, uid: '1234', title: 'loading', canSave: true, url: 'url', hasChanged: false, version: 1, permissions: [], }, getFolderByUid: jest.fn(), setFolderTitle: jest.fn(), saveFolder: jest.fn(), deleteFolder: jest.fn(), }; Object.assign(props, propOverrides); const wrapper = shallow(<FolderSettingsPage {...props} />); const instance = wrapper.instance() as FolderSettingsPage; return { wrapper, instance, }; }; describe('Render', () => { it('should render component', () => { const { wrapper } = setup(); expect(wrapper).toMatchSnapshot(); }); it('should enable save button', () => { const { wrapper } = setup({ folder: { id: 1, uid: '1234', title: 'loading', canSave: true, hasChanged: true, version: 1, }, }); expect(wrapper).toMatchSnapshot(); }); });
public/app/features/folders/FolderSettingsPage.test.tsx
0
https://github.com/grafana/grafana/commit/1341f4517a3a67c58c8d4bca2b184fb3dea735f7
[ 0.0001716381375445053, 0.00016995554324239492, 0.00016814070113468915, 0.00016963672533165663, 0.0000012646385130210547 ]