hunk
dict
file
stringlengths
0
11.8M
file_path
stringlengths
2
234
label
int64
0
1
commit_url
stringlengths
74
103
dependency_score
sequencelengths
5
5
{ "id": 0, "code_window": [ "tests/cases/compiler/a.js(1,10): error TS8016: 'type assertion expressions' can only be used in a .ts file.\n", "\n", "\n", "==== tests/cases/compiler/a.js (1 errors) ====\n" ], "labels": [ "replace", "keep", "keep", "keep" ], "after_edit": [ "tests/cases/compiler/a.js(1,27): error TS17002: Expected corresponding JSX closing tag for 'string'.\n" ], "file_path": "tests/baselines/reference/jsFileCompilationTypeAssertions.errors.txt", "type": "replace", "edit_start_line_idx": 0 }
=== tests/cases/compiler/shebang.ts === #!/usr/bin/env node var foo = 'I wish the generated JS to be executed in node'; >foo : string >'I wish the generated JS to be executed in node' : string
tests/baselines/reference/shebang.types
0
https://github.com/microsoft/TypeScript/commit/0fe282e71994ac950e32b8040e714f563609a32f
[ 0.00019222403352614492, 0.00019222403352614492, 0.00019222403352614492, 0.00019222403352614492, 0 ]
{ "id": 0, "code_window": [ "tests/cases/compiler/a.js(1,10): error TS8016: 'type assertion expressions' can only be used in a .ts file.\n", "\n", "\n", "==== tests/cases/compiler/a.js (1 errors) ====\n" ], "labels": [ "replace", "keep", "keep", "keep" ], "after_edit": [ "tests/cases/compiler/a.js(1,27): error TS17002: Expected corresponding JSX closing tag for 'string'.\n" ], "file_path": "tests/baselines/reference/jsFileCompilationTypeAssertions.errors.txt", "type": "replace", "edit_start_line_idx": 0 }
=== tests/cases/conformance/es6/unicodeExtendedEscapes/unicodeExtendedEscapesInTemplates11_ES6.ts === // ES6 Spec - 10.1.1 Static Semantics: UTF16Encoding (cp) // 2. Let cu2 be ((cp – 65536) modulo 1024) + 0xDC00. // Although we should just get back a single code point value of 0xDC00, // this is a useful edge-case test. var x = `\u{DC00}`; >x : string >`\u{DC00}` : string
tests/baselines/reference/unicodeExtendedEscapesInTemplates11_ES6.types
0
https://github.com/microsoft/TypeScript/commit/0fe282e71994ac950e32b8040e714f563609a32f
[ 0.00018457765690982342, 0.000181550596607849, 0.00017852355085778981, 0.000181550596607849, 0.0000030270530260168016 ]
{ "id": 1, "code_window": [ "\n", "\n", "==== tests/cases/compiler/a.js (1 errors) ====\n", " var v = <string>undefined;\n", " ~~~~~~\n", "!!! error TS8016: 'type assertion expressions' can only be used in a .ts file.\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace" ], "after_edit": [ " \n", "!!! error TS17002: Expected corresponding JSX closing tag for 'string'.\n" ], "file_path": "tests/baselines/reference/jsFileCompilationTypeAssertions.errors.txt", "type": "replace", "edit_start_line_idx": 5 }
/// <reference path="fourslash.ts" /> // @allowNonTsExtensions: true // @Filename: a.js //// var v = <string>undefined; verify.getSemanticDiagnostics(`[ { "message": "'type assertion expressions' can only be used in a .ts file.", "start": 9, "length": 6, "category": "error", "code": 8016 } ]`);
tests/cases/fourslash/getJavaScriptSemanticDiagnostics20.ts
1
https://github.com/microsoft/TypeScript/commit/0fe282e71994ac950e32b8040e714f563609a32f
[ 0.9936568140983582, 0.49691328406333923, 0.0001697613188298419, 0.49691328406333923, 0.4967435300350189 ]
{ "id": 1, "code_window": [ "\n", "\n", "==== tests/cases/compiler/a.js (1 errors) ====\n", " var v = <string>undefined;\n", " ~~~~~~\n", "!!! error TS8016: 'type assertion expressions' can only be used in a .ts file.\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace" ], "after_edit": [ " \n", "!!! error TS17002: Expected corresponding JSX closing tag for 'string'.\n" ], "file_path": "tests/baselines/reference/jsFileCompilationTypeAssertions.errors.txt", "type": "replace", "edit_start_line_idx": 5 }
=== tests/cases/conformance/parser/ecmascript5/VariableDeclarations/parserVariableDeclaration4.d.ts === declare var v; >v : any
tests/baselines/reference/parserVariableDeclaration4.d.types
0
https://github.com/microsoft/TypeScript/commit/0fe282e71994ac950e32b8040e714f563609a32f
[ 0.03617091849446297, 0.03617091849446297, 0.03617091849446297, 0.03617091849446297, 0 ]
{ "id": 1, "code_window": [ "\n", "\n", "==== tests/cases/compiler/a.js (1 errors) ====\n", " var v = <string>undefined;\n", " ~~~~~~\n", "!!! error TS8016: 'type assertion expressions' can only be used in a .ts file.\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace" ], "after_edit": [ " \n", "!!! error TS17002: Expected corresponding JSX closing tag for 'string'.\n" ], "file_path": "tests/baselines/reference/jsFileCompilationTypeAssertions.errors.txt", "type": "replace", "edit_start_line_idx": 5 }
// Each pair of signatures in these types has a signature that should cause an error. // Overloads, generic or not, that differ only by return type are an error. interface I { (x): number; (x): void; // error <T>(x: T): number; <T>(x: T): string; // error } interface I2 { <T>(x: T): number; <T>(x: T): string; // error } interface I3<T> { (x: T): number; (x: T): string; // error } var a: { (x, y): Object; (x, y): any; // error } var a2: { <T>(x: T): number; <T>(x: T): string; // error }
tests/cases/conformance/types/objectTypeLiteral/callSignatures/callSignaturesThatDifferOnlyByReturnType.ts
0
https://github.com/microsoft/TypeScript/commit/0fe282e71994ac950e32b8040e714f563609a32f
[ 0.0002539187844377011, 0.00020818751363549381, 0.00016829179367050529, 0.00020235196279827505, 0.000035199769627070054 ]
{ "id": 1, "code_window": [ "\n", "\n", "==== tests/cases/compiler/a.js (1 errors) ====\n", " var v = <string>undefined;\n", " ~~~~~~\n", "!!! error TS8016: 'type assertion expressions' can only be used in a .ts file.\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace" ], "after_edit": [ " \n", "!!! error TS17002: Expected corresponding JSX closing tag for 'string'.\n" ], "file_path": "tests/baselines/reference/jsFileCompilationTypeAssertions.errors.txt", "type": "replace", "edit_start_line_idx": 5 }
=== tests/cases/conformance/expressions/unaryOperators/bitwiseNotOperator/bitwiseNotOperatorWithBooleanType.ts === // ~ operator on boolean type var BOOLEAN: boolean; >BOOLEAN : boolean function foo(): boolean { return true; } >foo : () => boolean >true : boolean class A { >A : A public a: boolean; >a : boolean static foo() { return false; } >foo : () => boolean >false : boolean } module M { >M : typeof M export var n: boolean; >n : boolean } var objA = new A(); >objA : A >new A() : A >A : typeof A // boolean type var var ResultIsNumber1 = ~BOOLEAN; >ResultIsNumber1 : number >~BOOLEAN : number >BOOLEAN : boolean // boolean type literal var ResultIsNumber2 = ~true; >ResultIsNumber2 : number >~true : number >true : boolean var ResultIsNumber3 = ~{ x: true, y: false }; >ResultIsNumber3 : number >~{ x: true, y: false } : number >{ x: true, y: false } : { x: boolean; y: boolean; } >x : boolean >true : boolean >y : boolean >false : boolean // boolean type expressions var ResultIsNumber4 = ~objA.a; >ResultIsNumber4 : number >~objA.a : number >objA.a : boolean >objA : A >a : boolean var ResultIsNumber5 = ~M.n; >ResultIsNumber5 : number >~M.n : number >M.n : boolean >M : typeof M >n : boolean var ResultIsNumber6 = ~foo(); >ResultIsNumber6 : number >~foo() : number >foo() : boolean >foo : () => boolean var ResultIsNumber7 = ~A.foo(); >ResultIsNumber7 : number >~A.foo() : number >A.foo() : boolean >A.foo : () => boolean >A : typeof A >foo : () => boolean // multiple ~ operators var ResultIsNumber8 = ~~BOOLEAN; >ResultIsNumber8 : number >~~BOOLEAN : number >~BOOLEAN : number >BOOLEAN : boolean // miss assignment operators ~true; >~true : number >true : boolean ~BOOLEAN; >~BOOLEAN : number >BOOLEAN : boolean ~foo(); >~foo() : number >foo() : boolean >foo : () => boolean ~true, false; >~true, false : boolean >~true : number >true : boolean >false : boolean ~objA.a; >~objA.a : number >objA.a : boolean >objA : A >a : boolean ~M.n; >~M.n : number >M.n : boolean >M : typeof M >n : boolean
tests/baselines/reference/bitwiseNotOperatorWithBooleanType.types
0
https://github.com/microsoft/TypeScript/commit/0fe282e71994ac950e32b8040e714f563609a32f
[ 0.0006432655500248075, 0.0002079736441373825, 0.00016496915486641228, 0.00017320673214271665, 0.00012571888510137796 ]
{ "id": 2, "code_window": [ "\n", "// @allowNonTsExtensions: true\n", "// @Filename: a.js\n", "//// var v = <string>undefined;\n", "\n", "verify.getSemanticDiagnostics(`[\n", " {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "verify.getSyntacticDiagnostics(`[\n" ], "file_path": "tests/cases/fourslash/getJavaScriptSemanticDiagnostics20.ts", "type": "replace", "edit_start_line_idx": 6 }
/// <reference path="fourslash.ts" /> // @allowNonTsExtensions: true // @Filename: a.js //// var v = <string>undefined; verify.getSemanticDiagnostics(`[ { "message": "'type assertion expressions' can only be used in a .ts file.", "start": 9, "length": 6, "category": "error", "code": 8016 } ]`);
tests/cases/fourslash/getJavaScriptSemanticDiagnostics20.ts
1
https://github.com/microsoft/TypeScript/commit/0fe282e71994ac950e32b8040e714f563609a32f
[ 0.9981655478477478, 0.49916887283325195, 0.0001721803710097447, 0.49916887283325195, 0.49899670481681824 ]
{ "id": 2, "code_window": [ "\n", "// @allowNonTsExtensions: true\n", "// @Filename: a.js\n", "//// var v = <string>undefined;\n", "\n", "verify.getSemanticDiagnostics(`[\n", " {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "verify.getSyntacticDiagnostics(`[\n" ], "file_path": "tests/cases/fourslash/getJavaScriptSemanticDiagnostics20.ts", "type": "replace", "edit_start_line_idx": 6 }
=== tests/cases/conformance/es6/computedProperties/computedPropertyNames28_ES5.ts === class Base { >Base : Symbol(Base, Decl(computedPropertyNames28_ES5.ts, 0, 0)) } class C extends Base { >C : Symbol(C, Decl(computedPropertyNames28_ES5.ts, 1, 1)) >Base : Symbol(Base, Decl(computedPropertyNames28_ES5.ts, 0, 0)) constructor() { super(); >super : Symbol(Base, Decl(computedPropertyNames28_ES5.ts, 0, 0)) var obj = { >obj : Symbol(obj, Decl(computedPropertyNames28_ES5.ts, 5, 11)) [(super(), "prop")]() { } >super : Symbol(Base, Decl(computedPropertyNames28_ES5.ts, 0, 0)) }; } }
tests/baselines/reference/computedPropertyNames28_ES5.symbols
0
https://github.com/microsoft/TypeScript/commit/0fe282e71994ac950e32b8040e714f563609a32f
[ 0.00018195010488852859, 0.00017609423957765102, 0.00017290904361288995, 0.0001734235556796193, 0.000004146049832343124 ]
{ "id": 2, "code_window": [ "\n", "// @allowNonTsExtensions: true\n", "// @Filename: a.js\n", "//// var v = <string>undefined;\n", "\n", "verify.getSemanticDiagnostics(`[\n", " {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "verify.getSyntacticDiagnostics(`[\n" ], "file_path": "tests/cases/fourslash/getJavaScriptSemanticDiagnostics20.ts", "type": "replace", "edit_start_line_idx": 6 }
//// [sourceMapValidationModule.js.map] {"version":3,"file":"sourceMapValidationModule.js","sourceRoot":"","sources":["sourceMapValidationModule.ts"],"names":["m2","m3","m3.m4","m3.foo"],"mappings":"AAAA,IAAO,EAAE,CAGR;AAHD,WAAO,EAAE,EAAC,CAAC;IACPA,IAAIA,CAACA,GAAGA,EAAEA,CAACA;IACXA,CAACA,EAAEA,CAACA;AACRA,CAACA,EAHM,EAAE,KAAF,EAAE,QAGR;AACD,IAAO,EAAE,CAQR;AARD,WAAO,EAAE,EAAC,CAAC;IACPC,IAAOA,EAAEA,CAERA;IAFDA,WAAOA,EAAEA,EAACA,CAACA;QACIC,IAACA,GAAGA,EAAEA,CAACA;IACtBA,CAACA,EAFMD,EAAEA,KAAFA,EAAEA,QAERA;IAEDA;QACIE,MAAMA,CAACA,EAAEA,CAACA,CAACA,CAACA;IAChBA,CAACA;IAFeF,MAAGA,MAElBA,CAAAA;AACLA,CAACA,EARM,EAAE,KAAF,EAAE,QAQR"}
tests/baselines/reference/sourceMapValidationModule.js.map
0
https://github.com/microsoft/TypeScript/commit/0fe282e71994ac950e32b8040e714f563609a32f
[ 0.00016767543274909258, 0.00016767543274909258, 0.00016767543274909258, 0.00016767543274909258, 0 ]
{ "id": 2, "code_window": [ "\n", "// @allowNonTsExtensions: true\n", "// @Filename: a.js\n", "//// var v = <string>undefined;\n", "\n", "verify.getSemanticDiagnostics(`[\n", " {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "verify.getSyntacticDiagnostics(`[\n" ], "file_path": "tests/cases/fourslash/getJavaScriptSemanticDiagnostics20.ts", "type": "replace", "edit_start_line_idx": 6 }
=== tests/cases/conformance/es6/destructuring/emptyAssignmentPatterns01_ES5.ts === var a: any; >a : Symbol(a, Decl(emptyAssignmentPatterns01_ES5.ts, 1, 3)) ({} = a); >a : Symbol(a, Decl(emptyAssignmentPatterns01_ES5.ts, 1, 3)) ([] = a); >a : Symbol(a, Decl(emptyAssignmentPatterns01_ES5.ts, 1, 3))
tests/baselines/reference/emptyAssignmentPatterns01_ES5.symbols
0
https://github.com/microsoft/TypeScript/commit/0fe282e71994ac950e32b8040e714f563609a32f
[ 0.00018247809202875942, 0.00017250218661502004, 0.00016252628120128065, 0.00017250218661502004, 0.000009975905413739383 ]
{ "id": 3, "code_window": [ " {\n", " \"message\": \"'type assertion expressions' can only be used in a .ts file.\",\n", " \"start\": 9,\n", " \"length\": 6,\n", " \"category\": \"error\",\n" ], "labels": [ "keep", "replace", "replace", "replace", "keep" ], "after_edit": [ " \"message\": \"Expected corresponding JSX closing tag for 'string'.\",\n", " \"start\": 26,\n", " \"length\": 0,\n" ], "file_path": "tests/cases/fourslash/getJavaScriptSemanticDiagnostics20.ts", "type": "replace", "edit_start_line_idx": 8 }
/// <reference path="fourslash.ts" /> // @allowNonTsExtensions: true // @Filename: a.js //// var v = <string>undefined; verify.getSemanticDiagnostics(`[ { "message": "'type assertion expressions' can only be used in a .ts file.", "start": 9, "length": 6, "category": "error", "code": 8016 } ]`);
tests/cases/fourslash/getJavaScriptSemanticDiagnostics20.ts
1
https://github.com/microsoft/TypeScript/commit/0fe282e71994ac950e32b8040e714f563609a32f
[ 0.014604054391384125, 0.0074712298810482025, 0.0003384056326467544, 0.0074712298810482025, 0.007132824044674635 ]
{ "id": 3, "code_window": [ " {\n", " \"message\": \"'type assertion expressions' can only be used in a .ts file.\",\n", " \"start\": 9,\n", " \"length\": 6,\n", " \"category\": \"error\",\n" ], "labels": [ "keep", "replace", "replace", "replace", "keep" ], "after_edit": [ " \"message\": \"Expected corresponding JSX closing tag for 'string'.\",\n", " \"start\": 26,\n", " \"length\": 0,\n" ], "file_path": "tests/cases/fourslash/getJavaScriptSemanticDiagnostics20.ts", "type": "replace", "edit_start_line_idx": 8 }
tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserErrantEqualsGreaterThanAfterFunction1.ts(1,14): error TS1144: '{' or ';' expected. ==== tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserErrantEqualsGreaterThanAfterFunction1.ts (1 errors) ==== function f() => 4; ~~ !!! error TS1144: '{' or ';' expected.
tests/baselines/reference/parserErrantEqualsGreaterThanAfterFunction1.errors.txt
0
https://github.com/microsoft/TypeScript/commit/0fe282e71994ac950e32b8040e714f563609a32f
[ 0.00016802098252810538, 0.00016802098252810538, 0.00016802098252810538, 0.00016802098252810538, 0 ]
{ "id": 3, "code_window": [ " {\n", " \"message\": \"'type assertion expressions' can only be used in a .ts file.\",\n", " \"start\": 9,\n", " \"length\": 6,\n", " \"category\": \"error\",\n" ], "labels": [ "keep", "replace", "replace", "replace", "keep" ], "after_edit": [ " \"message\": \"Expected corresponding JSX closing tag for 'string'.\",\n", " \"start\": 26,\n", " \"length\": 0,\n" ], "file_path": "tests/cases/fourslash/getJavaScriptSemanticDiagnostics20.ts", "type": "replace", "edit_start_line_idx": 8 }
var m2_a1 = 10; var m2_c1 = (function () { function m2_c1() { } return m2_c1; })(); var m2_instance1 = new m2_c1(); function m2_f1() { return m2_instance1; } //# sourceMappingURL=m2.js.map
tests/baselines/reference/project/sourceRootRelativePathMultifolderNoOutdir/node/diskFile1.js
0
https://github.com/microsoft/TypeScript/commit/0fe282e71994ac950e32b8040e714f563609a32f
[ 0.0001731050288071856, 0.00017206877237185836, 0.00017103251593653113, 0.00017206877237185836, 0.0000010362564353272319 ]
{ "id": 3, "code_window": [ " {\n", " \"message\": \"'type assertion expressions' can only be used in a .ts file.\",\n", " \"start\": 9,\n", " \"length\": 6,\n", " \"category\": \"error\",\n" ], "labels": [ "keep", "replace", "replace", "replace", "keep" ], "after_edit": [ " \"message\": \"Expected corresponding JSX closing tag for 'string'.\",\n", " \"start\": 26,\n", " \"length\": 0,\n" ], "file_path": "tests/cases/fourslash/getJavaScriptSemanticDiagnostics20.ts", "type": "replace", "edit_start_line_idx": 8 }
define(["require", "exports"], function (require, exports) { var d = (function () { function d() { } return d; })(); exports.d = d; ; function foo() { return new d(); } exports.foo = foo; });
tests/baselines/reference/project/declarationsImportedInPrivate/amd/private_m4.js
0
https://github.com/microsoft/TypeScript/commit/0fe282e71994ac950e32b8040e714f563609a32f
[ 0.0001718233252177015, 0.0001705086324363947, 0.0001691939396550879, 0.0001705086324363947, 0.0000013146927813068032 ]
{ "id": 4, "code_window": [ " \"category\": \"error\",\n", " \"code\": 8016\n", " }\n" ], "labels": [ "keep", "replace", "keep" ], "after_edit": [ " \"code\": 17002\n" ], "file_path": "tests/cases/fourslash/getJavaScriptSemanticDiagnostics20.ts", "type": "replace", "edit_start_line_idx": 12 }
tests/cases/compiler/a.js(1,10): error TS8016: 'type assertion expressions' can only be used in a .ts file. ==== tests/cases/compiler/a.js (1 errors) ==== var v = <string>undefined; ~~~~~~ !!! error TS8016: 'type assertion expressions' can only be used in a .ts file.
tests/baselines/reference/jsFileCompilationTypeAssertions.errors.txt
1
https://github.com/microsoft/TypeScript/commit/0fe282e71994ac950e32b8040e714f563609a32f
[ 0.0002934550866484642, 0.0002934550866484642, 0.0002934550866484642, 0.0002934550866484642, 0 ]
{ "id": 4, "code_window": [ " \"category\": \"error\",\n", " \"code\": 8016\n", " }\n" ], "labels": [ "keep", "replace", "keep" ], "after_edit": [ " \"code\": 17002\n" ], "file_path": "tests/cases/fourslash/getJavaScriptSemanticDiagnostics20.ts", "type": "replace", "edit_start_line_idx": 12 }
//// [symbolType14.ts] new Symbol(); //// [symbolType14.js] new Symbol();
tests/baselines/reference/symbolType14.js
0
https://github.com/microsoft/TypeScript/commit/0fe282e71994ac950e32b8040e714f563609a32f
[ 0.00017432378081139177, 0.00017432378081139177, 0.00017432378081139177, 0.00017432378081139177, 0 ]
{ "id": 4, "code_window": [ " \"category\": \"error\",\n", " \"code\": 8016\n", " }\n" ], "labels": [ "keep", "replace", "keep" ], "after_edit": [ " \"code\": 17002\n" ], "file_path": "tests/cases/fourslash/getJavaScriptSemanticDiagnostics20.ts", "type": "replace", "edit_start_line_idx": 12 }
var m1_a1 = 10; var m1_c1 = (function () { function m1_c1() { } return m1_c1; })(); var m1_instance1 = new m1_c1(); function m1_f1() { return m1_instance1; } /// <reference path='ref/m1.ts'/> var a1 = 10; var c1 = (function () { function c1() { } return c1; })(); var instance1 = new c1(); function f1() { return instance1; } //# sourceMappingURL=test.js.map
tests/baselines/reference/project/sourcemapSubfolderSpecifyOutputFile/amd/bin/test.js
0
https://github.com/microsoft/TypeScript/commit/0fe282e71994ac950e32b8040e714f563609a32f
[ 0.0001735211262712255, 0.00017073571507353336, 0.00016869328101165593, 0.00016999278159346431, 0.000002039771288764314 ]
{ "id": 4, "code_window": [ " \"category\": \"error\",\n", " \"code\": 8016\n", " }\n" ], "labels": [ "keep", "replace", "keep" ], "after_edit": [ " \"code\": 17002\n" ], "file_path": "tests/cases/fourslash/getJavaScriptSemanticDiagnostics20.ts", "type": "replace", "edit_start_line_idx": 12 }
=== tests/cases/compiler/collisionCodeGenModuleWithModuleReopening.ts === module m1 { >m1 : Symbol(m1, Decl(collisionCodeGenModuleWithModuleReopening.ts, 0, 0), Decl(collisionCodeGenModuleWithModuleReopening.ts, 4, 22)) export class m1 { >m1 : Symbol(m1, Decl(collisionCodeGenModuleWithModuleReopening.ts, 0, 11)) } } var foo = new m1.m1(); >foo : Symbol(foo, Decl(collisionCodeGenModuleWithModuleReopening.ts, 4, 3)) >m1.m1 : Symbol(m1.m1, Decl(collisionCodeGenModuleWithModuleReopening.ts, 0, 11)) >m1 : Symbol(m1, Decl(collisionCodeGenModuleWithModuleReopening.ts, 0, 0), Decl(collisionCodeGenModuleWithModuleReopening.ts, 4, 22)) >m1 : Symbol(m1.m1, Decl(collisionCodeGenModuleWithModuleReopening.ts, 0, 11)) module m1 { >m1 : Symbol(m1, Decl(collisionCodeGenModuleWithModuleReopening.ts, 0, 0), Decl(collisionCodeGenModuleWithModuleReopening.ts, 4, 22)) export class c1 { >c1 : Symbol(c1, Decl(collisionCodeGenModuleWithModuleReopening.ts, 5, 11)) } var b = new c1(); >b : Symbol(b, Decl(collisionCodeGenModuleWithModuleReopening.ts, 8, 7)) >c1 : Symbol(c1, Decl(collisionCodeGenModuleWithModuleReopening.ts, 5, 11)) var c = new m1(); >c : Symbol(c, Decl(collisionCodeGenModuleWithModuleReopening.ts, 9, 7)) >m1 : Symbol(m1, Decl(collisionCodeGenModuleWithModuleReopening.ts, 0, 11)) } var foo2 = new m1.c1(); >foo2 : Symbol(foo2, Decl(collisionCodeGenModuleWithModuleReopening.ts, 11, 3), Decl(collisionCodeGenModuleWithModuleReopening.ts, 28, 3)) >m1.c1 : Symbol(m1.c1, Decl(collisionCodeGenModuleWithModuleReopening.ts, 5, 11)) >m1 : Symbol(m1, Decl(collisionCodeGenModuleWithModuleReopening.ts, 0, 0), Decl(collisionCodeGenModuleWithModuleReopening.ts, 4, 22)) >c1 : Symbol(m1.c1, Decl(collisionCodeGenModuleWithModuleReopening.ts, 5, 11)) module m2 { >m2 : Symbol(m2, Decl(collisionCodeGenModuleWithModuleReopening.ts, 11, 23), Decl(collisionCodeGenModuleWithModuleReopening.ts, 19, 23)) export class c1 { >c1 : Symbol(c1, Decl(collisionCodeGenModuleWithModuleReopening.ts, 13, 11)) } export var b10 = 10; >b10 : Symbol(b10, Decl(collisionCodeGenModuleWithModuleReopening.ts, 16, 14)) var x = new c1(); >x : Symbol(x, Decl(collisionCodeGenModuleWithModuleReopening.ts, 17, 7)) >c1 : Symbol(c1, Decl(collisionCodeGenModuleWithModuleReopening.ts, 13, 11)) } var foo3 = new m2.c1(); >foo3 : Symbol(foo3, Decl(collisionCodeGenModuleWithModuleReopening.ts, 19, 3), Decl(collisionCodeGenModuleWithModuleReopening.ts, 27, 3)) >m2.c1 : Symbol(m2.c1, Decl(collisionCodeGenModuleWithModuleReopening.ts, 13, 11)) >m2 : Symbol(m2, Decl(collisionCodeGenModuleWithModuleReopening.ts, 11, 23), Decl(collisionCodeGenModuleWithModuleReopening.ts, 19, 23)) >c1 : Symbol(m2.c1, Decl(collisionCodeGenModuleWithModuleReopening.ts, 13, 11)) module m2 { >m2 : Symbol(m2, Decl(collisionCodeGenModuleWithModuleReopening.ts, 11, 23), Decl(collisionCodeGenModuleWithModuleReopening.ts, 19, 23)) export class m2 { >m2 : Symbol(m2, Decl(collisionCodeGenModuleWithModuleReopening.ts, 20, 11)) } var b = new m2(); >b : Symbol(b, Decl(collisionCodeGenModuleWithModuleReopening.ts, 23, 7)) >m2 : Symbol(m2, Decl(collisionCodeGenModuleWithModuleReopening.ts, 20, 11)) var d = b10; >d : Symbol(d, Decl(collisionCodeGenModuleWithModuleReopening.ts, 24, 7)) >b10 : Symbol(b10, Decl(collisionCodeGenModuleWithModuleReopening.ts, 16, 14)) var c = new c1(); >c : Symbol(c, Decl(collisionCodeGenModuleWithModuleReopening.ts, 25, 7)) >c1 : Symbol(c1, Decl(collisionCodeGenModuleWithModuleReopening.ts, 13, 11)) } var foo3 = new m2.c1(); >foo3 : Symbol(foo3, Decl(collisionCodeGenModuleWithModuleReopening.ts, 19, 3), Decl(collisionCodeGenModuleWithModuleReopening.ts, 27, 3)) >m2.c1 : Symbol(m2.c1, Decl(collisionCodeGenModuleWithModuleReopening.ts, 13, 11)) >m2 : Symbol(m2, Decl(collisionCodeGenModuleWithModuleReopening.ts, 11, 23), Decl(collisionCodeGenModuleWithModuleReopening.ts, 19, 23)) >c1 : Symbol(m2.c1, Decl(collisionCodeGenModuleWithModuleReopening.ts, 13, 11)) var foo2 = new m2.m2(); >foo2 : Symbol(foo2, Decl(collisionCodeGenModuleWithModuleReopening.ts, 11, 3), Decl(collisionCodeGenModuleWithModuleReopening.ts, 28, 3)) >m2.m2 : Symbol(m2.m2, Decl(collisionCodeGenModuleWithModuleReopening.ts, 20, 11)) >m2 : Symbol(m2, Decl(collisionCodeGenModuleWithModuleReopening.ts, 11, 23), Decl(collisionCodeGenModuleWithModuleReopening.ts, 19, 23)) >m2 : Symbol(m2.m2, Decl(collisionCodeGenModuleWithModuleReopening.ts, 20, 11))
tests/baselines/reference/collisionCodeGenModuleWithModuleReopening.symbols
0
https://github.com/microsoft/TypeScript/commit/0fe282e71994ac950e32b8040e714f563609a32f
[ 0.0007125780102796853, 0.00027068014605902135, 0.00016460681217722595, 0.00017937533266376704, 0.00018441907013766468 ]
{ "id": 5, "code_window": [ " }\n", "]`);\n" ], "labels": [ "keep", "replace" ], "after_edit": [ "]`);\n", "verify.getSemanticDiagnostics(`[]`);\n" ], "file_path": "tests/cases/fourslash/getJavaScriptSemanticDiagnostics20.ts", "type": "replace", "edit_start_line_idx": 14 }
/// <reference path="fourslash.ts" /> // @allowNonTsExtensions: true // @Filename: a.js //// var v = <string>undefined; verify.getSemanticDiagnostics(`[ { "message": "'type assertion expressions' can only be used in a .ts file.", "start": 9, "length": 6, "category": "error", "code": 8016 } ]`);
tests/cases/fourslash/getJavaScriptSemanticDiagnostics20.ts
1
https://github.com/microsoft/TypeScript/commit/0fe282e71994ac950e32b8040e714f563609a32f
[ 0.10580991208553314, 0.05358557030558586, 0.001361230737529695, 0.05358557030558586, 0.05222433805465698 ]
{ "id": 5, "code_window": [ " }\n", "]`);\n" ], "labels": [ "keep", "replace" ], "after_edit": [ "]`);\n", "verify.getSemanticDiagnostics(`[]`);\n" ], "file_path": "tests/cases/fourslash/getJavaScriptSemanticDiagnostics20.ts", "type": "replace", "edit_start_line_idx": 14 }
class Clod { static x = 10; } module Clod { var p = x; // x isn't in scope here }
tests/cases/compiler/staticsNotInScopeInClodule.ts
0
https://github.com/microsoft/TypeScript/commit/0fe282e71994ac950e32b8040e714f563609a32f
[ 0.01144055649638176, 0.01144055649638176, 0.01144055649638176, 0.01144055649638176, 0 ]
{ "id": 5, "code_window": [ " }\n", "]`);\n" ], "labels": [ "keep", "replace" ], "after_edit": [ "]`);\n", "verify.getSemanticDiagnostics(`[]`);\n" ], "file_path": "tests/cases/fourslash/getJavaScriptSemanticDiagnostics20.ts", "type": "replace", "edit_start_line_idx": 14 }
=== tests/cases/conformance/es6/destructuring/objectBindingPatternKeywordIdentifiers06.ts === var { as: as } = { as: 1 } >as : Symbol(as, Decl(objectBindingPatternKeywordIdentifiers06.ts, 1, 18)) >as : Symbol(as, Decl(objectBindingPatternKeywordIdentifiers06.ts, 1, 5)) >as : Symbol(as, Decl(objectBindingPatternKeywordIdentifiers06.ts, 1, 18))
tests/baselines/reference/objectBindingPatternKeywordIdentifiers06.symbols
0
https://github.com/microsoft/TypeScript/commit/0fe282e71994ac950e32b8040e714f563609a32f
[ 0.00020944008429069072, 0.00020944008429069072, 0.00020944008429069072, 0.00020944008429069072, 0 ]
{ "id": 5, "code_window": [ " }\n", "]`);\n" ], "labels": [ "keep", "replace" ], "after_edit": [ "]`);\n", "verify.getSemanticDiagnostics(`[]`);\n" ], "file_path": "tests/cases/fourslash/getJavaScriptSemanticDiagnostics20.ts", "type": "replace", "edit_start_line_idx": 14 }
tests/cases/conformance/internalModules/DeclarationMerging/module.ts(2,19): error TS2433: A namespace declaration cannot be in a different file from a class or function with which it is merged tests/cases/conformance/internalModules/DeclarationMerging/simple.ts(1,8): error TS2434: A namespace declaration cannot be located prior to a class or function with which it is merged ==== tests/cases/conformance/internalModules/DeclarationMerging/module.ts (1 errors) ==== module X.Y { export module Point { ~~~~~ !!! error TS2433: A namespace declaration cannot be in a different file from a class or function with which it is merged export var Origin = new Point(0, 0); } } ==== tests/cases/conformance/internalModules/DeclarationMerging/classPoint.ts (0 errors) ==== module X.Y { // duplicate identifier export class Point { constructor(x: number, y: number) { this.x = x; this.y = y; } x: number; y: number; } } ==== tests/cases/conformance/internalModules/DeclarationMerging/simple.ts (1 errors) ==== module A { ~ !!! error TS2434: A namespace declaration cannot be located prior to a class or function with which it is merged export var Instance = new A(); } // duplicate identifier class A { id: string; }
tests/baselines/reference/ModuleAndClassWithSameNameAndCommonRoot.errors.txt
0
https://github.com/microsoft/TypeScript/commit/0fe282e71994ac950e32b8040e714f563609a32f
[ 0.0002306487294845283, 0.00019413181871641427, 0.00017725904763210565, 0.00018430975615046918, 0.00002137755109288264 ]
{ "id": 0, "code_window": [ "\n", "<p class=\"description\">Every Base UI component available so far.</p>\n", "\n", "{{\"component\": \"docs/src/modules/components/BaseUIComponents.js\"}}\n" ], "labels": [ "keep", "keep", "keep", "replace" ], "after_edit": [ "{{\"component\": \"modules/components/BaseUIComponents.js\"}}" ], "file_path": "docs/data/base/all-components/all-components.md", "type": "replace", "edit_start_line_idx": 4 }
# Showcase <p class="description">Check out these public apps using Material UI to get inspired for your next project.</p> This is a curated list of some of the best apps we've seen that show off what's possible with Material UI. Are you also using it? [Show us what you're building](https://github.com/mui/material-ui/issues/22426)! We'd love to see it. --- {{"component": "docs/src/modules/components/MaterialShowcase.js"}}
docs/data/material/discover-more/showcase/showcase.md
1
https://github.com/mui/material-ui/commit/e41667669bd16fb8736eb26aa4114ec220aac5c3
[ 0.0004630482872016728, 0.0004630482872016728, 0.0004630482872016728, 0.0004630482872016728, 0 ]
{ "id": 0, "code_window": [ "\n", "<p class=\"description\">Every Base UI component available so far.</p>\n", "\n", "{{\"component\": \"docs/src/modules/components/BaseUIComponents.js\"}}\n" ], "labels": [ "keep", "keep", "keep", "replace" ], "after_edit": [ "{{\"component\": \"modules/components/BaseUIComponents.js\"}}" ], "file_path": "docs/data/base/all-components/all-components.md", "type": "replace", "edit_start_line_idx": 4 }
import * as React from 'react'; import { styled } from '@mui/material/styles'; const Container = styled('div')({ display: 'flex', flexWrap: 'wrap', gap: 2 }); const Item = styled('div')(({ theme }) => ({ width: '100%', [theme.breakpoints.up('sm')]: { width: '50%', }, [theme.breakpoints.up('md')]: { width: 'calc(100% / 4)', }, })); export default function GridSimple() { return ( <Container> {new Array(1000).fill().map(() => ( <Item>test case</Item> ))} </Container> ); }
benchmark/browser/scenarios/grid-simple/index.js
0
https://github.com/mui/material-ui/commit/e41667669bd16fb8736eb26aa4114ec220aac5c3
[ 0.00016786564083304256, 0.0001670629862928763, 0.00016662607959005982, 0.000166697267559357, 5.682991854882857e-7 ]
{ "id": 0, "code_window": [ "\n", "<p class=\"description\">Every Base UI component available so far.</p>\n", "\n", "{{\"component\": \"docs/src/modules/components/BaseUIComponents.js\"}}\n" ], "labels": [ "keep", "keep", "keep", "replace" ], "after_edit": [ "{{\"component\": \"modules/components/BaseUIComponents.js\"}}" ], "file_path": "docs/data/base/all-components/all-components.md", "type": "replace", "edit_start_line_idx": 4 }
<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 0 24 24" width="24"><path d="M0 0h24v24H0V0z" fill="none"/><path d="M18.99 5H5l7 3.5zm.01 8.05V7l-7 3.5L5 7v8h10.35c.56-1.18 1.76-2 3.15-2 .17 0 .34.03.5.05z" opacity=".3"/><path d="M20.99 14.04V5c0-1.1-.9-2-2-2H5c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2h10.05c.28 1.92 2.1 3.35 4.18 2.93 1.34-.27 2.43-1.37 2.7-2.71.25-1.24-.16-2.39-.94-3.18zm-2-9.04L12 8.5 5 5h13.99zm-3.64 10H5V7l7 3.5L19 7v6.05c-.16-.02-.33-.05-.5-.05-1.39 0-2.59.82-3.15 2zm5.15 2h-4v-1h4v1z"/></svg>
packages/mui-icons-material/material-icons/unsubscribe_two_tone_24px.svg
0
https://github.com/mui/material-ui/commit/e41667669bd16fb8736eb26aa4114ec220aac5c3
[ 0.0001660688576521352, 0.0001660688576521352, 0.0001660688576521352, 0.0001660688576521352, 0 ]
{ "id": 0, "code_window": [ "\n", "<p class=\"description\">Every Base UI component available so far.</p>\n", "\n", "{{\"component\": \"docs/src/modules/components/BaseUIComponents.js\"}}\n" ], "labels": [ "keep", "keep", "keep", "replace" ], "after_edit": [ "{{\"component\": \"modules/components/BaseUIComponents.js\"}}" ], "file_path": "docs/data/base/all-components/all-components.md", "type": "replace", "edit_start_line_idx": 4 }
"use client"; import createSvgIcon from './utils/createSvgIcon'; import { jsx as _jsx } from "react/jsx-runtime"; export default createSvgIcon( /*#__PURE__*/_jsx("path", { d: "M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zm-1-4h2v2h-2zm1.61-9.96c-2.06-.3-3.88.97-4.43 2.79-.18.58.26 1.17.87 1.17h.2c.41 0 .74-.29.88-.67.32-.89 1.27-1.5 2.3-1.28.95.2 1.65 1.13 1.57 2.1-.1 1.34-1.62 1.63-2.45 2.88 0 .01-.01.01-.01.02-.01.02-.02.03-.03.05-.09.15-.18.32-.25.5-.01.03-.03.05-.04.08-.01.02-.01.04-.02.07-.12.34-.2.75-.2 1.25h2c0-.42.11-.77.28-1.07.02-.03.03-.06.05-.09.08-.14.18-.27.28-.39.01-.01.02-.03.03-.04.1-.12.21-.23.33-.34.96-.91 2.26-1.65 1.99-3.56-.24-1.74-1.61-3.21-3.35-3.47z" }), 'HelpOutlineRounded');
packages/mui-icons-material/lib/esm/HelpOutlineRounded.js
0
https://github.com/mui/material-ui/commit/e41667669bd16fb8736eb26aa4114ec220aac5c3
[ 0.00020961349946446717, 0.00020961349946446717, 0.00020961349946446717, 0.00020961349946446717, 0 ]
{ "id": 1, "code_window": [ "This is a curated list of some of the best apps we've seen that show off what's possible with Material UI. Are you also using it? [Show us what you're building](https://github.com/mui/material-ui/issues/22426)! We'd love to see it.\n", "\n", "---\n", "\n", "{{\"component\": \"docs/src/modules/components/MaterialShowcase.js\"}}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace" ], "after_edit": [ "{{\"component\": \"modules/components/MaterialShowcase.js\"}}" ], "file_path": "docs/data/material/discover-more/showcase/showcase.md", "type": "replace", "edit_start_line_idx": 8 }
--- productId: material-ui title: 9+ Free React Templates --- # React Templates <p class="description">Browse our collection of free React templates to get started building your app with Material UI, including a React dashboard, React admin panel, and more.</p> <!-- #default-branch-switch --> Our curated collection of Material UI templates includes dashboards, sign-in and sign-up pages, a blog, a checkout flow, and more. The templates can be combined with one of the [example projects](https://github.com/mui/material-ui/tree/master/examples) to form a complete starter. Sections of each layout are clearly defined either by comments or use of separate files, making it simple to extract parts of a page (such as a "hero unit", or footer, for example) for reuse in other pages. For multi-part examples, a table in the README at the linked source code location describes the purpose of each file. {{"component": "docs/src/modules/components/MaterialFreeTemplatesCollection.js"}} See any room for improvement? Please feel free to open an [issue](https://github.com/mui/material-ui/issues/new/choose) or [pull request](https://github.com/mui/material-ui/pulls) on GitHub. ## Premium templates Looking for something more? You can find complete templates and themes in the <a href="https://mui.com/store/?utm_source=docs&utm_medium=referral&utm_campaign=templates-store">premium template section</a>. <a href="https://mui.com/store/?utm_source=docs&utm_medium=referral&utm_campaign=templates-store"><img src="/static/images/themes-light.jpg" alt="react templates" width="2278" height="1358" /></a>
docs/data/material/getting-started/templates/templates.md
1
https://github.com/mui/material-ui/commit/e41667669bd16fb8736eb26aa4114ec220aac5c3
[ 0.0007159757660701871, 0.00035698365536518395, 0.00016552644956391305, 0.00027321622474119067, 0.00021201510389801115 ]
{ "id": 1, "code_window": [ "This is a curated list of some of the best apps we've seen that show off what's possible with Material UI. Are you also using it? [Show us what you're building](https://github.com/mui/material-ui/issues/22426)! We'd love to see it.\n", "\n", "---\n", "\n", "{{\"component\": \"docs/src/modules/components/MaterialShowcase.js\"}}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace" ], "after_edit": [ "{{\"component\": \"modules/components/MaterialShowcase.js\"}}" ], "file_path": "docs/data/material/discover-more/showcase/showcase.md", "type": "replace", "edit_start_line_idx": 8 }
# Understanding MUI packages <p class="description">An overview of MUI's packages and the relationships between them.</p> ## Overview - If you want to build a design system based on Material Design, use `@mui/material`. - If you want to build with components that give you complete control over your app's CSS, use `@mui/base`. - For CSS utilities to help in laying out custom designs with Material UI or Base UI, use `@mui/system`. ### Glossary - **install** refers to running `yarn add $module` or `npm install $module`. - **import** refers to making a module API available in your code by adding `import ... from '$module'`. ## MUI packages The following is an up-to-date list of `@mui` public packages. - `@mui/material` - `@mui/base` - `@mui/system` - `@mui/styled-engine` - `@mui/styled-engine-sc` - `@mui/styles` ### Understanding MUI's products As a company, MUI maintains a suite of open-source and open-core React UI projects. These projects live within two product lines: MUI Core and MUI X. The following chart illustrates how MUI's packages are related to one another: <img src="/static/images/packages/mui-packages.png" style="width: 600px; margin-top: 4px; margin-bottom: 8px;" alt="The first half of the image shows @mui/material and @mui/base as component libraries, and @mui/system and styled engines as styling solutions, both under the MUI Core umbrella. The second half shows @mui/x-data-grid and @mui/x-date-pickers as components from MUI X." width="1200" height="600" /> In this article, we'll only cover the MUI Core packages. Visit the [MUI X Overview](/x/introduction/) for more information about our collection of advanced components. ## Component libraries ### Material UI Material UI is a comprehensive library of components that features our implementation of Google's Material Design. `@mui/system` is included as dependency, meaning you don't need to install or import it separately—you can import its components and functions directly from `@mui/material`. ### Base UI [Base UI](/base-ui/getting-started/) is our library of "unstyled" components and hooks. With Base, you gain complete control over your app's CSS and accessibility features. The Base package includes prebuilt components with production-ready functionality, along with low-level hooks for transferring that functionality to other components. ### Using them together Imagine you're working on an application that uses `@mui/material` with a custom theme, and you need to develop a new switch component that looks very different from the one found in Material Design. In this case, instead of overriding all the styles on the Material UI `Switch` component, you can use the `styled` API to customize the Base `SwitchUnstyled` component from scratch: ```js import { styled } from '@mui/material/styles'; import { SwitchUnstyled, switchUnstyledClasses } from '@mui/base/SwitchUnstyled'; const Root = styled('span')(` position: relative; display: inline-block; width: 32px; height: 20px; & .${switchUnstyledClasses.track} { // ...css } & .${switchUnstyledClasses.thumb} { // ...css } `); export default function CustomSwitch() { const label = { slotProps: { input: { 'aria-label': 'Demo switch' } } }; return <SwitchUnstyled component={Root} {...label} />; } ``` ## Styling ### Styled engines Material UI relies on styling engines to inject CSS into your app. These engines come in two packages: - `@mui/styled-engine` - `@mui/styled-engine-sc` By default, Material UI uses [Emotion](https://emotion.sh/docs/styled) as its styling engine—it's included in the [installation](/material-ui/getting-started/installation/) process. If you plan to stick with Emotion, then `@mui/styled-engine` is a dependency in your app, and you don't need to install it separately. If you prefer to use [styled-components](https://styled-components.com/docs/basics#getting-started), then you need to install `@mui/styled-engine-sc` in place of the Emotion packages. See the [Styled engine guide](/material-ui/guides/styled-engine/) for more details. In either case, you won't interact much with either of these packages beyond installation—they're used internally in `@mui/system`. :::warning Prior to v5, Material UI used `@mui/styles` as a JSS wrapper. This package is now deprecated and will be removed in the future. Check out [the guide to migrating from v4 to v5](/material-ui/migration/migration-v4/) to learn how to upgrade to a newer solution. ::: ### MUI System MUI System is a collection of CSS utilities to help you rapidly lay out custom designs. It uses the Emotion adapter (`@mui/styled-engine`) as the default style engine to create the CSS utilities. #### Advantages of MUI System - You have full control of the `theme` object. - You can use `sx` prop normally as the `styled` API supports it by default. - You can have themeable components by using `styled` via slots and variants. :::warning To use MUI System, you must install either Emotion or styled-components, because the respective `styled-engine` package depends on it. ::: <img src="/static/images/packages/mui-system.png" style="width: 600px; margin-top: 4px; margin-bottom: 8px;" alt="A diagram showing an arrow going from @mui/system to @mui/styled-engine, with a note that it is the default engine. Then, from @mui/styled-engine a solid arrow points to @emotion/react and @emotion/styled while a dashed arrow points to @mui/styled-engine-sc, which points to styled-components." width="1200" height="600" />
docs/data/material/guides/understand-mui-packages/understand-mui-packages.md
0
https://github.com/mui/material-ui/commit/e41667669bd16fb8736eb26aa4114ec220aac5c3
[ 0.00037181301740929484, 0.00020094656792934984, 0.00016131444135680795, 0.00017525008297525346, 0.00005534287993214093 ]
{ "id": 1, "code_window": [ "This is a curated list of some of the best apps we've seen that show off what's possible with Material UI. Are you also using it? [Show us what you're building](https://github.com/mui/material-ui/issues/22426)! We'd love to see it.\n", "\n", "---\n", "\n", "{{\"component\": \"docs/src/modules/components/MaterialShowcase.js\"}}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace" ], "after_edit": [ "{{\"component\": \"modules/components/MaterialShowcase.js\"}}" ], "file_path": "docs/data/material/discover-more/showcase/showcase.md", "type": "replace", "edit_start_line_idx": 8 }
"use strict"; "use client"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon")); var _jsxRuntime = require("react/jsx-runtime"); var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M20 19V5c0-1.1-.9-2-2-2H6c-1.1 0-2 .9-2 2v14H3c-.55 0-1 .45-1 1s.45 1 1 1h18c.55 0 1-.45 1-1s-.45-1-1-1h-1zM13 5h1.5v14H13V5zm-2 14H9.5V5H11v14zM6 5h1.5v14H6V5zm10.5 14V5H18v14h-1.5z" }), 'VerticalShadesClosedRounded'); exports.default = _default;
packages/mui-icons-material/lib/VerticalShadesClosedRounded.js
0
https://github.com/mui/material-ui/commit/e41667669bd16fb8736eb26aa4114ec220aac5c3
[ 0.00017303209460806102, 0.00017030644812621176, 0.00016758081619627774, 0.00017030644812621176, 0.000002725639205891639 ]
{ "id": 1, "code_window": [ "This is a curated list of some of the best apps we've seen that show off what's possible with Material UI. Are you also using it? [Show us what you're building](https://github.com/mui/material-ui/issues/22426)! We'd love to see it.\n", "\n", "---\n", "\n", "{{\"component\": \"docs/src/modules/components/MaterialShowcase.js\"}}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace" ], "after_edit": [ "{{\"component\": \"modules/components/MaterialShowcase.js\"}}" ], "file_path": "docs/data/material/discover-more/showcase/showcase.md", "type": "replace", "edit_start_line_idx": 8 }
import MenuItem from '@material-ui/core/MenuItem'; import Tab from '@material-ui/core/Tab'; import { green as greenColor, red, yellow } from '@material-ui/core/colors'; import MuiTabs from '@material-ui/core/Tabs'; import TableContext from '@material-ui/core/Table/TableContext'; import SwitchBase from '@material-ui/core/internal/SwitchBase'; import Ripple from '@material-ui/core/ButtonBase/Ripple'; import { useTheme, createTheme } from '@material-ui/core/styles';
packages/mui-codemod/src/v5.0.0/optimal-imports.test/expected.js
0
https://github.com/mui/material-ui/commit/e41667669bd16fb8736eb26aa4114ec220aac5c3
[ 0.00016859920287970454, 0.00016859920287970454, 0.00016859920287970454, 0.00016859920287970454, 0 ]
{ "id": 2, "code_window": [ "We recommend Next.js for a comprehensive solution, or Vite if you're looking for a leaner development experience.\n", "See [Start a New React Project](https://react.dev/learn/start-a-new-react-project) from the official React docs to learn more about the options available.\n", "\n", "<!-- #default-branch-switch -->\n", "\n", "{{\"component\": \"docs/src/modules/components/ExampleCollection.js\"}}\n", "\n", "<br />\n", "\n", "## Official themes and templates\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "{{\"component\": \"modules/components/ExampleCollection.js\"}}\n" ], "file_path": "docs/data/material/getting-started/example-projects/example-projects.md", "type": "replace", "edit_start_line_idx": 15 }
import * as React from 'react'; import Box from '@mui/material/Box'; import Grid from '@mui/material/Unstable_Grid2'; import Card from '@mui/material/Card'; import Avatar from '@mui/material/Avatar'; import Typography from '@mui/material/Typography'; import Link from '@mui/material/Link'; import ChevronRightRoundedIcon from '@mui/icons-material/ChevronRightRounded'; import FilterDramaIcon from '@mui/icons-material/FilterDrama'; const examples = [ { name: 'Next.js App Router', label: 'View JS example', tsLabel: 'View TS example', link: 'https://github.com/mui/material-ui/tree/master/examples/material-ui-nextjs', tsLink: 'https://github.com/mui/material-ui/tree/master/examples/material-ui-nextjs-ts', src: '/static/images/examples/next.svg', }, { name: 'Vite.js', label: 'View JS example', tsLabel: 'View TS example', link: 'https://github.com/mui/material-ui/tree/master/examples/material-ui-vite', tsLink: 'https://github.com/mui/material-ui/tree/master/examples/material-ui-vite-ts', src: '/static/images/examples/vite.svg', }, { name: 'Next.js Pages Router', label: 'View JS example', tsLabel: 'View TS example', link: 'https://github.com/mui/material-ui/tree/master/examples/material-ui-nextjs-pages-router', tsLink: 'https://github.com/mui/material-ui/tree/master/examples/material-ui-nextjs-pages-router-ts', src: '/static/images/examples/next.svg', }, { name: 'Remix', label: 'View TS example', link: 'https://github.com/mui/material-ui/tree/master/examples/material-ui-remix-ts', src: '/static/images/examples/remix.svg', }, { name: 'Tailwind CSS + CRA', label: 'View TS example', link: 'https://github.com/mui/material-ui/tree/master/examples/material-ui-cra-tailwind-ts', src: '/static/images/examples/tailwindcss.svg', }, { name: 'Create React App', label: 'View JS example', tsLabel: 'View TS example', link: 'https://github.com/mui/material-ui/tree/master/examples/material-ui-cra', tsLink: 'https://github.com/mui/material-ui/tree/master/examples/material-ui-cra-ts', src: '/static/images/examples/cra.svg', }, { name: 'styled-components', label: 'View JS example', tsLabel: 'View TS example', link: 'https://github.com/mui/material-ui/tree/master/examples/material-ui-cra-styled-components', tsLink: 'https://github.com/mui/material-ui/tree/master/examples/material-ui-cra-styled-components-ts', src: '/static/images/examples/styled.png', }, { name: 'Gatsby', label: 'View JS example', link: 'https://github.com/mui/material-ui/tree/master/examples/material-ui-gatsby', src: '/static/images/examples/gatsby.svg', }, { name: 'Preact', label: 'View JS example', link: 'https://github.com/mui/material-ui/tree/master/examples/material-ui-preact', src: '/static/images/examples/preact.svg', }, { name: 'CDN', label: 'View JS example', link: 'https://github.com/mui/material-ui/tree/master/examples/material-ui-via-cdn', src: <FilterDramaIcon />, }, { name: 'Express.js (server-rendered)', label: 'View JS example', link: 'https://github.com/mui/material-ui/tree/master/examples/material-ui-express-ssr', src: '/static/images/examples/express.png', }, ]; export default function ExampleCollection() { return ( <Grid container spacing={2}> {examples.map((example) => ( <Grid key={example.name} xs={12} sm={6}> <Card sx={[ { p: 2, height: '100%', display: 'flex', alignItems: 'center', gap: 2, bgcolor: '#fff', backgroundImage: 'none', borderRadius: 1, border: '1px solid', borderColor: 'divider', boxShadow: 'none', }, (theme) => theme.applyDarkStyles({ bgcolor: 'transparent', borderColor: 'divider', }), ]} > <Avatar imgProps={{ width: '40', height: '40', loading: 'lazy', }} {...(typeof example.src === 'string' ? { src: example.src } : { children: example.src })} alt={example.name} /> <div> <Typography variant="body" fontWeight="semiBold"> {example.name} </Typography> <Box sx={{ display: 'flex', flexWrap: 'wrap', alignItems: 'baseline', }} data-ga-event-category="material-ui-example" data-ga-event-label={example.name} data-ga-event-action="click" > <Link href={example.link} variant="body2" sx={{ fontWeight: 500, display: 'flex', alignItems: 'center', mt: 0.5, }} > {example.label} <ChevronRightRoundedIcon fontSize="small" /> </Link> {!!example.tsLink && ( <React.Fragment> <Typography variant="caption" sx={{ display: { xs: 'none', sm: 'block' }, opacity: 0.2, mr: 0.75, }} > / </Typography> <Link href={example.tsLink} variant="body2" sx={{ fontWeight: 500, display: 'flex', alignItems: 'center', }} > {example.tsLabel} <ChevronRightRoundedIcon fontSize="small" /> </Link> </React.Fragment> )} </Box> </div> </Card> </Grid> ))} </Grid> ); }
docs/src/modules/components/ExampleCollection.js
1
https://github.com/mui/material-ui/commit/e41667669bd16fb8736eb26aa4114ec220aac5c3
[ 0.0015446911565959454, 0.00024226855020970106, 0.0001662933937041089, 0.00017382616351824254, 0.0002988617343362421 ]
{ "id": 2, "code_window": [ "We recommend Next.js for a comprehensive solution, or Vite if you're looking for a leaner development experience.\n", "See [Start a New React Project](https://react.dev/learn/start-a-new-react-project) from the official React docs to learn more about the options available.\n", "\n", "<!-- #default-branch-switch -->\n", "\n", "{{\"component\": \"docs/src/modules/components/ExampleCollection.js\"}}\n", "\n", "<br />\n", "\n", "## Official themes and templates\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "{{\"component\": \"modules/components/ExampleCollection.js\"}}\n" ], "file_path": "docs/data/material/getting-started/example-projects/example-projects.md", "type": "replace", "edit_start_line_idx": 15 }
<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 0 24 24" width="24"><path d="M0 0h24v24H0V0z" fill="none"/><path d="M13.89 8.7L12 10.59 10.11 8.7c-.39-.39-1.02-.39-1.41 0-.39.39-.39 1.02 0 1.41L10.59 12 8.7 13.89c-.39.39-.39 1.02 0 1.41.39.39 1.02.39 1.41 0L12 13.41l1.89 1.89c.39.39 1.02.39 1.41 0 .39-.39.39-1.02 0-1.41L13.41 12l1.89-1.89c.39-.39.39-1.02 0-1.41-.39-.38-1.03-.38-1.41 0zM12 2C6.47 2 2 6.47 2 12s4.47 10 10 10 10-4.47 10-10S17.53 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z"/></svg>
packages/mui-icons-material/material-icons/highlight_off_rounded_24px.svg
0
https://github.com/mui/material-ui/commit/e41667669bd16fb8736eb26aa4114ec220aac5c3
[ 0.00016974625759758055, 0.00016974625759758055, 0.00016974625759758055, 0.00016974625759758055, 0 ]
{ "id": 2, "code_window": [ "We recommend Next.js for a comprehensive solution, or Vite if you're looking for a leaner development experience.\n", "See [Start a New React Project](https://react.dev/learn/start-a-new-react-project) from the official React docs to learn more about the options available.\n", "\n", "<!-- #default-branch-switch -->\n", "\n", "{{\"component\": \"docs/src/modules/components/ExampleCollection.js\"}}\n", "\n", "<br />\n", "\n", "## Official themes and templates\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "{{\"component\": \"modules/components/ExampleCollection.js\"}}\n" ], "file_path": "docs/data/material/getting-started/example-projects/example-projects.md", "type": "replace", "edit_start_line_idx": 15 }
<svg xmlns="http://www.w3.org/2000/svg" enable-background="new 0 0 24 24" height="24" viewBox="0 0 24 24" width="24"><rect fill="none" height="24" width="24"/><path d="M3,19v-6h18v6H3z M3,5v6h18V5H3z"/></svg>
packages/mui-icons-material/material-icons/view_stream_sharp_24px.svg
0
https://github.com/mui/material-ui/commit/e41667669bd16fb8736eb26aa4114ec220aac5c3
[ 0.00017446678248234093, 0.00017446678248234093, 0.00017446678248234093, 0.00017446678248234093, 0 ]
{ "id": 2, "code_window": [ "We recommend Next.js for a comprehensive solution, or Vite if you're looking for a leaner development experience.\n", "See [Start a New React Project](https://react.dev/learn/start-a-new-react-project) from the official React docs to learn more about the options available.\n", "\n", "<!-- #default-branch-switch -->\n", "\n", "{{\"component\": \"docs/src/modules/components/ExampleCollection.js\"}}\n", "\n", "<br />\n", "\n", "## Official themes and templates\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "{{\"component\": \"modules/components/ExampleCollection.js\"}}\n" ], "file_path": "docs/data/material/getting-started/example-projects/example-projects.md", "type": "replace", "edit_start_line_idx": 15 }
"use strict"; "use client"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon")); var _jsxRuntime = require("react/jsx-runtime"); var _default = (0, _createSvgIcon.default)([/*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M13.94 8.31C13.62 7.52 12.85 7 12 7s-1.62.52-1.94 1.31L7 16h3.5v6h3v-6H17l-3.06-7.69z" }, "0"), /*#__PURE__*/(0, _jsxRuntime.jsx)("circle", { cx: "12", cy: "4", r: "2" }, "1")], 'Woman2'); exports.default = _default;
packages/mui-icons-material/lib/Woman2.js
0
https://github.com/mui/material-ui/commit/e41667669bd16fb8736eb26aa4114ec220aac5c3
[ 0.00016738710110075772, 0.00016560658696107566, 0.00016382608737330884, 0.00016560658696107566, 0.0000017805068637244403 ]
{ "id": 3, "code_window": [ "making it simple to extract parts of a page (such as a \"hero unit\", or footer, for example)\n", "for reuse in other pages.\n", "For multi-part examples, a table in the README at the linked source code location describes\n", "the purpose of each file.\n", "\n", "{{\"component\": \"docs/src/modules/components/MaterialFreeTemplatesCollection.js\"}}\n", "\n", "See any room for improvement?\n", "Please feel free to open an [issue](https://github.com/mui/material-ui/issues/new/choose) or [pull request](https://github.com/mui/material-ui/pulls) on GitHub.\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "{{\"component\": \"modules/components/MaterialFreeTemplatesCollection.js\"}}\n" ], "file_path": "docs/data/material/getting-started/templates/templates.md", "type": "replace", "edit_start_line_idx": 21 }
const { promises: fs, readdirSync } = require('fs'); const path = require('path'); const { prepareMarkdown } = require('./parseMarkdown'); const extractImports = require('./extractImports'); const notEnglishMarkdownRegExp = /-([a-z]{2})\.md$/; /** * @param {string} string */ function upperCaseFirst(string) { return `${string[0].toUpperCase()}${string.slice(1)}`; } /** * @param {string} moduleID * @example moduleIDToJSIdentifier('./Box.js') === '$$IndexJs' * @example moduleIDToJSIdentifier('./Box-new.js') === '$$BoxNewJs' * @example moduleIDToJSIdentifier('../Box-new.js') === '$$$BoxNewJs' */ function moduleIDToJSIdentifier(moduleID) { const delimiter = /(\.|-|\/|:)/; return moduleID .split(delimiter) .filter((part) => !delimiter.test(part)) .map((part) => (part.length === 0 ? '$' : part)) .map(upperCaseFirst) .join(''); } const componentPackageMapping = { 'material-ui': {}, 'base-ui': {}, 'joy-ui': {}, }; const packages = [ { productId: 'material-ui', paths: [ path.join(__dirname, '../../packages/mui-base/src'), path.join(__dirname, '../../packages/mui-lab/src'), path.join(__dirname, '../../packages/mui-material/src'), ], }, { productId: 'base-ui', paths: [path.join(__dirname, '../../packages/mui-base/src')], }, { productId: 'joy-ui', paths: [path.join(__dirname, '../../packages/mui-joy/src')], }, ]; packages.forEach((pkg) => { pkg.paths.forEach((pkgPath) => { const match = pkgPath.match(/packages(?:\\|\/)([^/\\]+)(?:\\|\/)src/); const packageName = match ? match[1] : null; if (!packageName) { throw new Error(`cannot find package name from path: ${pkgPath}`); } const filePaths = readdirSync(pkgPath); filePaths.forEach((folder) => { if (folder.match(/^[A-Z]/)) { if (!componentPackageMapping[pkg.productId]) { throw new Error(`componentPackageMapping must have "${pkg.productId}" as a key`); } // filename starts with Uppercase = component componentPackageMapping[pkg.productId][folder] = packageName; } }); }); }); /** * @type {import('webpack').loader.Loader} */ module.exports = async function demoLoader() { const englishFilepath = this.resourcePath; const options = this.getOptions(); const englishFilename = path.basename(englishFilepath, '.md'); const files = await fs.readdir(path.dirname(englishFilepath)); const translations = await Promise.all( files .map((filename) => { if (filename === `${englishFilename}.md`) { return { filename, userLanguage: 'en', }; } const matchNotEnglishMarkdown = filename.match(notEnglishMarkdownRegExp); if ( filename.startsWith(englishFilename) && matchNotEnglishMarkdown !== null && options.languagesInProgress.indexOf(matchNotEnglishMarkdown[1]) !== -1 ) { return { filename, userLanguage: matchNotEnglishMarkdown[1], }; } return null; }) .filter((translation) => translation) .map(async (translation) => { const filepath = path.join(path.dirname(englishFilepath), translation.filename); this.addDependency(filepath); const markdown = await fs.readFile(filepath, { encoding: 'utf8' }); return { ...translation, markdown, }; }), ); // Use .. as the docs runs from the /docs folder const repositoryRoot = path.join(this.rootContext, '..'); const fileRelativeContext = path .relative(repositoryRoot, this.context) // win32 to posix .replace(/\\/g, '/'); const { docs } = prepareMarkdown({ fileRelativeContext, translations, componentPackageMapping, options, }); const demos = {}; const importedModuleIDs = new Set(); const components = {}; const demoModuleIDs = new Set(); const componentModuleIDs = new Set(); const demoNames = Array.from( new Set( docs.en.rendered .filter((markdownOrComponentConfig) => { return typeof markdownOrComponentConfig !== 'string' && markdownOrComponentConfig.demo; }) .map((demoConfig) => { return demoConfig.demo; }), ), ); await Promise.all( demoNames.map(async (demoName) => { const multipleDemoVersionsUsed = !demoName.endsWith('.js'); // TODO: const moduleID = demoName; // The import paths currently use a completely different format. // They should just use relative imports. let moduleID = `./${demoName.replace( `pages/${fileRelativeContext.replace(/^docs\/src\/pages\//, '')}/`, '', )}`; if (multipleDemoVersionsUsed) { moduleID = `${moduleID}/system/index.js`; } const moduleFilepath = path.join( path.dirname(this.resourcePath), moduleID.replace(/\//g, path.sep), ); this.addDependency(moduleFilepath); demos[demoName] = { module: moduleID, raw: await fs.readFile(moduleFilepath, { encoding: 'utf8' }), }; demoModuleIDs.add(moduleID); extractImports(demos[demoName].raw).forEach((importModuleID) => importedModuleIDs.add(importModuleID), ); if (multipleDemoVersionsUsed) { // Add Tailwind demo data const tailwindModuleID = moduleID.replace('/system/index.js', '/tailwind/index.js'); try { // Add JS demo data const tailwindModuleFilepath = path.join( path.dirname(this.resourcePath), tailwindModuleID.replace(/\//g, path.sep), ); demos[demoName].moduleTailwind = tailwindModuleID; demos[demoName].rawTailwind = await fs.readFile(tailwindModuleFilepath, { encoding: 'utf8', }); this.addDependency(tailwindModuleFilepath); demoModuleIDs.add(tailwindModuleID); extractImports(demos[demoName].rawTailwind).forEach((importModuleID) => importedModuleIDs.add(importModuleID), ); demoModuleIDs.add(demos[demoName].moduleTailwind); } catch (error) { // tailwind js demo doesn't exists } try { // Add TS demo data const tailwindTSModuleID = tailwindModuleID.replace('.js', '.tsx'); const tailwindTSModuleFilepath = path.join( path.dirname(this.resourcePath), tailwindTSModuleID.replace(/\//g, path.sep), ); demos[demoName].moduleTSTailwind = tailwindTSModuleID; demos[demoName].rawTailwindTS = await fs.readFile(tailwindTSModuleFilepath, { encoding: 'utf8', }); this.addDependency(tailwindTSModuleFilepath); demoModuleIDs.add(tailwindTSModuleID); extractImports(demos[demoName].rawTailwindTS).forEach((importModuleID) => importedModuleIDs.add(importModuleID), ); demoModuleIDs.add(demos[demoName].moduleTSTailwind); } catch (error) { // tailwind TS demo doesn't exists } // Add plain CSS demo data const cssModuleID = moduleID.replace('/system/index.js', '/css/index.js'); try { // Add JS demo data const cssModuleFilepath = path.join( path.dirname(this.resourcePath), cssModuleID.replace(/\//g, path.sep), ); demos[demoName].moduleCSS = cssModuleID; demos[demoName].rawCSS = await fs.readFile(cssModuleFilepath, { encoding: 'utf8', }); this.addDependency(cssModuleFilepath); demoModuleIDs.add(cssModuleID); extractImports(demos[demoName].rawCSS).forEach((importModuleID) => importedModuleIDs.add(importModuleID), ); demoModuleIDs.add(demos[demoName].moduleCSS); } catch (error) { // plain css js demo doesn't exists } try { // Add TS demo data const cssTSModuleID = cssModuleID.replace('.js', '.tsx'); const cssTSModuleFilepath = path.join( path.dirname(this.resourcePath), cssTSModuleID.replace(/\//g, path.sep), ); demos[demoName].moduleTSCSS = cssTSModuleID; demos[demoName].rawCSSTS = await fs.readFile(cssTSModuleFilepath, { encoding: 'utf8', }); this.addDependency(cssTSModuleFilepath); demoModuleIDs.add(cssTSModuleID); extractImports(demos[demoName].rawCSSTS).forEach((importModuleID) => importedModuleIDs.add(importModuleID), ); demoModuleIDs.add(demos[demoName].moduleTSCSS); } catch (error) { // plain css demo doesn't exists } // Tailwind preview try { const tailwindPreviewFilepath = moduleFilepath.replace( `${path.sep}system${path.sep}index.js`, `${path.sep}tailwind${path.sep}index.tsx.preview`, ); const tailwindJsxPreview = await fs.readFile(tailwindPreviewFilepath, { encoding: 'utf8', }); this.addDependency(tailwindPreviewFilepath); demos[demoName].tailwindJsxPreview = tailwindJsxPreview; } catch (error) { // No preview exists. This is fine. } // CSS preview try { const cssPreviewFilepath = moduleFilepath.replace( `${path.sep}system${path.sep}index.js`, `${path.sep}css${path.sep}index.tsx.preview`, ); const cssJsxPreview = await fs.readFile(cssPreviewFilepath, { encoding: 'utf8', }); this.addDependency(cssPreviewFilepath); demos[demoName].cssJsxPreview = cssJsxPreview; } catch (error) { // No preview exists. This is fine. } } try { const previewFilepath = moduleFilepath.replace(/\.js$/, '.tsx.preview'); const jsxPreview = await fs.readFile(previewFilepath, { encoding: 'utf8' }); this.addDependency(previewFilepath); demos[demoName].jsxPreview = jsxPreview; } catch (error) { // No preview exists. This is fine. } try { const moduleTS = moduleID.replace(/\.js$/, '.tsx'); const moduleTSFilepath = path.join( path.dirname(this.resourcePath), moduleTS.replace(/\//g, path.sep), ); this.addDependency(moduleTSFilepath); const rawTS = await fs.readFile(moduleTSFilepath, { encoding: 'utf8' }); // In development devs can choose whether they want to work on the TS or JS version. // But this leads to building both demo version i.e. more build time. demos[demoName].moduleTS = this.mode === 'production' ? moduleID : moduleTS; demos[demoName].rawTS = rawTS; demoModuleIDs.add(demos[demoName].moduleTS); } catch (error) { // TS version of the demo doesn't exist. This is fine. } }), ); const componentNames = Array.from( new Set( docs.en.rendered .filter((markdownOrComponentConfig) => { return ( typeof markdownOrComponentConfig !== 'string' && markdownOrComponentConfig.component ); }) .map((componentConfig) => { return componentConfig.component; }), ), ); componentNames.forEach((componentName) => { const moduleID = path .join(this.rootContext, 'src', componentName.replace(/^docs\/src/, '')) .replace(/\\/g, '/'); components[moduleID] = componentName; componentModuleIDs.add(moduleID); }); const transformed = ` ${Array.from(importedModuleIDs) .map((moduleID) => { return `import * as ${moduleIDToJSIdentifier( moduleID.replace('@', '$'), )} from '${moduleID}';`; }) .join('\n')} ${Array.from(demoModuleIDs) .map((moduleID) => { return `import ${moduleIDToJSIdentifier(moduleID)} from '${moduleID}';`; }) .join('\n')} ${Array.from(componentModuleIDs) .map((moduleID) => { return `import ${moduleIDToJSIdentifier(moduleID)} from '${moduleID}';`; }) .join('\n')} export const docs = ${JSON.stringify(docs, null, 2)}; export const demos = ${JSON.stringify(demos, null, 2)}; demos.scope = { process: {}, import: { ${Array.from(importedModuleIDs) .map((moduleID) => ` "${moduleID}": ${moduleIDToJSIdentifier(moduleID.replace('@', '$'))},`) .join('\n')} }, }; export const demoComponents = { ${Array.from(demoModuleIDs) .map((moduleID) => { return ` "${moduleID}": ${moduleIDToJSIdentifier(moduleID)},`; }) .join('\n')} }; export const srcComponents = { ${Array.from(componentModuleIDs) .map((moduleID) => { return ` "${components[moduleID]}": ${moduleIDToJSIdentifier(moduleID)},`; }) .join('\n')} }; `; return transformed; };
packages/markdown/loader.js
1
https://github.com/mui/material-ui/commit/e41667669bd16fb8736eb26aa4114ec220aac5c3
[ 0.0006286959396675229, 0.00019693745707627386, 0.0001633411447983235, 0.00016860771575011313, 0.00010174627095693722 ]
{ "id": 3, "code_window": [ "making it simple to extract parts of a page (such as a \"hero unit\", or footer, for example)\n", "for reuse in other pages.\n", "For multi-part examples, a table in the README at the linked source code location describes\n", "the purpose of each file.\n", "\n", "{{\"component\": \"docs/src/modules/components/MaterialFreeTemplatesCollection.js\"}}\n", "\n", "See any room for improvement?\n", "Please feel free to open an [issue](https://github.com/mui/material-ui/issues/new/choose) or [pull request](https://github.com/mui/material-ui/pulls) on GitHub.\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "{{\"component\": \"modules/components/MaterialFreeTemplatesCollection.js\"}}\n" ], "file_path": "docs/data/material/getting-started/templates/templates.md", "type": "replace", "edit_start_line_idx": 21 }
<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 0 24 24" width="24"><path d="M0 0h24v24H0V0z" fill="none"/><path d="M8 2c-1.1 0-2 .9-2 2v3.17c0 .53.21 1.04.59 1.42L10 12l-3.42 3.42c-.37.38-.58.89-.58 1.42V20c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2v-3.16c0-.53-.21-1.04-.58-1.41L14 12l3.41-3.4c.38-.38.59-.89.59-1.42V4c0-1.1-.9-2-2-2H8zm8 14.5V19c0 .55-.45 1-1 1H9c-.55 0-1-.45-1-1v-2.5l4-4 4 4zm-4-5l-4-4V5c0-.55.45-1 1-1h6c.55 0 1 .45 1 1v2.5l-4 4z"/></svg>
packages/mui-icons-material/material-icons/hourglass_empty_rounded_24px.svg
0
https://github.com/mui/material-ui/commit/e41667669bd16fb8736eb26aa4114ec220aac5c3
[ 0.00016428834351245314, 0.00016428834351245314, 0.00016428834351245314, 0.00016428834351245314, 0 ]
{ "id": 3, "code_window": [ "making it simple to extract parts of a page (such as a \"hero unit\", or footer, for example)\n", "for reuse in other pages.\n", "For multi-part examples, a table in the README at the linked source code location describes\n", "the purpose of each file.\n", "\n", "{{\"component\": \"docs/src/modules/components/MaterialFreeTemplatesCollection.js\"}}\n", "\n", "See any room for improvement?\n", "Please feel free to open an [issue](https://github.com/mui/material-ui/issues/new/choose) or [pull request](https://github.com/mui/material-ui/pulls) on GitHub.\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "{{\"component\": \"modules/components/MaterialFreeTemplatesCollection.js\"}}\n" ], "file_path": "docs/data/material/getting-started/templates/templates.md", "type": "replace", "edit_start_line_idx": 21 }
<Tabs value={value} onChange={handleChange} variant="scrollable" scrollButtons="auto" aria-label="scrollable auto tabs example" > <Tab label="Item One" /> <Tab label="Item Two" /> <Tab label="Item Three" /> <Tab label="Item Four" /> <Tab label="Item Five" /> <Tab label="Item Six" /> <Tab label="Item Seven" /> </Tabs>
docs/data/material/components/tabs/ScrollableTabsButtonAuto.tsx.preview
0
https://github.com/mui/material-ui/commit/e41667669bd16fb8736eb26aa4114ec220aac5c3
[ 0.00017113152716774493, 0.00017104583093896508, 0.00017096013471018523, 0.00017104583093896508, 8.569622877985239e-8 ]
{ "id": 3, "code_window": [ "making it simple to extract parts of a page (such as a \"hero unit\", or footer, for example)\n", "for reuse in other pages.\n", "For multi-part examples, a table in the README at the linked source code location describes\n", "the purpose of each file.\n", "\n", "{{\"component\": \"docs/src/modules/components/MaterialFreeTemplatesCollection.js\"}}\n", "\n", "See any room for improvement?\n", "Please feel free to open an [issue](https://github.com/mui/material-ui/issues/new/choose) or [pull request](https://github.com/mui/material-ui/pulls) on GitHub.\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "{{\"component\": \"modules/components/MaterialFreeTemplatesCollection.js\"}}\n" ], "file_path": "docs/data/material/getting-started/templates/templates.md", "type": "replace", "edit_start_line_idx": 21 }
"use strict"; "use client"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon")); var _jsxRuntime = require("react/jsx-runtime"); var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M20 4v12H5.17L4 17.17V4h16m0-2H4c-1.1 0-2 .9-2 2v15.59c0 .89 1.08 1.34 1.71.71L6 18h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2z" }), 'ChatBubbleOutlineRounded'); exports.default = _default;
packages/mui-icons-material/lib/ChatBubbleOutlineRounded.js
0
https://github.com/mui/material-ui/commit/e41667669bd16fb8736eb26aa4114ec220aac5c3
[ 0.00016760460857767612, 0.0001671618374530226, 0.00016671905177645385, 0.0001671618374530226, 4.427784006111324e-7 ]
{ "id": 4, "code_window": [ " <Link\n", " href={example.link}\n", " variant=\"body2\"\n", " sx={{\n", " fontWeight: 500,\n", " display: 'flex',\n", " alignItems: 'center',\n", " mt: 0.5,\n", " }}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " fontWeight: 'medium',\n" ], "file_path": "docs/src/modules/components/ExampleCollection.js", "type": "replace", "edit_start_line_idx": 147 }
# Base UI components <p class="description">Every Base UI component available so far.</p> {{"component": "docs/src/modules/components/BaseUIComponents.js"}}
docs/data/base/all-components/all-components.md
1
https://github.com/mui/material-ui/commit/e41667669bd16fb8736eb26aa4114ec220aac5c3
[ 0.00016103398229461163, 0.00016103398229461163, 0.00016103398229461163, 0.00016103398229461163, 0 ]
{ "id": 4, "code_window": [ " <Link\n", " href={example.link}\n", " variant=\"body2\"\n", " sx={{\n", " fontWeight: 500,\n", " display: 'flex',\n", " alignItems: 'center',\n", " mt: 0.5,\n", " }}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " fontWeight: 'medium',\n" ], "file_path": "docs/src/modules/components/ExampleCollection.js", "type": "replace", "edit_start_line_idx": 147 }
"use client"; import createSvgIcon from './utils/createSvgIcon'; import { jsx as _jsx } from "react/jsx-runtime"; export default createSvgIcon( /*#__PURE__*/_jsx("path", { d: "M2.81 2.81 1.39 4.22l2.69 2.69C2.78 8.6 2 10.71 2 13c0 2.76 1.12 5.26 2.93 7.07l1.42-1.42C4.9 17.21 4 15.21 4 13c0-1.75.57-3.35 1.51-4.66l1.43 1.43C6.35 10.7 6 11.81 6 13c0 1.66.68 3.15 1.76 4.24l1.42-1.42C8.45 15.1 8 14.11 8 13c0-.63.15-1.23.41-1.76l1.61 1.61c0 .05-.02.1-.02.15 0 .55.23 1.05.59 1.41.36.36.86.59 1.41.59.05 0 .1-.01.16-.02l7.62 7.62 1.41-1.41L2.81 2.81zM17.7 14.87c.19-.59.3-1.22.3-1.87 0-3.31-2.69-6-6-6-.65 0-1.28.1-1.87.3l1.71 1.71C11.89 9 11.95 9 12 9c2.21 0 4 1.79 4 4 0 .05 0 .11-.01.16l1.71 1.71zM12 5c4.42 0 8 3.58 8 8 0 1.22-.27 2.37-.77 3.4l1.49 1.49C21.53 16.45 22 14.78 22 13c0-5.52-4.48-10-10-10-1.78 0-3.44.46-4.89 1.28l1.48 1.48C9.63 5.27 10.78 5 12 5z" }), 'WifiTetheringOff');
packages/mui-icons-material/lib/esm/WifiTetheringOff.js
0
https://github.com/mui/material-ui/commit/e41667669bd16fb8736eb26aa4114ec220aac5c3
[ 0.00016522132500540465, 0.00016522132500540465, 0.00016522132500540465, 0.00016522132500540465, 0 ]
{ "id": 4, "code_window": [ " <Link\n", " href={example.link}\n", " variant=\"body2\"\n", " sx={{\n", " fontWeight: 500,\n", " display: 'flex',\n", " alignItems: 'center',\n", " mt: 0.5,\n", " }}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " fontWeight: 'medium',\n" ], "file_path": "docs/src/modules/components/ExampleCollection.js", "type": "replace", "edit_start_line_idx": 147 }
"use client"; import createSvgIcon from './utils/createSvgIcon'; import { jsx as _jsx } from "react/jsx-runtime"; export default createSvgIcon([/*#__PURE__*/_jsx("path", { d: "M18 10H6c-.84 0-1.55.52-1.85 1.25l11.11 2.72c.31.08.64 0 .88-.2l3.49-2.92c-.37-.51-.96-.85-1.63-.85zm0-4H6c-1.1 0-2 .9-2 2v.55C4.59 8.21 5.27 8 6 8h12c.73 0 1.41.21 2 .55V8c0-1.1-.9-2-2-2z", opacity: ".3" }, "0"), /*#__PURE__*/_jsx("path", { d: "M18 4H6C3.79 4 2 5.79 2 8v8c0 2.21 1.79 4 4 4h12c2.21 0 4-1.79 4-4V8c0-2.21-1.79-4-4-4zm-1.86 9.77c-.24.2-.57.28-.88.2L4.15 11.25C4.45 10.52 5.16 10 6 10h12c.67 0 1.26.34 1.63.84l-3.49 2.93zM20 8.55c-.59-.34-1.27-.55-2-.55H6c-.73 0-1.41.21-2 .55V8c0-1.1.9-2 2-2h12c1.1 0 2 .9 2 2v.55z" }, "1")], 'WalletTwoTone');
packages/mui-icons-material/lib/esm/WalletTwoTone.js
0
https://github.com/mui/material-ui/commit/e41667669bd16fb8736eb26aa4114ec220aac5c3
[ 0.00016733795928303152, 0.00016711471835151315, 0.00016689147741999477, 0.00016711471835151315, 2.2324093151837587e-7 ]
{ "id": 4, "code_window": [ " <Link\n", " href={example.link}\n", " variant=\"body2\"\n", " sx={{\n", " fontWeight: 500,\n", " display: 'flex',\n", " alignItems: 'center',\n", " mt: 0.5,\n", " }}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " fontWeight: 'medium',\n" ], "file_path": "docs/src/modules/components/ExampleCollection.js", "type": "replace", "edit_start_line_idx": 147 }
<Grid container rowSpacing={1} columnSpacing={{ xs: 1, sm: 2, md: 3 }}> <Grid item xs={6}> <Item>1</Item> </Grid> <Grid item xs={6}> <Item>2</Item> </Grid> <Grid item xs={6}> <Item>3</Item> </Grid> <Grid item xs={6}> <Item>4</Item> </Grid> </Grid>
docs/data/material/components/grid/RowAndColumnSpacing.tsx.preview
0
https://github.com/mui/material-ui/commit/e41667669bd16fb8736eb26aa4114ec220aac5c3
[ 0.000170640429132618, 0.00016845794743858278, 0.00016627546574454755, 0.00016845794743858278, 0.000002182481694035232 ]
{ "id": 5, "code_window": [ " </Typography>\n", " <Link\n", " href={example.tsLink}\n", " variant=\"body2\"\n", " sx={{\n", " fontWeight: 500,\n", " display: 'flex',\n", " alignItems: 'center',\n", " }}\n", " >\n", " {example.tsLabel}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " fontWeight: 'medium',\n" ], "file_path": "docs/src/modules/components/ExampleCollection.js", "type": "replace", "edit_start_line_idx": 172 }
const { promises: fs, readdirSync } = require('fs'); const path = require('path'); const { prepareMarkdown } = require('./parseMarkdown'); const extractImports = require('./extractImports'); const notEnglishMarkdownRegExp = /-([a-z]{2})\.md$/; /** * @param {string} string */ function upperCaseFirst(string) { return `${string[0].toUpperCase()}${string.slice(1)}`; } /** * @param {string} moduleID * @example moduleIDToJSIdentifier('./Box.js') === '$$IndexJs' * @example moduleIDToJSIdentifier('./Box-new.js') === '$$BoxNewJs' * @example moduleIDToJSIdentifier('../Box-new.js') === '$$$BoxNewJs' */ function moduleIDToJSIdentifier(moduleID) { const delimiter = /(\.|-|\/|:)/; return moduleID .split(delimiter) .filter((part) => !delimiter.test(part)) .map((part) => (part.length === 0 ? '$' : part)) .map(upperCaseFirst) .join(''); } const componentPackageMapping = { 'material-ui': {}, 'base-ui': {}, 'joy-ui': {}, }; const packages = [ { productId: 'material-ui', paths: [ path.join(__dirname, '../../packages/mui-base/src'), path.join(__dirname, '../../packages/mui-lab/src'), path.join(__dirname, '../../packages/mui-material/src'), ], }, { productId: 'base-ui', paths: [path.join(__dirname, '../../packages/mui-base/src')], }, { productId: 'joy-ui', paths: [path.join(__dirname, '../../packages/mui-joy/src')], }, ]; packages.forEach((pkg) => { pkg.paths.forEach((pkgPath) => { const match = pkgPath.match(/packages(?:\\|\/)([^/\\]+)(?:\\|\/)src/); const packageName = match ? match[1] : null; if (!packageName) { throw new Error(`cannot find package name from path: ${pkgPath}`); } const filePaths = readdirSync(pkgPath); filePaths.forEach((folder) => { if (folder.match(/^[A-Z]/)) { if (!componentPackageMapping[pkg.productId]) { throw new Error(`componentPackageMapping must have "${pkg.productId}" as a key`); } // filename starts with Uppercase = component componentPackageMapping[pkg.productId][folder] = packageName; } }); }); }); /** * @type {import('webpack').loader.Loader} */ module.exports = async function demoLoader() { const englishFilepath = this.resourcePath; const options = this.getOptions(); const englishFilename = path.basename(englishFilepath, '.md'); const files = await fs.readdir(path.dirname(englishFilepath)); const translations = await Promise.all( files .map((filename) => { if (filename === `${englishFilename}.md`) { return { filename, userLanguage: 'en', }; } const matchNotEnglishMarkdown = filename.match(notEnglishMarkdownRegExp); if ( filename.startsWith(englishFilename) && matchNotEnglishMarkdown !== null && options.languagesInProgress.indexOf(matchNotEnglishMarkdown[1]) !== -1 ) { return { filename, userLanguage: matchNotEnglishMarkdown[1], }; } return null; }) .filter((translation) => translation) .map(async (translation) => { const filepath = path.join(path.dirname(englishFilepath), translation.filename); this.addDependency(filepath); const markdown = await fs.readFile(filepath, { encoding: 'utf8' }); return { ...translation, markdown, }; }), ); // Use .. as the docs runs from the /docs folder const repositoryRoot = path.join(this.rootContext, '..'); const fileRelativeContext = path .relative(repositoryRoot, this.context) // win32 to posix .replace(/\\/g, '/'); const { docs } = prepareMarkdown({ fileRelativeContext, translations, componentPackageMapping, options, }); const demos = {}; const importedModuleIDs = new Set(); const components = {}; const demoModuleIDs = new Set(); const componentModuleIDs = new Set(); const demoNames = Array.from( new Set( docs.en.rendered .filter((markdownOrComponentConfig) => { return typeof markdownOrComponentConfig !== 'string' && markdownOrComponentConfig.demo; }) .map((demoConfig) => { return demoConfig.demo; }), ), ); await Promise.all( demoNames.map(async (demoName) => { const multipleDemoVersionsUsed = !demoName.endsWith('.js'); // TODO: const moduleID = demoName; // The import paths currently use a completely different format. // They should just use relative imports. let moduleID = `./${demoName.replace( `pages/${fileRelativeContext.replace(/^docs\/src\/pages\//, '')}/`, '', )}`; if (multipleDemoVersionsUsed) { moduleID = `${moduleID}/system/index.js`; } const moduleFilepath = path.join( path.dirname(this.resourcePath), moduleID.replace(/\//g, path.sep), ); this.addDependency(moduleFilepath); demos[demoName] = { module: moduleID, raw: await fs.readFile(moduleFilepath, { encoding: 'utf8' }), }; demoModuleIDs.add(moduleID); extractImports(demos[demoName].raw).forEach((importModuleID) => importedModuleIDs.add(importModuleID), ); if (multipleDemoVersionsUsed) { // Add Tailwind demo data const tailwindModuleID = moduleID.replace('/system/index.js', '/tailwind/index.js'); try { // Add JS demo data const tailwindModuleFilepath = path.join( path.dirname(this.resourcePath), tailwindModuleID.replace(/\//g, path.sep), ); demos[demoName].moduleTailwind = tailwindModuleID; demos[demoName].rawTailwind = await fs.readFile(tailwindModuleFilepath, { encoding: 'utf8', }); this.addDependency(tailwindModuleFilepath); demoModuleIDs.add(tailwindModuleID); extractImports(demos[demoName].rawTailwind).forEach((importModuleID) => importedModuleIDs.add(importModuleID), ); demoModuleIDs.add(demos[demoName].moduleTailwind); } catch (error) { // tailwind js demo doesn't exists } try { // Add TS demo data const tailwindTSModuleID = tailwindModuleID.replace('.js', '.tsx'); const tailwindTSModuleFilepath = path.join( path.dirname(this.resourcePath), tailwindTSModuleID.replace(/\//g, path.sep), ); demos[demoName].moduleTSTailwind = tailwindTSModuleID; demos[demoName].rawTailwindTS = await fs.readFile(tailwindTSModuleFilepath, { encoding: 'utf8', }); this.addDependency(tailwindTSModuleFilepath); demoModuleIDs.add(tailwindTSModuleID); extractImports(demos[demoName].rawTailwindTS).forEach((importModuleID) => importedModuleIDs.add(importModuleID), ); demoModuleIDs.add(demos[demoName].moduleTSTailwind); } catch (error) { // tailwind TS demo doesn't exists } // Add plain CSS demo data const cssModuleID = moduleID.replace('/system/index.js', '/css/index.js'); try { // Add JS demo data const cssModuleFilepath = path.join( path.dirname(this.resourcePath), cssModuleID.replace(/\//g, path.sep), ); demos[demoName].moduleCSS = cssModuleID; demos[demoName].rawCSS = await fs.readFile(cssModuleFilepath, { encoding: 'utf8', }); this.addDependency(cssModuleFilepath); demoModuleIDs.add(cssModuleID); extractImports(demos[demoName].rawCSS).forEach((importModuleID) => importedModuleIDs.add(importModuleID), ); demoModuleIDs.add(demos[demoName].moduleCSS); } catch (error) { // plain css js demo doesn't exists } try { // Add TS demo data const cssTSModuleID = cssModuleID.replace('.js', '.tsx'); const cssTSModuleFilepath = path.join( path.dirname(this.resourcePath), cssTSModuleID.replace(/\//g, path.sep), ); demos[demoName].moduleTSCSS = cssTSModuleID; demos[demoName].rawCSSTS = await fs.readFile(cssTSModuleFilepath, { encoding: 'utf8', }); this.addDependency(cssTSModuleFilepath); demoModuleIDs.add(cssTSModuleID); extractImports(demos[demoName].rawCSSTS).forEach((importModuleID) => importedModuleIDs.add(importModuleID), ); demoModuleIDs.add(demos[demoName].moduleTSCSS); } catch (error) { // plain css demo doesn't exists } // Tailwind preview try { const tailwindPreviewFilepath = moduleFilepath.replace( `${path.sep}system${path.sep}index.js`, `${path.sep}tailwind${path.sep}index.tsx.preview`, ); const tailwindJsxPreview = await fs.readFile(tailwindPreviewFilepath, { encoding: 'utf8', }); this.addDependency(tailwindPreviewFilepath); demos[demoName].tailwindJsxPreview = tailwindJsxPreview; } catch (error) { // No preview exists. This is fine. } // CSS preview try { const cssPreviewFilepath = moduleFilepath.replace( `${path.sep}system${path.sep}index.js`, `${path.sep}css${path.sep}index.tsx.preview`, ); const cssJsxPreview = await fs.readFile(cssPreviewFilepath, { encoding: 'utf8', }); this.addDependency(cssPreviewFilepath); demos[demoName].cssJsxPreview = cssJsxPreview; } catch (error) { // No preview exists. This is fine. } } try { const previewFilepath = moduleFilepath.replace(/\.js$/, '.tsx.preview'); const jsxPreview = await fs.readFile(previewFilepath, { encoding: 'utf8' }); this.addDependency(previewFilepath); demos[demoName].jsxPreview = jsxPreview; } catch (error) { // No preview exists. This is fine. } try { const moduleTS = moduleID.replace(/\.js$/, '.tsx'); const moduleTSFilepath = path.join( path.dirname(this.resourcePath), moduleTS.replace(/\//g, path.sep), ); this.addDependency(moduleTSFilepath); const rawTS = await fs.readFile(moduleTSFilepath, { encoding: 'utf8' }); // In development devs can choose whether they want to work on the TS or JS version. // But this leads to building both demo version i.e. more build time. demos[demoName].moduleTS = this.mode === 'production' ? moduleID : moduleTS; demos[demoName].rawTS = rawTS; demoModuleIDs.add(demos[demoName].moduleTS); } catch (error) { // TS version of the demo doesn't exist. This is fine. } }), ); const componentNames = Array.from( new Set( docs.en.rendered .filter((markdownOrComponentConfig) => { return ( typeof markdownOrComponentConfig !== 'string' && markdownOrComponentConfig.component ); }) .map((componentConfig) => { return componentConfig.component; }), ), ); componentNames.forEach((componentName) => { const moduleID = path .join(this.rootContext, 'src', componentName.replace(/^docs\/src/, '')) .replace(/\\/g, '/'); components[moduleID] = componentName; componentModuleIDs.add(moduleID); }); const transformed = ` ${Array.from(importedModuleIDs) .map((moduleID) => { return `import * as ${moduleIDToJSIdentifier( moduleID.replace('@', '$'), )} from '${moduleID}';`; }) .join('\n')} ${Array.from(demoModuleIDs) .map((moduleID) => { return `import ${moduleIDToJSIdentifier(moduleID)} from '${moduleID}';`; }) .join('\n')} ${Array.from(componentModuleIDs) .map((moduleID) => { return `import ${moduleIDToJSIdentifier(moduleID)} from '${moduleID}';`; }) .join('\n')} export const docs = ${JSON.stringify(docs, null, 2)}; export const demos = ${JSON.stringify(demos, null, 2)}; demos.scope = { process: {}, import: { ${Array.from(importedModuleIDs) .map((moduleID) => ` "${moduleID}": ${moduleIDToJSIdentifier(moduleID.replace('@', '$'))},`) .join('\n')} }, }; export const demoComponents = { ${Array.from(demoModuleIDs) .map((moduleID) => { return ` "${moduleID}": ${moduleIDToJSIdentifier(moduleID)},`; }) .join('\n')} }; export const srcComponents = { ${Array.from(componentModuleIDs) .map((moduleID) => { return ` "${components[moduleID]}": ${moduleIDToJSIdentifier(moduleID)},`; }) .join('\n')} }; `; return transformed; };
packages/markdown/loader.js
1
https://github.com/mui/material-ui/commit/e41667669bd16fb8736eb26aa4114ec220aac5c3
[ 0.005974675063043833, 0.00030192785197868943, 0.00016431513358838856, 0.00017017607751768082, 0.0008650908130221069 ]
{ "id": 5, "code_window": [ " </Typography>\n", " <Link\n", " href={example.tsLink}\n", " variant=\"body2\"\n", " sx={{\n", " fontWeight: 500,\n", " display: 'flex',\n", " alignItems: 'center',\n", " }}\n", " >\n", " {example.tsLabel}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " fontWeight: 'medium',\n" ], "file_path": "docs/src/modules/components/ExampleCollection.js", "type": "replace", "edit_start_line_idx": 172 }
import * as React from 'react'; import { expect } from 'chai'; import { act, createRenderer, fireEvent } from 'test/utils'; import MenuItem from '@mui/material/MenuItem'; import Select from '@mui/material/Select'; import Dialog from '@mui/material/Dialog'; import FormControl from '@mui/material/FormControl'; import InputLabel from '@mui/material/InputLabel'; describe('<Select> integration', () => { const { clock, render } = createRenderer({ clock: 'fake' }); describe('with Dialog', () => { function SelectAndDialog() { const [value, setValue] = React.useState(10); const handleChange = (event) => { setValue(Number(event.target.value)); }; return ( <Dialog open> <Select MenuProps={{ transitionDuration: 0, BackdropProps: { 'data-testid': 'select-backdrop' }, }} value={value} onChange={handleChange} > <MenuItem value=""> <em>None</em> </MenuItem> <MenuItem value={10}>Ten</MenuItem> <MenuItem value={20}>Twenty</MenuItem> <MenuItem value={30}>Thirty</MenuItem> </Select> </Dialog> ); } it('should focus the selected item', () => { const { getByTestId, getAllByRole, getByRole, queryByRole } = render(<SelectAndDialog />); const trigger = getByRole('button'); // Let's open the select component // in the browser user click also focuses fireEvent.mouseDown(trigger); const options = getAllByRole('option'); expect(options[1]).toHaveFocus(); // Now, let's close the select component act(() => { getByTestId('select-backdrop').click(); }); clock.tick(0); expect(queryByRole('listbox')).to.equal(null); expect(trigger).toHaveFocus(); }); it('should be able to change the selected item', () => { const { getAllByRole, getByRole, queryByRole } = render(<SelectAndDialog />); const trigger = getByRole('button'); expect(trigger).toHaveAccessibleName('Ten'); // Let's open the select component // in the browser user click also focuses fireEvent.mouseDown(trigger); const options = getAllByRole('option'); expect(options[1]).toHaveFocus(); // Now, let's close the select component act(() => { options[2].click(); }); clock.tick(0); expect(queryByRole('listbox')).to.equal(null); expect(trigger).toHaveFocus(); expect(trigger).to.have.text('Twenty'); }); }); describe('with label', () => { it('requires `id` and `labelId` for a proper accessible name', () => { const { getByRole } = render( <FormControl> <InputLabel id="label">Age</InputLabel> <Select id="input" labelId="label" value="10"> <MenuItem value="">none</MenuItem> <MenuItem value="10">Ten</MenuItem> </Select> </FormControl>, ); expect(getByRole('button')).toHaveAccessibleName('Age Ten'); }); // we're somewhat abusing "focus" here. What we're actually interested in is // displaying it as "active". WAI-ARIA authoring practices do not consider the // the trigger part of the widget while a native <select /> will outline the trigger // as well it('is displayed as focused while open', () => { const { getByTestId, getByRole } = render( <FormControl> <InputLabel classes={{ focused: 'focused-label' }} data-testid="label"> Age </InputLabel> <Select MenuProps={{ transitionDuration: 0, }} value="" > <MenuItem value="">none</MenuItem> <MenuItem value={10}>Ten</MenuItem> </Select> </FormControl>, ); const trigger = getByRole('button'); act(() => { trigger.focus(); }); fireEvent.keyDown(trigger, { key: 'Enter' }); clock.tick(0); expect(getByTestId('label')).to.have.class('focused-label'); }); it('does not stays in an active state if an open action did not actually open', () => { // test for https://github.com/mui/material-ui/issues/17294 // we used to set a flag to stop blur propagation when we wanted to open the // select but never considered what happened if the select never opened const { container, getByRole } = render( <FormControl> <InputLabel classes={{ focused: 'focused-label' }} htmlFor="age-simple"> Age </InputLabel> <Select inputProps={{ id: 'age' }} open={false} value=""> <MenuItem value="">none</MenuItem> <MenuItem value={10}>Ten</MenuItem> </Select> </FormControl>, ); const trigger = getByRole('button'); act(() => { trigger.focus(); }); expect(container.querySelector('[for="age-simple"]')).to.have.class('focused-label'); fireEvent.keyDown(trigger, { key: 'Enter' }); expect(container.querySelector('[for="age-simple"]')).to.have.class('focused-label'); act(() => { trigger.blur(); }); expect(container.querySelector('[for="age-simple"]')).not.to.have.class('focused-label'); }); }); });
packages/mui-material/test/integration/Select.test.js
0
https://github.com/mui/material-ui/commit/e41667669bd16fb8736eb26aa4114ec220aac5c3
[ 0.00017482467228546739, 0.00017010403098538518, 0.00016397486615460366, 0.0001706135954009369, 0.0000029650279884663178 ]
{ "id": 5, "code_window": [ " </Typography>\n", " <Link\n", " href={example.tsLink}\n", " variant=\"body2\"\n", " sx={{\n", " fontWeight: 500,\n", " display: 'flex',\n", " alignItems: 'center',\n", " }}\n", " >\n", " {example.tsLabel}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " fontWeight: 'medium',\n" ], "file_path": "docs/src/modules/components/ExampleCollection.js", "type": "replace", "edit_start_line_idx": 172 }
<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 0 24 24" width="24"><path d="M0 0h24v24H0V0z" fill="none"/><path d="M3.96 11.38C4.24 9.91 5.62 8.9 7.12 8.9h2.93c.52 0 .95-.43.95-.95S10.57 7 10.05 7H7.22c-2.61 0-4.94 1.91-5.19 4.51C1.74 14.49 4.08 17 7 17h3.05c.52 0 .95-.43.95-.95s-.43-.95-.95-.95H7c-1.91 0-3.42-1.74-3.04-3.72zM9 13h6c.55 0 1-.45 1-1s-.45-1-1-1H9c-.55 0-1 .45-1 1s.45 1 1 1zm7.78-6h-2.83c-.52 0-.95.43-.95.95s.43.95.95.95h2.93c1.5 0 2.88 1.01 3.16 2.48.38 1.98-1.13 3.72-3.04 3.72h-3.05c-.52 0-.95.43-.95.95s.43.95.95.95H17c2.92 0 5.26-2.51 4.98-5.49-.25-2.6-2.59-4.51-5.2-4.51z"/></svg>
packages/mui-icons-material/material-icons/insert_link_rounded_24px.svg
0
https://github.com/mui/material-ui/commit/e41667669bd16fb8736eb26aa4114ec220aac5c3
[ 0.0001645926822675392, 0.0001645926822675392, 0.0001645926822675392, 0.0001645926822675392, 0 ]
{ "id": 5, "code_window": [ " </Typography>\n", " <Link\n", " href={example.tsLink}\n", " variant=\"body2\"\n", " sx={{\n", " fontWeight: 500,\n", " display: 'flex',\n", " alignItems: 'center',\n", " }}\n", " >\n", " {example.tsLabel}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " fontWeight: 'medium',\n" ], "file_path": "docs/src/modules/components/ExampleCollection.js", "type": "replace", "edit_start_line_idx": 172 }
import * as React from 'react'; import createSvgIcon from './utils/createSvgIcon'; import { jsx as _jsx } from "react/jsx-runtime"; import { jsxs as _jsxs } from "react/jsx-runtime"; export default createSvgIcon( /*#__PURE__*/_jsxs(React.Fragment, { children: [/*#__PURE__*/_jsx("path", { fillOpacity: ".3", d: "M17 5.33C17 4.6 16.4 4 15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33V8h10V5.33z" }), /*#__PURE__*/_jsx("path", { d: "M7 8v12.67C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V8H7z" })] }), 'Battery90');
packages/mui-icons-material/lib/esm/Battery90.js
0
https://github.com/mui/material-ui/commit/e41667669bd16fb8736eb26aa4114ec220aac5c3
[ 0.00017024924454744905, 0.00016917525499593467, 0.00016810126544442028, 0.00016917525499593467, 0.0000010739895515143871 ]
{ "id": 6, "code_window": [ " ),\n", " );\n", "\n", " componentNames.forEach((componentName) => {\n", " const moduleID = path\n", " .join(this.rootContext, 'src', componentName.replace(/^docs\\/src/, ''))\n", " .replace(/\\\\/g, '/');\n", "\n", " components[moduleID] = componentName;\n", " componentModuleIDs.add(moduleID);\n", " });\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " const moduleID = path.join(this.rootContext, 'src', componentName).replace(/\\\\/g, '/');\n" ], "file_path": "packages/markdown/loader.js", "type": "replace", "edit_start_line_idx": 374 }
# Example projects <p class="description">A collection of example, boilerplates, and scaffolds to jumpstart your next Material UI project.</p> ## Official examples The following starter projects are all available in the MUI Core [`/examples`](https://github.com/mui/material-ui/tree/master/examples) folder. These examples feature Material UI paired with other popular React libraries and frameworks, so you can skip the initial setup steps and jump straight into building. Not sure which to pick? We recommend Next.js for a comprehensive solution, or Vite if you're looking for a leaner development experience. See [Start a New React Project](https://react.dev/learn/start-a-new-react-project) from the official React docs to learn more about the options available. <!-- #default-branch-switch --> {{"component": "docs/src/modules/components/ExampleCollection.js"}} <br /> ## Official themes and templates Once you've chosen your preferred scaffold above, you could move on to the [Templates](/material-ui/getting-started/templates/) doc and choose a readymade user interface to plug in. For more complex prebuilt UIs, check out our [premium themes and templates](https://mui.com/store/?utm_source=docs&utm_medium=referral&utm_campaign=example-projects-store) in the MUI Store. ## Community projects The following projects are maintained by the community and curated by MUI. They're great resources for learning more about real-world usage of Material UI alongside other popular libraries and tools. ### Free - [GraphQL API and Relay Starter Kit](https://github.com/kriasoft/relay-starter-kit): - ![stars](https://img.shields.io/github/stars/kriasoft/graphql-starter.svg?style=social&label=Star) - GraphQL API project using code-first design (TypeScript, OAuth, GraphQL.js, Knex, Cloud SQL). - Web application project pre-configured with Webpack v5, TypeScript, React, Relay, Material UI. - Serverless deployment: `api` -> Cloud Functions, `web` -> Cloudflare Workers. - Client-side page routing/rendering at CDN edge locations, lazy loading. - Optimized for fast CI/CD builds and deployments using Yarn v2 monorepo design. - [React Admin](https://github.com/marmelab/react-admin) - ![stars](https://img.shields.io/github/stars/marmelab/react-admin.svg?style=social&label=Star) - A frontend framework for building B2B applications running in the browser. - On top of REST/GraphQL APIs, using ES6, React and Material Design. - [refine](https://github.com/refinedev/refine): - ![stars](https://img.shields.io/github/stars/refinedev/refine.svg?style=social&label=Star) - An open-source, headless, React-based framework for the rapid development of web applications that supports Vite, Next.js and Remix. - Designed for building data-intensive applications like admin panels, dashboards, and internal tools, but thanks to built-in SSR support, can also power customer-facing applications like storefronts. - Supports Material UI to generate a complete CRUD app that follows the Material Design guidelines and best practices. - Connectors for 15+ backend services, including REST API, GraphQL, NestJS, Airtable, Strapi, Supabase, Appwrite, Firebase, and Hasura. - Out-of-the-box support for live/real-time applications, audit logs, authentication, access control flows and i18n. - Advanced routing with any router library. - [React Most Wanted](https://github.com/TarikHuber/react-most-wanted): - ![stars](https://img.shields.io/github/stars/TarikHuber/react-most-wanted.svg?style=social&label=Star) - Created with Create React App. - Custom Create React App script to start a new project with just a single CLI command. - Build for Firebase including Authentication using the official Firebase Web Auth UI. - Routing with React Router including error handling (404) and lazy loading. - All PWA features included (SW, Notifications, deferred installation prompt, and more). - Optimized and scalable performance (all ~100 points on Lighthouse). - [React SaaS Template](https://github.com/dunky11/react-saas-template): - ![stars](https://img.shields.io/github/stars/dunky11/react-saas-template.svg?style=social&label=Star) - Created with Create React App. - Features a landing page, a blog, an area to login/register and an admin-dashboard. - Fully routed using react-router. - Lazy loads components to boost performance. - Components for statistics, text with emoji support, image upload, and more. ### Paid - [ScaffoldHub](https://scaffoldhub.io/?partner=1): - Tool for building web applications. - Choose your framework and library (React with Material UI). - Choose your database (SQL, MongoDB or Firestore). - Model your database and application with the intuitive GUI. - Generate your application, including a complete scaffolded backend. - Preview your application online, and download the generated code. - [Divjoy](https://divjoy.com?via=material-ui): - Create a Material UI app in minutes. - Templates, authentication, database integration, subscription payments, and more.
docs/data/material/getting-started/example-projects/example-projects.md
1
https://github.com/mui/material-ui/commit/e41667669bd16fb8736eb26aa4114ec220aac5c3
[ 0.0001679244014667347, 0.0001651491766097024, 0.00016044343647081405, 0.00016530317952856421, 0.0000018818565195033443 ]
{ "id": 6, "code_window": [ " ),\n", " );\n", "\n", " componentNames.forEach((componentName) => {\n", " const moduleID = path\n", " .join(this.rootContext, 'src', componentName.replace(/^docs\\/src/, ''))\n", " .replace(/\\\\/g, '/');\n", "\n", " components[moduleID] = componentName;\n", " componentModuleIDs.add(moduleID);\n", " });\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " const moduleID = path.join(this.rootContext, 'src', componentName).replace(/\\\\/g, '/');\n" ], "file_path": "packages/markdown/loader.js", "type": "replace", "edit_start_line_idx": 374 }
"use strict"; "use client"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon")); var _jsxRuntime = require("react/jsx-runtime"); var _default = (0, _createSvgIcon.default)([/*#__PURE__*/(0, _jsxRuntime.jsx)("circle", { cx: "14.5", cy: "10.5", r: "1.25" }, "0"), /*#__PURE__*/(0, _jsxRuntime.jsx)("circle", { cx: "9.5", cy: "10.5", r: "1.25" }, "1"), /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M16.1 14H7.9c-.19 0-.32.2-.23.37C8.5 15.94 10.13 17 12 17s3.5-1.06 4.33-2.63c.08-.17-.05-.37-.23-.37zm6.84-2.66c-.25-1.51-1.36-2.74-2.81-3.17-.53-1.12-1.28-2.1-2.19-2.91C16.36 3.85 14.28 3 12 3s-4.36.85-5.94 2.26c-.92.81-1.67 1.8-2.19 2.91-1.45.43-2.56 1.65-2.81 3.17-.04.21-.06.43-.06.66 0 .23.02.45.06.66.25 1.51 1.36 2.74 2.81 3.17.52 1.11 1.27 2.09 2.17 2.89C7.62 20.14 9.71 21 12 21s4.38-.86 5.97-2.28c.9-.8 1.65-1.79 2.17-2.89 1.44-.43 2.55-1.65 2.8-3.17.04-.21.06-.43.06-.66 0-.23-.02-.45-.06-.66zM19 14c-.1 0-.19-.02-.29-.03-.2.67-.49 1.29-.86 1.86C16.6 17.74 14.45 19 12 19s-4.6-1.26-5.85-3.17c-.37-.57-.66-1.19-.86-1.86-.1.01-.19.03-.29.03-1.1 0-2-.9-2-2s.9-2 2-2c.1 0 .19.02.29.03.2-.67.49-1.29.86-1.86C7.4 6.26 9.55 5 12 5s4.6 1.26 5.85 3.17c.37.57.66 1.19.86 1.86.1-.01.19-.03.29-.03 1.1 0 2 .9 2 2s-.9 2-2 2z" }, "2")], 'ChildCareRounded'); exports.default = _default;
packages/mui-icons-material/lib/ChildCareRounded.js
0
https://github.com/mui/material-ui/commit/e41667669bd16fb8736eb26aa4114ec220aac5c3
[ 0.00020145525922998786, 0.00018402666319161654, 0.00017479198868386447, 0.00017583274166099727, 0.000012331201105553191 ]
{ "id": 6, "code_window": [ " ),\n", " );\n", "\n", " componentNames.forEach((componentName) => {\n", " const moduleID = path\n", " .join(this.rootContext, 'src', componentName.replace(/^docs\\/src/, ''))\n", " .replace(/\\\\/g, '/');\n", "\n", " components[moduleID] = componentName;\n", " componentModuleIDs.add(moduleID);\n", " });\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " const moduleID = path.join(this.rootContext, 'src', componentName).replace(/\\\\/g, '/');\n" ], "file_path": "packages/markdown/loader.js", "type": "replace", "edit_start_line_idx": 374 }
<svg xmlns="http://www.w3.org/2000/svg" enable-background="new 0 0 24 24" height="24" viewBox="0 0 24 24" width="24"><g><rect fill="none" height="24" width="24"/></g><g><path d="M4,7.59l6.41-6.41L20.24,11h-2.83L10.4,4L5.41,9H8v2H2V5h2V7.59z M20,19h2v-6h-6v2h2.59l-4.99,5l-7.01-7H3.76l9.83,9.83 L20,16.41V19z"/></g></svg>
packages/mui-icons-material/material-icons/screen_rotation_alt_sharp_24px.svg
0
https://github.com/mui/material-ui/commit/e41667669bd16fb8736eb26aa4114ec220aac5c3
[ 0.0001734944962663576, 0.0001734944962663576, 0.0001734944962663576, 0.0001734944962663576, 0 ]
{ "id": 6, "code_window": [ " ),\n", " );\n", "\n", " componentNames.forEach((componentName) => {\n", " const moduleID = path\n", " .join(this.rootContext, 'src', componentName.replace(/^docs\\/src/, ''))\n", " .replace(/\\\\/g, '/');\n", "\n", " components[moduleID] = componentName;\n", " componentModuleIDs.add(moduleID);\n", " });\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " const moduleID = path.join(this.rootContext, 'src', componentName).replace(/\\\\/g, '/');\n" ], "file_path": "packages/markdown/loader.js", "type": "replace", "edit_start_line_idx": 374 }
{ "componentDescription": "", "propDescriptions": { "allowSwipeInChildren": { "description": "If set to true, the swipe event will open the drawer even if the user begins the swipe on one of the drawer&#39;s children. This can be useful in scenarios where the drawer is partially visible. You can customize it further with a callback that determines which children the user can drag over to open the drawer (for example, to ignore other elements that handle touch move events, like sliders)." }, "children": { "description": "The content of the component." }, "disableBackdropTransition": { "description": "Disable the backdrop transition. This can improve the FPS on low-end devices." }, "disableDiscovery": { "description": "If <code>true</code>, touching the screen near the edge of the drawer will not slide in the drawer a bit to promote accidental discovery of the swipe gesture." }, "disableSwipeToOpen": { "description": "If <code>true</code>, swipe to open is disabled. This is useful in browsers where swiping triggers navigation actions. Swipe to open is disabled on iOS browsers by default." }, "hysteresis": { "description": "Affects how far the drawer must be opened/closed to change its state. Specified as percent (0-1) of the width of the drawer" }, "minFlingVelocity": { "description": "Defines, from which (average) velocity on, the swipe is defined as complete although hysteresis isn&#39;t reached. Good threshold is between 250 - 1000 px/s" }, "onClose": { "description": "Callback fired when the component requests to be closed.", "typeDescriptions": { "event": "The event source of the callback." } }, "onOpen": { "description": "Callback fired when the component requests to be opened.", "typeDescriptions": { "event": "The event source of the callback." } }, "open": { "description": "If <code>true</code>, the component is shown." }, "SwipeAreaProps": { "description": "The element is used to intercept the touch events on the edge." }, "swipeAreaWidth": { "description": "The width of the left most (or right most) area in <code>px</code> that the drawer can be swiped open from." }, "transitionDuration": { "description": "The duration for the transition, in milliseconds. You may specify a single timeout for all transitions, or individually with an object." } }, "classDescriptions": {} }
docs/translations/api-docs/swipeable-drawer/swipeable-drawer.json
0
https://github.com/mui/material-ui/commit/e41667669bd16fb8736eb26aa4114ec220aac5c3
[ 0.00017414138710591942, 0.00016894117288757116, 0.0001657971879467368, 0.00016784132458269596, 0.000002817450649672537 ]
{ "id": 0, "code_window": [ " displayName: 'Update the project level settings',\n", " pluginName: 'admin',\n", " section: 'settings',\n", " category: 'project',\n", " },\n", " ],\n", "};" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep" ], "after_edit": [ " {\n", " uid: 'project-settings.read',\n", " displayName: 'Read the project level settings',\n", " pluginName: 'admin',\n", " section: 'settings',\n", " category: 'project',\n", " },\n" ], "file_path": "packages/core/admin/server/config/admin-actions.js", "type": "add", "edit_start_line_idx": 155 }
'use strict'; const _ = require('lodash'); const { createAuthRequest } = require('../../../../../test/helpers/request'); const { createStrapiInstance } = require('../../../../../test/helpers/strapi'); const edition = process.env.STRAPI_DISABLE_EE === 'true' ? 'CE' : 'EE'; describe('Role CRUD End to End', () => { let rq; let strapi; beforeAll(async () => { strapi = await createStrapiInstance(); rq = await createAuthRequest({ strapi }); }); afterAll(async () => { await strapi.destroy(); }); test('Can get the existing permissions', async () => { let res = await rq({ url: '/admin/permissions', method: 'GET', }); expect(res.statusCode).toBe(200); // Data is sorted to avoid error with snapshot when the data is not in the same order const sortedData = _.cloneDeep(res.body.data); Object.keys(sortedData.sections).forEach(sectionName => { sortedData.sections[sectionName] = _.sortBy(sortedData.sections[sectionName], ['action']); }); sortedData.conditions = sortedData.conditions.sort(); if (edition === 'CE') { expect(sortedData).toMatchInlineSnapshot(` Object { "conditions": Array [ Object { "category": "default", "displayName": "Is creator", "id": "admin::is-creator", }, Object { "category": "default", "displayName": "Has same role as creator", "id": "admin::has-same-role-as-creator", }, ], "sections": Object { "collectionTypes": Array [ Array [ Object { "actionId": "plugin::content-manager.explorer.create", "applyToProperties": Array [ "fields", "locales", ], "label": "Create", "subjects": Array [ "plugin::users-permissions.user", ], }, Object { "actionId": "plugin::content-manager.explorer.read", "applyToProperties": Array [ "fields", "locales", ], "label": "Read", "subjects": Array [ "plugin::users-permissions.user", ], }, Object { "actionId": "plugin::content-manager.explorer.update", "applyToProperties": Array [ "fields", "locales", ], "label": "Update", "subjects": Array [ "plugin::users-permissions.user", ], }, Object { "actionId": "plugin::content-manager.explorer.delete", "applyToProperties": Array [ "locales", ], "label": "Delete", "subjects": Array [ "plugin::users-permissions.user", ], }, Object { "actionId": "plugin::content-manager.explorer.publish", "applyToProperties": Array [ "locales", ], "label": "Publish", "subjects": Array [], }, ], Array [ Object { "label": "user", "properties": Array [ Object { "children": Array [ Object { "label": "username", "required": true, "value": "username", }, Object { "label": "email", "required": true, "value": "email", }, Object { "label": "provider", "value": "provider", }, Object { "label": "password", "value": "password", }, Object { "label": "resetPasswordToken", "value": "resetPasswordToken", }, Object { "label": "confirmationToken", "value": "confirmationToken", }, Object { "label": "confirmed", "value": "confirmed", }, Object { "label": "blocked", "value": "blocked", }, Object { "label": "role", "value": "role", }, ], "label": "Fields", "value": "fields", }, ], "uid": "plugin::users-permissions.user", }, ], ], "plugins": Array [ Object { "action": "plugin::content-manager.collection-types.configure-view", "displayName": "Configure view", "plugin": "content-manager", "subCategory": "collection types", }, Object { "action": "plugin::content-manager.components.configure-layout", "displayName": "Configure Layout", "plugin": "content-manager", "subCategory": "components", }, Object { "action": "plugin::content-manager.single-types.configure-view", "displayName": "Configure view", "plugin": "content-manager", "subCategory": "single types", }, Object { "action": "plugin::content-type-builder.read", "displayName": "Read", "plugin": "content-type-builder", "subCategory": "general", }, Object { "action": "plugin::documentation.read", "displayName": "Access the Documentation", "plugin": "documentation", "subCategory": "general", }, Object { "action": "plugin::documentation.settings.regenerate", "displayName": "Regenerate", "plugin": "documentation", "subCategory": "general", }, Object { "action": "plugin::documentation.settings.update", "displayName": "Update and delete", "plugin": "documentation", "subCategory": "general", }, Object { "action": "plugin::upload.assets.copy-link", "displayName": "Copy link", "plugin": "upload", "subCategory": "assets", }, Object { "action": "plugin::upload.assets.create", "displayName": "Create (upload)", "plugin": "upload", "subCategory": "assets", }, Object { "action": "plugin::upload.assets.download", "displayName": "Download", "plugin": "upload", "subCategory": "assets", }, Object { "action": "plugin::upload.assets.update", "displayName": "Update (crop, details, replace) + delete", "plugin": "upload", "subCategory": "assets", }, Object { "action": "plugin::upload.read", "displayName": "Access the Media Library", "plugin": "upload", "subCategory": "general", }, Object { "action": "plugin::users-permissions.advanced-settings.read", "displayName": "Read", "plugin": "users-permissions", "subCategory": "advancedSettings", }, Object { "action": "plugin::users-permissions.advanced-settings.update", "displayName": "Edit", "plugin": "users-permissions", "subCategory": "advancedSettings", }, Object { "action": "plugin::users-permissions.email-templates.read", "displayName": "Read", "plugin": "users-permissions", "subCategory": "emailTemplates", }, Object { "action": "plugin::users-permissions.email-templates.update", "displayName": "Edit", "plugin": "users-permissions", "subCategory": "emailTemplates", }, Object { "action": "plugin::users-permissions.providers.read", "displayName": "Read", "plugin": "users-permissions", "subCategory": "providers", }, Object { "action": "plugin::users-permissions.providers.update", "displayName": "Edit", "plugin": "users-permissions", "subCategory": "providers", }, Object { "action": "plugin::users-permissions.roles.create", "displayName": "Create", "plugin": "users-permissions", "subCategory": "roles", }, Object { "action": "plugin::users-permissions.roles.delete", "displayName": "Delete", "plugin": "users-permissions", "subCategory": "roles", }, Object { "action": "plugin::users-permissions.roles.read", "displayName": "Read", "plugin": "users-permissions", "subCategory": "roles", }, Object { "action": "plugin::users-permissions.roles.update", "displayName": "Update", "plugin": "users-permissions", "subCategory": "roles", }, ], "settings": Array [ Object { "action": "admin::api-tokens.create", "category": "api tokens", "displayName": "Create (generate)", "subCategory": "general", }, Object { "action": "admin::api-tokens.delete", "category": "api tokens", "displayName": "Delete (revoke)", "subCategory": "general", }, Object { "action": "admin::api-tokens.read", "category": "api tokens", "displayName": "Read", "subCategory": "general", }, Object { "action": "admin::api-tokens.update", "category": "api tokens", "displayName": "Update", "subCategory": "general", }, Object { "action": "admin::marketplace.plugins.install", "category": "plugins and marketplace", "displayName": "Install (only for dev env)", "subCategory": "plugins", }, Object { "action": "admin::marketplace.plugins.uninstall", "category": "plugins and marketplace", "displayName": "Uninstall (only for dev env)", "subCategory": "plugins", }, Object { "action": "admin::marketplace.read", "category": "plugins and marketplace", "displayName": "Access the marketplace", "subCategory": "marketplace", }, Object { "action": "admin::project-settings.update", "category": "project", "displayName": "Update the project level settings", "subCategory": "general", }, Object { "action": "admin::roles.create", "category": "users and roles", "displayName": "Create", "subCategory": "roles", }, Object { "action": "admin::roles.delete", "category": "users and roles", "displayName": "Delete", "subCategory": "roles", }, Object { "action": "admin::roles.read", "category": "users and roles", "displayName": "Read", "subCategory": "roles", }, Object { "action": "admin::roles.update", "category": "users and roles", "displayName": "Update", "subCategory": "roles", }, Object { "action": "admin::users.create", "category": "users and roles", "displayName": "Create (invite)", "subCategory": "users", }, Object { "action": "admin::users.delete", "category": "users and roles", "displayName": "Delete", "subCategory": "users", }, Object { "action": "admin::users.read", "category": "users and roles", "displayName": "Read", "subCategory": "users", }, Object { "action": "admin::users.update", "category": "users and roles", "displayName": "Update", "subCategory": "users", }, Object { "action": "admin::webhooks.create", "category": "webhooks", "displayName": "Create", "subCategory": "general", }, Object { "action": "admin::webhooks.delete", "category": "webhooks", "displayName": "Delete", "subCategory": "general", }, Object { "action": "admin::webhooks.read", "category": "webhooks", "displayName": "Read", "subCategory": "general", }, Object { "action": "admin::webhooks.update", "category": "webhooks", "displayName": "Update", "subCategory": "general", }, Object { "action": "plugin::documentation.settings.read", "category": "documentation", "displayName": "Access the documentation settings page", "subCategory": "general", }, Object { "action": "plugin::email.settings.read", "category": "email", "displayName": "Access the Email Settings page", "subCategory": "general", }, Object { "action": "plugin::i18n.locale.create", "category": "Internationalization", "displayName": "Create", "subCategory": "Locales", }, Object { "action": "plugin::i18n.locale.delete", "category": "Internationalization", "displayName": "Delete", "subCategory": "Locales", }, Object { "action": "plugin::i18n.locale.read", "category": "Internationalization", "displayName": "Read", "subCategory": "Locales", }, Object { "action": "plugin::i18n.locale.update", "category": "Internationalization", "displayName": "Update", "subCategory": "Locales", }, Object { "action": "plugin::upload.settings.read", "category": "media library", "displayName": "Access the Media Library settings page", "subCategory": "general", }, ], "singleTypes": Array [ Array [ Object { "actionId": "plugin::content-manager.explorer.create", "applyToProperties": Array [ "fields", "locales", ], "label": "Create", "subjects": Array [ "plugin::users-permissions.user", ], }, Object { "actionId": "plugin::content-manager.explorer.read", "applyToProperties": Array [ "fields", "locales", ], "label": "Read", "subjects": Array [ "plugin::users-permissions.user", ], }, Object { "actionId": "plugin::content-manager.explorer.update", "applyToProperties": Array [ "fields", "locales", ], "label": "Update", "subjects": Array [ "plugin::users-permissions.user", ], }, Object { "actionId": "plugin::content-manager.explorer.delete", "applyToProperties": Array [ "locales", ], "label": "Delete", "subjects": Array [ "plugin::users-permissions.user", ], }, Object { "actionId": "plugin::content-manager.explorer.publish", "applyToProperties": Array [ "locales", ], "label": "Publish", "subjects": Array [], }, ], Array [], ], }, } `); } else { // eslint-disable-next-line node/no-extraneous-require const { features } = require('@strapi/strapi/lib/utils/ee'); const hasSSO = features.isEnabled('sso'); if (hasSSO) { expect(sortedData).toMatchInlineSnapshot(` Object { "conditions": Array [ Object { "category": "default", "displayName": "Is creator", "id": "admin::is-creator", }, Object { "category": "default", "displayName": "Has same role as creator", "id": "admin::has-same-role-as-creator", }, ], "sections": Object { "collectionTypes": Array [ Array [ Object { "actionId": "plugin::content-manager.explorer.create", "applyToProperties": Array [ "fields", "locales", ], "label": "Create", "subjects": Array [ "plugin::users-permissions.user", ], }, Object { "actionId": "plugin::content-manager.explorer.read", "applyToProperties": Array [ "fields", "locales", ], "label": "Read", "subjects": Array [ "plugin::users-permissions.user", ], }, Object { "actionId": "plugin::content-manager.explorer.update", "applyToProperties": Array [ "fields", "locales", ], "label": "Update", "subjects": Array [ "plugin::users-permissions.user", ], }, Object { "actionId": "plugin::content-manager.explorer.delete", "applyToProperties": Array [ "locales", ], "label": "Delete", "subjects": Array [ "plugin::users-permissions.user", ], }, Object { "actionId": "plugin::content-manager.explorer.publish", "applyToProperties": Array [ "locales", ], "label": "Publish", "subjects": Array [], }, ], Array [ Object { "label": "user", "properties": Array [ Object { "children": Array [ Object { "label": "username", "required": true, "value": "username", }, Object { "label": "email", "required": true, "value": "email", }, Object { "label": "provider", "value": "provider", }, Object { "label": "password", "value": "password", }, Object { "label": "resetPasswordToken", "value": "resetPasswordToken", }, Object { "label": "confirmationToken", "value": "confirmationToken", }, Object { "label": "confirmed", "value": "confirmed", }, Object { "label": "blocked", "value": "blocked", }, Object { "label": "role", "value": "role", }, ], "label": "Fields", "value": "fields", }, ], "uid": "plugin::users-permissions.user", }, ], ], "plugins": Array [ Object { "action": "plugin::content-manager.collection-types.configure-view", "displayName": "Configure view", "plugin": "content-manager", "subCategory": "collection types", }, Object { "action": "plugin::content-manager.components.configure-layout", "displayName": "Configure Layout", "plugin": "content-manager", "subCategory": "components", }, Object { "action": "plugin::content-manager.single-types.configure-view", "displayName": "Configure view", "plugin": "content-manager", "subCategory": "single types", }, Object { "action": "plugin::content-type-builder.read", "displayName": "Read", "plugin": "content-type-builder", "subCategory": "general", }, Object { "action": "plugin::documentation.read", "displayName": "Access the Documentation", "plugin": "documentation", "subCategory": "general", }, Object { "action": "plugin::documentation.settings.regenerate", "displayName": "Regenerate", "plugin": "documentation", "subCategory": "general", }, Object { "action": "plugin::documentation.settings.update", "displayName": "Update and delete", "plugin": "documentation", "subCategory": "general", }, Object { "action": "plugin::upload.assets.copy-link", "displayName": "Copy link", "plugin": "upload", "subCategory": "assets", }, Object { "action": "plugin::upload.assets.create", "displayName": "Create (upload)", "plugin": "upload", "subCategory": "assets", }, Object { "action": "plugin::upload.assets.download", "displayName": "Download", "plugin": "upload", "subCategory": "assets", }, Object { "action": "plugin::upload.assets.update", "displayName": "Update (crop, details, replace) + delete", "plugin": "upload", "subCategory": "assets", }, Object { "action": "plugin::upload.read", "displayName": "Access the Media Library", "plugin": "upload", "subCategory": "general", }, Object { "action": "plugin::users-permissions.advanced-settings.read", "displayName": "Read", "plugin": "users-permissions", "subCategory": "advancedSettings", }, Object { "action": "plugin::users-permissions.advanced-settings.update", "displayName": "Edit", "plugin": "users-permissions", "subCategory": "advancedSettings", }, Object { "action": "plugin::users-permissions.email-templates.read", "displayName": "Read", "plugin": "users-permissions", "subCategory": "emailTemplates", }, Object { "action": "plugin::users-permissions.email-templates.update", "displayName": "Edit", "plugin": "users-permissions", "subCategory": "emailTemplates", }, Object { "action": "plugin::users-permissions.providers.read", "displayName": "Read", "plugin": "users-permissions", "subCategory": "providers", }, Object { "action": "plugin::users-permissions.providers.update", "displayName": "Edit", "plugin": "users-permissions", "subCategory": "providers", }, Object { "action": "plugin::users-permissions.roles.create", "displayName": "Create", "plugin": "users-permissions", "subCategory": "roles", }, Object { "action": "plugin::users-permissions.roles.delete", "displayName": "Delete", "plugin": "users-permissions", "subCategory": "roles", }, Object { "action": "plugin::users-permissions.roles.read", "displayName": "Read", "plugin": "users-permissions", "subCategory": "roles", }, Object { "action": "plugin::users-permissions.roles.update", "displayName": "Update", "plugin": "users-permissions", "subCategory": "roles", }, ], "settings": Array [ Object { "action": "admin::api-tokens.create", "category": "api tokens", "displayName": "Create (generate)", "subCategory": "general", }, Object { "action": "admin::api-tokens.delete", "category": "api tokens", "displayName": "Delete (revoke)", "subCategory": "general", }, Object { "action": "admin::api-tokens.read", "category": "api tokens", "displayName": "Read", "subCategory": "general", }, Object { "action": "admin::api-tokens.update", "category": "api tokens", "displayName": "Update", "subCategory": "general", }, Object { "action": "admin::marketplace.plugins.install", "category": "plugins and marketplace", "displayName": "Install (only for dev env)", "subCategory": "plugins", }, Object { "action": "admin::marketplace.plugins.uninstall", "category": "plugins and marketplace", "displayName": "Uninstall (only for dev env)", "subCategory": "plugins", }, Object { "action": "admin::marketplace.read", "category": "plugins and marketplace", "displayName": "Access the marketplace", "subCategory": "marketplace", }, Object { "action": "admin::project-settings.update", "category": "project", "displayName": "Update the project level settings", "subCategory": "general", }, Object { "action": "admin::provider-login.read", "category": "single sign on", "displayName": "Read", "subCategory": "options", }, Object { "action": "admin::provider-login.update", "category": "single sign on", "displayName": "Update", "subCategory": "options", }, Object { "action": "admin::roles.create", "category": "users and roles", "displayName": "Create", "subCategory": "roles", }, Object { "action": "admin::roles.delete", "category": "users and roles", "displayName": "Delete", "subCategory": "roles", }, Object { "action": "admin::roles.read", "category": "users and roles", "displayName": "Read", "subCategory": "roles", }, Object { "action": "admin::roles.update", "category": "users and roles", "displayName": "Update", "subCategory": "roles", }, Object { "action": "admin::users.create", "category": "users and roles", "displayName": "Create (invite)", "subCategory": "users", }, Object { "action": "admin::users.delete", "category": "users and roles", "displayName": "Delete", "subCategory": "users", }, Object { "action": "admin::users.read", "category": "users and roles", "displayName": "Read", "subCategory": "users", }, Object { "action": "admin::users.update", "category": "users and roles", "displayName": "Update", "subCategory": "users", }, Object { "action": "admin::webhooks.create", "category": "webhooks", "displayName": "Create", "subCategory": "general", }, Object { "action": "admin::webhooks.delete", "category": "webhooks", "displayName": "Delete", "subCategory": "general", }, Object { "action": "admin::webhooks.read", "category": "webhooks", "displayName": "Read", "subCategory": "general", }, Object { "action": "admin::webhooks.update", "category": "webhooks", "displayName": "Update", "subCategory": "general", }, Object { "action": "plugin::documentation.settings.read", "category": "documentation", "displayName": "Access the documentation settings page", "subCategory": "general", }, Object { "action": "plugin::email.settings.read", "category": "email", "displayName": "Access the Email Settings page", "subCategory": "general", }, Object { "action": "plugin::i18n.locale.create", "category": "Internationalization", "displayName": "Create", "subCategory": "Locales", }, Object { "action": "plugin::i18n.locale.delete", "category": "Internationalization", "displayName": "Delete", "subCategory": "Locales", }, Object { "action": "plugin::i18n.locale.read", "category": "Internationalization", "displayName": "Read", "subCategory": "Locales", }, Object { "action": "plugin::i18n.locale.update", "category": "Internationalization", "displayName": "Update", "subCategory": "Locales", }, Object { "action": "plugin::upload.settings.read", "category": "media library", "displayName": "Access the Media Library settings page", "subCategory": "general", }, ], "singleTypes": Array [ Array [ Object { "actionId": "plugin::content-manager.explorer.create", "applyToProperties": Array [ "fields", "locales", ], "label": "Create", "subjects": Array [ "plugin::users-permissions.user", ], }, Object { "actionId": "plugin::content-manager.explorer.read", "applyToProperties": Array [ "fields", "locales", ], "label": "Read", "subjects": Array [ "plugin::users-permissions.user", ], }, Object { "actionId": "plugin::content-manager.explorer.update", "applyToProperties": Array [ "fields", "locales", ], "label": "Update", "subjects": Array [ "plugin::users-permissions.user", ], }, Object { "actionId": "plugin::content-manager.explorer.delete", "applyToProperties": Array [ "locales", ], "label": "Delete", "subjects": Array [ "plugin::users-permissions.user", ], }, Object { "actionId": "plugin::content-manager.explorer.publish", "applyToProperties": Array [ "locales", ], "label": "Publish", "subjects": Array [], }, ], Array [], ], }, } `); } else { expect(sortedData).toMatchInlineSnapshot(` Object { "conditions": Array [ Object { "category": "default", "displayName": "Is creator", "id": "admin::is-creator", }, Object { "category": "default", "displayName": "Has same role as creator", "id": "admin::has-same-role-as-creator", }, ], "sections": Object { "contentTypes": Array [ Object { "action": "plugin::content-manager.explorer.create", "displayName": "Create", "subjects": Array [ "plugin::users-permissions.user", ], }, Object { "action": "plugin::content-manager.explorer.delete", "displayName": "Delete", "subjects": Array [ "plugin::users-permissions.user", ], }, Object { "action": "plugin::content-manager.explorer.publish", "displayName": "Publish", "subjects": Array [], }, Object { "action": "plugin::content-manager.explorer.read", "displayName": "Read", "subjects": Array [ "plugin::users-permissions.user", ], }, Object { "action": "plugin::content-manager.explorer.update", "displayName": "Update", "subjects": Array [ "plugin::users-permissions.user", ], }, ], "plugins": Array [ Object { "action": "plugin::content-manager.collection-types.configure-view", "displayName": "Configure view", "plugin": "plugin::content-manager", "subCategory": "collection types", }, Object { "action": "plugin::content-manager.components.configure-layout", "displayName": "Configure Layout", "plugin": "plugin::content-manager", "subCategory": "components", }, Object { "action": "plugin::content-manager.single-types.configure-view", "displayName": "Configure view", "plugin": "plugin::content-manager", "subCategory": "single types", }, Object { "action": "plugin::content-type-builder.read", "displayName": "Read", "plugin": "plugin::content-type-builder", "subCategory": "general", }, Object { "action": "plugin::documentation.read", "displayName": "Access the Documentation", "plugin": "plugin::documentation", "subCategory": "general", }, Object { "action": "plugin::documentation.settings.regenerate", "displayName": "Regenerate", "plugin": "plugin::documentation", "subCategory": "settings", }, Object { "action": "plugin::documentation.settings.update", "displayName": "Update and delete", "plugin": "plugin::documentation", "subCategory": "settings", }, Object { "action": "plugin::upload.assets.copy-link", "displayName": "Copy link", "plugin": "plugin::upload", "subCategory": "assets", }, Object { "action": "plugin::upload.assets.create", "displayName": "Create (upload)", "plugin": "plugin::upload", "subCategory": "assets", }, Object { "action": "plugin::upload.assets.download", "displayName": "Download", "plugin": "plugin::upload", "subCategory": "assets", }, Object { "action": "plugin::upload.assets.update", "displayName": "Update (crop, details, replace) + delete", "plugin": "plugin::upload", "subCategory": "assets", }, Object { "action": "plugin::upload.read", "displayName": "Access the Media Library", "plugin": "plugin::upload", "subCategory": "general", }, Object { "action": "plugin::users-permissions.advanced-settings.read", "displayName": "Read", "plugin": "plugin::users-permissions", "subCategory": "advancedSettings", }, Object { "action": "plugin::users-permissions.advanced-settings.update", "displayName": "Edit", "plugin": "plugin::users-permissions", "subCategory": "advancedSettings", }, Object { "action": "plugin::users-permissions.email-templates.read", "displayName": "Read", "plugin": "plugin::users-permissions", "subCategory": "emailTemplates", }, Object { "action": "plugin::users-permissions.email-templates.update", "displayName": "Edit", "plugin": "plugin::users-permissions", "subCategory": "emailTemplates", }, Object { "action": "plugin::users-permissions.providers.read", "displayName": "Read", "plugin": "plugin::users-permissions", "subCategory": "providers", }, Object { "action": "plugin::users-permissions.providers.update", "displayName": "Edit", "plugin": "plugin::users-permissions", "subCategory": "providers", }, Object { "action": "plugin::users-permissions.roles.create", "displayName": "Create", "plugin": "plugin::users-permissions", "subCategory": "roles", }, Object { "action": "plugin::users-permissions.roles.delete", "displayName": "Delete", "plugin": "plugin::users-permissions", "subCategory": "roles", }, Object { "action": "plugin::users-permissions.roles.read", "displayName": "Read", "plugin": "plugin::users-permissions", "subCategory": "roles", }, Object { "action": "plugin::users-permissions.roles.update", "displayName": "Update", "plugin": "plugin::users-permissions", "subCategory": "roles", }, ], "settings": Array [ Object { "action": "admin::api-tokens.create", "category": "api tokens", "displayName": "Create (generate)", "subCategory": "general", }, Object { "action": "admin::api-tokens.delete", "category": "api tokens", "displayName": "Delete (revoke)", "subCategory": "general", }, Object { "action": "admin::api-tokens.read", "category": "api tokens", "displayName": "Read", "subCategory": "general", }, Object { "action": "admin::api-tokens.update", "category": "api tokens", "displayName": "Update", "subCategory": "general", }, Object { "action": "admin::marketplace.plugins.install", "category": "plugins and marketplace", "displayName": "Install (only for dev env)", "subCategory": "plugins", }, Object { "action": "admin::marketplace.plugins.uninstall", "category": "plugins and marketplace", "displayName": "Uninstall (only for dev env)", "subCategory": "plugins", }, Object { "action": "admin::marketplace.read", "category": "plugins and marketplace", "displayName": "Access the marketplace", "subCategory": "marketplace", }, Object { "action": "admin::project-settings.update", "category": "project", "displayName": "Update the project level settings", "subCategory": "general", }, Object { "action": "admin::roles.create", "category": "users and roles", "displayName": "Create", "subCategory": "roles", }, Object { "action": "admin::roles.delete", "category": "users and roles", "displayName": "Delete", "subCategory": "roles", }, Object { "action": "admin::roles.read", "category": "users and roles", "displayName": "Read", "subCategory": "roles", }, Object { "action": "admin::roles.update", "category": "users and roles", "displayName": "Update", "subCategory": "roles", }, Object { "action": "admin::users.create", "category": "users and roles", "displayName": "Create (invite)", "subCategory": "users", }, Object { "action": "admin::users.delete", "category": "users and roles", "displayName": "Delete", "subCategory": "users", }, Object { "action": "admin::users.read", "category": "users and roles", "displayName": "Read", "subCategory": "users", }, Object { "action": "admin::users.update", "category": "users and roles", "displayName": "Update", "subCategory": "users", }, Object { "action": "admin::webhooks.create", "category": "webhooks", "displayName": "Create", "subCategory": "general", }, Object { "action": "admin::webhooks.delete", "category": "webhooks", "displayName": "Delete", "subCategory": "general", }, Object { "action": "admin::webhooks.read", "category": "webhooks", "displayName": "Read", "subCategory": "general", }, Object { "action": "admin::webhooks.update", "category": "webhooks", "displayName": "Update", "subCategory": "general", }, Object { "action": "plugin::email.settings.read", "category": "email", "displayName": "Access the Email Settings page", "subCategory": "general", }, Object { "action": "plugin::upload.settings.read", "category": "media library", "displayName": "Access the Media Library settings page", "subCategory": "general", }, ], }, } `); } } }); });
packages/core/admin/server/tests/admin-permission.test.e2e.js
1
https://github.com/strapi/strapi/commit/ce181eccf0a12a47c1e77517ffe0650a1cefe4ba
[ 0.004847587086260319, 0.0002771936124190688, 0.00016216591757256538, 0.00016836867143865675, 0.000544863345567137 ]
{ "id": 0, "code_window": [ " displayName: 'Update the project level settings',\n", " pluginName: 'admin',\n", " section: 'settings',\n", " category: 'project',\n", " },\n", " ],\n", "};" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep" ], "after_edit": [ " {\n", " uid: 'project-settings.read',\n", " displayName: 'Read the project level settings',\n", " pluginName: 'admin',\n", " section: 'settings',\n", " category: 'project',\n", " },\n" ], "file_path": "packages/core/admin/server/config/admin-actions.js", "type": "add", "edit_start_line_idx": 155 }
import React from 'react'; import PropTypes from 'prop-types'; const Cross = ({ fill, height, width, ...rest }) => { return ( <svg {...rest} width={width} height={height} xmlns="http://www.w3.org/2000/svg"> <path d="M7.78 6.72L5.06 4l2.72-2.72a.748.748 0 0 0 0-1.06.748.748 0 0 0-1.06 0L4 2.94 1.28.22a.748.748 0 0 0-1.06 0 .748.748 0 0 0 0 1.06L2.94 4 .22 6.72a.748.748 0 0 0 0 1.06.748.748 0 0 0 1.06 0L4 5.06l2.72 2.72a.748.748 0 0 0 1.06 0 .752.752 0 0 0 0-1.06z" fill={fill} fillRule="evenodd" /> </svg> ); }; Cross.defaultProps = { fill: '#b3b5b9', height: '8', width: '8', }; Cross.propTypes = { fill: PropTypes.string, height: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), width: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), }; export default Cross;
packages/core/admin/admin/src/content-manager/icons/Cross/index.js
0
https://github.com/strapi/strapi/commit/ce181eccf0a12a47c1e77517ffe0650a1cefe4ba
[ 0.0001748781796777621, 0.0001740297448122874, 0.00017331972776446491, 0.00017389132699463516, 6.43719772597251e-7 ]
{ "id": 0, "code_window": [ " displayName: 'Update the project level settings',\n", " pluginName: 'admin',\n", " section: 'settings',\n", " category: 'project',\n", " },\n", " ],\n", "};" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep" ], "after_edit": [ " {\n", " uid: 'project-settings.read',\n", " displayName: 'Read the project level settings',\n", " pluginName: 'admin',\n", " section: 'settings',\n", " category: 'project',\n", " },\n" ], "file_path": "packages/core/admin/server/config/admin-actions.js", "type": "add", "edit_start_line_idx": 155 }
import React from 'react'; import { useFocusWhenNavigate, NoPermissions as NoPermissionsCompo } from '@strapi/helper-plugin'; import { Main } from '@strapi/design-system/Main'; import { ContentLayout, HeaderLayout } from '@strapi/design-system/Layout'; import { useIntl } from 'react-intl'; import { getTrad } from '../../utils'; const NoPermissions = () => { const { formatMessage } = useIntl(); useFocusWhenNavigate(); return ( <Main> <HeaderLayout title={formatMessage({ id: getTrad('header.name'), defaultMessage: 'Content', })} /> <ContentLayout> <NoPermissionsCompo /> </ContentLayout> </Main> ); }; export default NoPermissions;
packages/core/admin/admin/src/content-manager/pages/NoPermissions/index.js
0
https://github.com/strapi/strapi/commit/ce181eccf0a12a47c1e77517ffe0650a1cefe4ba
[ 0.00017533314530737698, 0.00017073545313905925, 0.000167596954270266, 0.00016927624528761953, 0.0000033225610422960017 ]
{ "id": 0, "code_window": [ " displayName: 'Update the project level settings',\n", " pluginName: 'admin',\n", " section: 'settings',\n", " category: 'project',\n", " },\n", " ],\n", "};" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep" ], "after_edit": [ " {\n", " uid: 'project-settings.read',\n", " displayName: 'Read the project level settings',\n", " pluginName: 'admin',\n", " section: 'settings',\n", " category: 'project',\n", " },\n" ], "file_path": "packages/core/admin/server/config/admin-actions.js", "type": "add", "edit_start_line_idx": 155 }
import React from 'react'; function connect(WrappedComponent, select) { return function(props) { const selectors = select(props); return <WrappedComponent {...props} {...selectors} />; }; } export default connect;
packages/core/admin/admin/src/content-manager/components/RepeatableComponent/DraggedItem/utils/connect.js
0
https://github.com/strapi/strapi/commit/ce181eccf0a12a47c1e77517ffe0650a1cefe4ba
[ 0.0001726783812046051, 0.00017174569074995816, 0.0001708130002953112, 0.00017174569074995816, 9.32690454646945e-7 ]
{ "id": 1, "code_window": [ " 'admin::isAuthenticatedAdmin',\n", " {\n", " name: 'admin::hasPermissions',\n", " config: { actions: ['admin::project-settings.update'] },\n", " },\n", " ],\n", " },\n", " },\n", " {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " config: { actions: ['admin::project-settings.read'] },\n" ], "file_path": "packages/core/admin/server/routes/admin.js", "type": "replace", "edit_start_line_idx": 18 }
'use strict'; module.exports = [ { method: 'GET', path: '/init', handler: 'admin.init', config: { auth: false }, }, { method: 'GET', path: '/project-settings', handler: 'admin.getProjectSettings', config: { policies: [ 'admin::isAuthenticatedAdmin', { name: 'admin::hasPermissions', config: { actions: ['admin::project-settings.update'] }, }, ], }, }, { method: 'POST', path: '/project-settings', handler: 'admin.updateProjectSettings', config: { policies: [ 'admin::isAuthenticatedAdmin', { name: 'admin::hasPermissions', config: { actions: ['admin::project-settings.update'] }, }, ], }, }, { method: 'GET', path: '/project-type', handler: 'admin.getProjectType', config: { auth: false }, }, { method: 'GET', path: '/information', handler: 'admin.information', config: { policies: ['admin::isAuthenticatedAdmin'], }, }, { method: 'GET', path: '/plugins', handler: 'admin.plugins', config: { policies: [ 'admin::isAuthenticatedAdmin', { name: 'admin::hasPermissions', config: { actions: ['admin::marketplace.read'] } }, ], }, }, { method: 'POST', path: '/plugins/install', handler: 'admin.installPlugin', config: { policies: [ 'admin::isAuthenticatedAdmin', { name: 'admin::hasPermissions', config: { actions: ['admin::marketplace.plugins.install'] }, }, ], }, }, { method: 'DELETE', path: '/plugins/uninstall/:plugin', handler: 'admin.uninstallPlugin', config: { policies: [ 'admin::isAuthenticatedAdmin', { name: 'admin::hasPermissions', config: { actions: ['admin::marketplace.plugins.uninstall'] }, }, ], }, }, ];
packages/core/admin/server/routes/admin.js
1
https://github.com/strapi/strapi/commit/ce181eccf0a12a47c1e77517ffe0650a1cefe4ba
[ 0.9913451671600342, 0.15344618260860443, 0.0001667039468884468, 0.01559649407863617, 0.3085009455680847 ]
{ "id": 1, "code_window": [ " 'admin::isAuthenticatedAdmin',\n", " {\n", " name: 'admin::hasPermissions',\n", " config: { actions: ['admin::project-settings.update'] },\n", " },\n", " ],\n", " },\n", " },\n", " {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " config: { actions: ['admin::project-settings.read'] },\n" ], "file_path": "packages/core/admin/server/routes/admin.js", "type": "replace", "edit_start_line_idx": 18 }
'use strict'; /** * Returns a url base on hostname, port and ssl options */ module.exports = ({ hostname, port, ssl = false }) => { const protocol = ssl ? 'https' : 'http'; const defaultPort = ssl ? 443 : 80; const portString = port === undefined || parseInt(port, 10) === defaultPort ? '' : `:${port}`; return `${protocol}://${hostname}${portString}`; };
packages/core/strapi/lib/utils/url-from-segments.js
0
https://github.com/strapi/strapi/commit/ce181eccf0a12a47c1e77517ffe0650a1cefe4ba
[ 0.00016786757623776793, 0.00016597495414316654, 0.00016408231749664992, 0.00016597495414316654, 0.000001892629370559007 ]
{ "id": 1, "code_window": [ " 'admin::isAuthenticatedAdmin',\n", " {\n", " name: 'admin::hasPermissions',\n", " config: { actions: ['admin::project-settings.update'] },\n", " },\n", " ],\n", " },\n", " },\n", " {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " config: { actions: ['admin::project-settings.read'] },\n" ], "file_path": "packages/core/admin/server/routes/admin.js", "type": "replace", "edit_start_line_idx": 18 }
'use strict'; const createSection = require('../permission/sections-builder/section'); describe('Section', () => { test('Creates a new section with the correct properties', () => { const section = createSection(); expect(section.hooks).toMatchObject({ handlers: expect.any(Object), matchers: expect.any(Object), }); expect(section).toHaveProperty('appliesToAction', expect.any(Function)); expect(section).toHaveProperty('build', expect.any(Function)); }); test(`It's possible to register handlers for hooks on section init`, async () => { const handler = jest.fn(); const matcher = jest.fn(); const section = createSection({ handlers: [handler], matchers: [matcher] }); await section.hooks.matchers.call(); await section.hooks.handlers.call(); expect(handler).toHaveBeenCalled(); expect(matcher).toHaveBeenCalled(); }); test(`It's possible to register handlers for hooks after section init`, async () => { const handler = jest.fn(); const matcher = jest.fn(); const section = createSection(); section.hooks.handlers.register(handler); section.hooks.matchers.register(matcher); await section.hooks.matchers.call(); await section.hooks.handlers.call(); expect(handler).toHaveBeenCalled(); expect(matcher).toHaveBeenCalled(); }); describe('appliesToAction', () => { test(`If there is no matcher registered, it should return false everytime`, async () => { const section = createSection(); const action = {}; const applies = await section.appliesToAction(action); expect(applies).toBe(false); }); test(`If there is at least one matcher returning true, it should return true`, async () => { const action = { foo: 'bar' }; const matchers = [jest.fn(a => a.foo === 'bar'), jest.fn(a => a.bar === 'foo')]; const section = createSection({ matchers }); const applies = await section.appliesToAction(action); matchers.forEach(matcher => expect(matcher).toHaveBeenCalledWith(action)); expect(applies).toBe(true); }); test('If every matcher returns other results than true, it should return false', async () => { const action = { foo: 'bar' }; const matchers = [jest.fn(a => a.foo === 'foo'), jest.fn(a => a.bar === 'foo')]; const section = createSection({ matchers }); const applies = await section.appliesToAction(action); matchers.forEach(matcher => expect(matcher).toHaveBeenCalledWith(action)); expect(applies).toBe(false); }); }); describe('build', () => { test('Trying to build the section without any action should return the section initial state', async () => { const initialStateFactory = jest.fn(() => ({ foo: 'bar' })); const section = createSection({ initialStateFactory }); const result = await section.build(); expect(initialStateFactory).toHaveBeenCalled(); expect(result).toStrictEqual({ foo: 'bar' }); }); test('Trying to build the section without any registered matcher should return the section initial state', async () => { const initialStateFactory = jest.fn(() => ({ foo: 'bar' })); const actions = [{ foo: 'bar' }, { bar: 'foo' }]; const section = createSection({ initialStateFactory }); const result = await section.build(actions); expect(initialStateFactory).toHaveBeenCalled(); expect(result).toStrictEqual({ foo: 'bar' }); }); test('Trying to build the section without any registered handler should return the section initial state', async () => { const initialStateFactory = jest.fn(() => ({ foo: 'bar' })); const matchers = [jest.fn(() => true)]; const actions = [{ foo: 'bar' }, { bar: 'foo' }]; const section = createSection({ initialStateFactory, matchers }); const result = await section.build(actions); expect(initialStateFactory).toHaveBeenCalled(); expect(matchers[0]).toHaveBeenCalledTimes(actions.length); expect(result).toStrictEqual({ foo: 'bar' }); }); test('Building the section with different handlers', async () => { const initialStateFactory = jest.fn(() => ({ foo: 'bar' })); const matchers = [jest.fn(() => true)]; const handlers = [ jest.fn(({ section }) => { section.foobar = 1; }), jest.fn(({ section }) => { section.barfoo = 2; }), ]; const actions = [{ foo: 'bar' }, { bar: 'foo' }]; const section = createSection({ initialStateFactory, matchers, handlers }); const result = await section.build(actions); expect(initialStateFactory).toHaveBeenCalled(); expect(matchers[0]).toHaveBeenCalledTimes(actions.length); expect(result).toStrictEqual({ foo: 'bar', foobar: 1, barfoo: 2 }); }); }); });
packages/core/admin/server/services/__tests__/permissions.section-builder.section.test.js
0
https://github.com/strapi/strapi/commit/ce181eccf0a12a47c1e77517ffe0650a1cefe4ba
[ 0.006674129515886307, 0.0006518766167573631, 0.00016548289568163455, 0.00017273527919314802, 0.00167115218937397 ]
{ "id": 1, "code_window": [ " 'admin::isAuthenticatedAdmin',\n", " {\n", " name: 'admin::hasPermissions',\n", " config: { actions: ['admin::project-settings.update'] },\n", " },\n", " ],\n", " },\n", " },\n", " {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " config: { actions: ['admin::project-settings.read'] },\n" ], "file_path": "packages/core/admin/server/routes/admin.js", "type": "replace", "edit_start_line_idx": 18 }
import checkPermissions from '../checkPermissions'; jest.mock('@strapi/helper-plugin', () => ({ hasPermissions: () => Promise.resolve(true), })); describe('checkPermissions', () => { it('creates an array of boolean corresponding to the permission state', async () => { const userPermissions = {}; const permissions = [{ permissions: {} }, { permissions: {} }]; const expected = [true, true]; const actual = await Promise.all(checkPermissions(userPermissions, permissions)); expect(actual).toEqual(expected); }); });
packages/core/admin/admin/src/hooks/useMenu/utils/tests/checkPermissions.test.js
0
https://github.com/strapi/strapi/commit/ce181eccf0a12a47c1e77517ffe0650a1cefe4ba
[ 0.00024122752074617893, 0.00021086211199872196, 0.00018049671780318022, 0.00021086211199872196, 0.000030365401471499354 ]
{ "id": 2, "code_window": [ " \"action\": \"admin::marketplace.read\",\n", " \"category\": \"plugins and marketplace\",\n", " \"displayName\": \"Access the marketplace\",\n", " \"subCategory\": \"marketplace\",\n", " },\n", " Object {\n", " \"action\": \"admin::project-settings.update\",\n", " \"category\": \"project\",\n", " \"displayName\": \"Update the project level settings\",\n", " \"subCategory\": \"general\",\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " Object {\n", " \"action\": \"admin::project-settings.read\",\n", " \"category\": \"project\",\n", " \"displayName\": \"Read the project level settings\",\n", " \"subCategory\": \"general\",\n", " },\n" ], "file_path": "packages/core/admin/server/tests/admin-permission.test.e2e.js", "type": "add", "edit_start_line_idx": 337 }
'use strict'; module.exports = { actions: [ { uid: 'marketplace.read', displayName: 'Access the marketplace', pluginName: 'admin', section: 'settings', category: 'plugins and marketplace', subCategory: 'marketplace', }, { uid: 'marketplace.plugins.install', displayName: 'Install (only for dev env)', pluginName: 'admin', section: 'settings', category: 'plugins and marketplace', subCategory: 'plugins', }, { uid: 'marketplace.plugins.uninstall', displayName: 'Uninstall (only for dev env)', pluginName: 'admin', section: 'settings', category: 'plugins and marketplace', subCategory: 'plugins', }, { uid: 'webhooks.create', displayName: 'Create', pluginName: 'admin', section: 'settings', category: 'webhooks', }, { uid: 'webhooks.read', displayName: 'Read', pluginName: 'admin', section: 'settings', category: 'webhooks', }, { uid: 'webhooks.update', displayName: 'Update', pluginName: 'admin', section: 'settings', category: 'webhooks', }, { uid: 'webhooks.delete', displayName: 'Delete', pluginName: 'admin', section: 'settings', category: 'webhooks', }, { uid: 'users.create', displayName: 'Create (invite)', pluginName: 'admin', section: 'settings', category: 'users and roles', subCategory: 'users', }, { uid: 'users.read', displayName: 'Read', pluginName: 'admin', section: 'settings', category: 'users and roles', subCategory: 'users', }, { uid: 'users.update', displayName: 'Update', pluginName: 'admin', section: 'settings', category: 'users and roles', subCategory: 'users', }, { uid: 'users.delete', displayName: 'Delete', pluginName: 'admin', section: 'settings', category: 'users and roles', subCategory: 'users', }, { uid: 'roles.create', displayName: 'Create', pluginName: 'admin', section: 'settings', category: 'users and roles', subCategory: 'roles', }, { uid: 'roles.read', displayName: 'Read', pluginName: 'admin', section: 'settings', category: 'users and roles', subCategory: 'roles', }, { uid: 'roles.update', displayName: 'Update', pluginName: 'admin', section: 'settings', category: 'users and roles', subCategory: 'roles', }, { uid: 'roles.delete', displayName: 'Delete', pluginName: 'admin', section: 'settings', category: 'users and roles', subCategory: 'roles', }, { uid: 'api-tokens.create', displayName: 'Create (generate)', pluginName: 'admin', section: 'settings', category: 'api tokens', }, { uid: 'api-tokens.read', displayName: 'Read', pluginName: 'admin', section: 'settings', category: 'api tokens', }, { uid: 'api-tokens.update', displayName: 'Update', pluginName: 'admin', section: 'settings', category: 'api tokens', }, { uid: 'api-tokens.delete', displayName: 'Delete (revoke)', pluginName: 'admin', section: 'settings', category: 'api tokens', }, { uid: 'project-settings.update', displayName: 'Update the project level settings', pluginName: 'admin', section: 'settings', category: 'project', }, ], };
packages/core/admin/server/config/admin-actions.js
1
https://github.com/strapi/strapi/commit/ce181eccf0a12a47c1e77517ffe0650a1cefe4ba
[ 0.011176686733961105, 0.0008782140794210136, 0.0001649716723477468, 0.00016835333372000605, 0.0026594207156449556 ]
{ "id": 2, "code_window": [ " \"action\": \"admin::marketplace.read\",\n", " \"category\": \"plugins and marketplace\",\n", " \"displayName\": \"Access the marketplace\",\n", " \"subCategory\": \"marketplace\",\n", " },\n", " Object {\n", " \"action\": \"admin::project-settings.update\",\n", " \"category\": \"project\",\n", " \"displayName\": \"Update the project level settings\",\n", " \"subCategory\": \"general\",\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " Object {\n", " \"action\": \"admin::project-settings.read\",\n", " \"category\": \"project\",\n", " \"displayName\": \"Read the project level settings\",\n", " \"subCategory\": \"general\",\n", " },\n" ], "file_path": "packages/core/admin/server/tests/admin-permission.test.e2e.js", "type": "add", "edit_start_line_idx": 337 }
'use strict'; const { isPrivateAttribute } = require('../../content-types'); module.exports = ({ schema, key }, { remove }) => { const isPrivate = isPrivateAttribute(schema, key); if (isPrivate) { remove(key); } };
packages/core/utils/lib/sanitize/visitors/remove-private.js
0
https://github.com/strapi/strapi/commit/ce181eccf0a12a47c1e77517ffe0650a1cefe4ba
[ 0.00016977702034637332, 0.00016773826791904867, 0.00016569953004363924, 0.00016773826791904867, 0.0000020387451513670385 ]
{ "id": 2, "code_window": [ " \"action\": \"admin::marketplace.read\",\n", " \"category\": \"plugins and marketplace\",\n", " \"displayName\": \"Access the marketplace\",\n", " \"subCategory\": \"marketplace\",\n", " },\n", " Object {\n", " \"action\": \"admin::project-settings.update\",\n", " \"category\": \"project\",\n", " \"displayName\": \"Update the project level settings\",\n", " \"subCategory\": \"general\",\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " Object {\n", " \"action\": \"admin::project-settings.read\",\n", " \"category\": \"project\",\n", " \"displayName\": \"Read the project level settings\",\n", " \"subCategory\": \"general\",\n", " },\n" ], "file_path": "packages/core/admin/server/tests/admin-permission.test.e2e.js", "type": "add", "edit_start_line_idx": 337 }
import produce from 'immer'; import { set } from 'lodash'; const initialState = { formErrors: {}, isLoading: true, initialData: {}, modifiedData: {}, }; const reducer = (state, action) => // eslint-disable-next-line consistent-return produce(state, draftState => { switch (action.type) { case 'GET_DATA': { draftState.isLoading = true; draftState.initialData = {}; draftState.modifiedData = {}; break; } case 'GET_DATA_SUCCEEDED': { draftState.isLoading = false; draftState.initialData = action.data; draftState.modifiedData = action.data; break; } case 'GET_DATA_ERROR': { draftState.isLoading = true; break; } case 'ON_CHANGE': { set(draftState, ['modifiedData', ...action.keys.split('.')], action.value); break; } case 'RESET_FORM': { draftState.modifiedData = state.initialData; draftState.formErrors = {}; break; } case 'SET_ERRORS': { draftState.formErrors = action.errors; break; } default: { return draftState; } } }); export default reducer; export { initialState };
packages/plugins/users-permissions/admin/src/pages/Providers/reducer.js
0
https://github.com/strapi/strapi/commit/ce181eccf0a12a47c1e77517ffe0650a1cefe4ba
[ 0.00017491971084382385, 0.00017037609359249473, 0.00016640426474623382, 0.00016967314877547324, 0.000002895801117119845 ]
{ "id": 2, "code_window": [ " \"action\": \"admin::marketplace.read\",\n", " \"category\": \"plugins and marketplace\",\n", " \"displayName\": \"Access the marketplace\",\n", " \"subCategory\": \"marketplace\",\n", " },\n", " Object {\n", " \"action\": \"admin::project-settings.update\",\n", " \"category\": \"project\",\n", " \"displayName\": \"Update the project level settings\",\n", " \"subCategory\": \"general\",\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " Object {\n", " \"action\": \"admin::project-settings.read\",\n", " \"category\": \"project\",\n", " \"displayName\": \"Read the project level settings\",\n", " \"subCategory\": \"general\",\n", " },\n" ], "file_path": "packages/core/admin/server/tests/admin-permission.test.e2e.js", "type": "add", "edit_start_line_idx": 337 }
import produce from 'immer'; const initialState = { isLoading: true, modifiedData: {}, }; const reducer = (state, action) => // eslint-disable-next-line consistent-return produce(state, draftState => { switch (action.type) { case 'GET_DATA': { draftState.isLoading = true; draftState.modifiedData = {}; break; } case 'GET_DATA_SUCCEEDED': { draftState.isLoading = false; draftState.modifiedData = action.data; break; } case 'GET_DATA_ERROR': { draftState.isLoading = true; break; } case 'ON_SUBMIT_SUCCEEDED': { draftState.modifiedData = action.data; break; } default: { return draftState; } } }); export default reducer; export { initialState };
packages/plugins/users-permissions/admin/src/hooks/useForm/reducer.js
0
https://github.com/strapi/strapi/commit/ce181eccf0a12a47c1e77517ffe0650a1cefe4ba
[ 0.00017342966748401523, 0.00017090323672164232, 0.0001662692811805755, 0.00017133497749455273, 0.000002468726052029524 ]
{ "id": 3, "code_window": [ " \"displayName\": \"Access the marketplace\",\n", " \"subCategory\": \"marketplace\",\n", " },\n", " Object {\n", " \"action\": \"admin::project-settings.update\",\n", " \"category\": \"project\",\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " Object {\n", " \"action\": \"admin::project-settings.read\",\n", " \"category\": \"project\",\n", " \"displayName\": \"Read the project level settings\",\n", " \"subCategory\": \"general\",\n", " },\n" ], "file_path": "packages/core/admin/server/tests/admin-permission.test.e2e.js", "type": "add", "edit_start_line_idx": 822 }
'use strict'; const _ = require('lodash'); const { createAuthRequest } = require('../../../../../test/helpers/request'); const { createStrapiInstance } = require('../../../../../test/helpers/strapi'); const edition = process.env.STRAPI_DISABLE_EE === 'true' ? 'CE' : 'EE'; describe('Role CRUD End to End', () => { let rq; let strapi; beforeAll(async () => { strapi = await createStrapiInstance(); rq = await createAuthRequest({ strapi }); }); afterAll(async () => { await strapi.destroy(); }); test('Can get the existing permissions', async () => { let res = await rq({ url: '/admin/permissions', method: 'GET', }); expect(res.statusCode).toBe(200); // Data is sorted to avoid error with snapshot when the data is not in the same order const sortedData = _.cloneDeep(res.body.data); Object.keys(sortedData.sections).forEach(sectionName => { sortedData.sections[sectionName] = _.sortBy(sortedData.sections[sectionName], ['action']); }); sortedData.conditions = sortedData.conditions.sort(); if (edition === 'CE') { expect(sortedData).toMatchInlineSnapshot(` Object { "conditions": Array [ Object { "category": "default", "displayName": "Is creator", "id": "admin::is-creator", }, Object { "category": "default", "displayName": "Has same role as creator", "id": "admin::has-same-role-as-creator", }, ], "sections": Object { "collectionTypes": Array [ Array [ Object { "actionId": "plugin::content-manager.explorer.create", "applyToProperties": Array [ "fields", "locales", ], "label": "Create", "subjects": Array [ "plugin::users-permissions.user", ], }, Object { "actionId": "plugin::content-manager.explorer.read", "applyToProperties": Array [ "fields", "locales", ], "label": "Read", "subjects": Array [ "plugin::users-permissions.user", ], }, Object { "actionId": "plugin::content-manager.explorer.update", "applyToProperties": Array [ "fields", "locales", ], "label": "Update", "subjects": Array [ "plugin::users-permissions.user", ], }, Object { "actionId": "plugin::content-manager.explorer.delete", "applyToProperties": Array [ "locales", ], "label": "Delete", "subjects": Array [ "plugin::users-permissions.user", ], }, Object { "actionId": "plugin::content-manager.explorer.publish", "applyToProperties": Array [ "locales", ], "label": "Publish", "subjects": Array [], }, ], Array [ Object { "label": "user", "properties": Array [ Object { "children": Array [ Object { "label": "username", "required": true, "value": "username", }, Object { "label": "email", "required": true, "value": "email", }, Object { "label": "provider", "value": "provider", }, Object { "label": "password", "value": "password", }, Object { "label": "resetPasswordToken", "value": "resetPasswordToken", }, Object { "label": "confirmationToken", "value": "confirmationToken", }, Object { "label": "confirmed", "value": "confirmed", }, Object { "label": "blocked", "value": "blocked", }, Object { "label": "role", "value": "role", }, ], "label": "Fields", "value": "fields", }, ], "uid": "plugin::users-permissions.user", }, ], ], "plugins": Array [ Object { "action": "plugin::content-manager.collection-types.configure-view", "displayName": "Configure view", "plugin": "content-manager", "subCategory": "collection types", }, Object { "action": "plugin::content-manager.components.configure-layout", "displayName": "Configure Layout", "plugin": "content-manager", "subCategory": "components", }, Object { "action": "plugin::content-manager.single-types.configure-view", "displayName": "Configure view", "plugin": "content-manager", "subCategory": "single types", }, Object { "action": "plugin::content-type-builder.read", "displayName": "Read", "plugin": "content-type-builder", "subCategory": "general", }, Object { "action": "plugin::documentation.read", "displayName": "Access the Documentation", "plugin": "documentation", "subCategory": "general", }, Object { "action": "plugin::documentation.settings.regenerate", "displayName": "Regenerate", "plugin": "documentation", "subCategory": "general", }, Object { "action": "plugin::documentation.settings.update", "displayName": "Update and delete", "plugin": "documentation", "subCategory": "general", }, Object { "action": "plugin::upload.assets.copy-link", "displayName": "Copy link", "plugin": "upload", "subCategory": "assets", }, Object { "action": "plugin::upload.assets.create", "displayName": "Create (upload)", "plugin": "upload", "subCategory": "assets", }, Object { "action": "plugin::upload.assets.download", "displayName": "Download", "plugin": "upload", "subCategory": "assets", }, Object { "action": "plugin::upload.assets.update", "displayName": "Update (crop, details, replace) + delete", "plugin": "upload", "subCategory": "assets", }, Object { "action": "plugin::upload.read", "displayName": "Access the Media Library", "plugin": "upload", "subCategory": "general", }, Object { "action": "plugin::users-permissions.advanced-settings.read", "displayName": "Read", "plugin": "users-permissions", "subCategory": "advancedSettings", }, Object { "action": "plugin::users-permissions.advanced-settings.update", "displayName": "Edit", "plugin": "users-permissions", "subCategory": "advancedSettings", }, Object { "action": "plugin::users-permissions.email-templates.read", "displayName": "Read", "plugin": "users-permissions", "subCategory": "emailTemplates", }, Object { "action": "plugin::users-permissions.email-templates.update", "displayName": "Edit", "plugin": "users-permissions", "subCategory": "emailTemplates", }, Object { "action": "plugin::users-permissions.providers.read", "displayName": "Read", "plugin": "users-permissions", "subCategory": "providers", }, Object { "action": "plugin::users-permissions.providers.update", "displayName": "Edit", "plugin": "users-permissions", "subCategory": "providers", }, Object { "action": "plugin::users-permissions.roles.create", "displayName": "Create", "plugin": "users-permissions", "subCategory": "roles", }, Object { "action": "plugin::users-permissions.roles.delete", "displayName": "Delete", "plugin": "users-permissions", "subCategory": "roles", }, Object { "action": "plugin::users-permissions.roles.read", "displayName": "Read", "plugin": "users-permissions", "subCategory": "roles", }, Object { "action": "plugin::users-permissions.roles.update", "displayName": "Update", "plugin": "users-permissions", "subCategory": "roles", }, ], "settings": Array [ Object { "action": "admin::api-tokens.create", "category": "api tokens", "displayName": "Create (generate)", "subCategory": "general", }, Object { "action": "admin::api-tokens.delete", "category": "api tokens", "displayName": "Delete (revoke)", "subCategory": "general", }, Object { "action": "admin::api-tokens.read", "category": "api tokens", "displayName": "Read", "subCategory": "general", }, Object { "action": "admin::api-tokens.update", "category": "api tokens", "displayName": "Update", "subCategory": "general", }, Object { "action": "admin::marketplace.plugins.install", "category": "plugins and marketplace", "displayName": "Install (only for dev env)", "subCategory": "plugins", }, Object { "action": "admin::marketplace.plugins.uninstall", "category": "plugins and marketplace", "displayName": "Uninstall (only for dev env)", "subCategory": "plugins", }, Object { "action": "admin::marketplace.read", "category": "plugins and marketplace", "displayName": "Access the marketplace", "subCategory": "marketplace", }, Object { "action": "admin::project-settings.update", "category": "project", "displayName": "Update the project level settings", "subCategory": "general", }, Object { "action": "admin::roles.create", "category": "users and roles", "displayName": "Create", "subCategory": "roles", }, Object { "action": "admin::roles.delete", "category": "users and roles", "displayName": "Delete", "subCategory": "roles", }, Object { "action": "admin::roles.read", "category": "users and roles", "displayName": "Read", "subCategory": "roles", }, Object { "action": "admin::roles.update", "category": "users and roles", "displayName": "Update", "subCategory": "roles", }, Object { "action": "admin::users.create", "category": "users and roles", "displayName": "Create (invite)", "subCategory": "users", }, Object { "action": "admin::users.delete", "category": "users and roles", "displayName": "Delete", "subCategory": "users", }, Object { "action": "admin::users.read", "category": "users and roles", "displayName": "Read", "subCategory": "users", }, Object { "action": "admin::users.update", "category": "users and roles", "displayName": "Update", "subCategory": "users", }, Object { "action": "admin::webhooks.create", "category": "webhooks", "displayName": "Create", "subCategory": "general", }, Object { "action": "admin::webhooks.delete", "category": "webhooks", "displayName": "Delete", "subCategory": "general", }, Object { "action": "admin::webhooks.read", "category": "webhooks", "displayName": "Read", "subCategory": "general", }, Object { "action": "admin::webhooks.update", "category": "webhooks", "displayName": "Update", "subCategory": "general", }, Object { "action": "plugin::documentation.settings.read", "category": "documentation", "displayName": "Access the documentation settings page", "subCategory": "general", }, Object { "action": "plugin::email.settings.read", "category": "email", "displayName": "Access the Email Settings page", "subCategory": "general", }, Object { "action": "plugin::i18n.locale.create", "category": "Internationalization", "displayName": "Create", "subCategory": "Locales", }, Object { "action": "plugin::i18n.locale.delete", "category": "Internationalization", "displayName": "Delete", "subCategory": "Locales", }, Object { "action": "plugin::i18n.locale.read", "category": "Internationalization", "displayName": "Read", "subCategory": "Locales", }, Object { "action": "plugin::i18n.locale.update", "category": "Internationalization", "displayName": "Update", "subCategory": "Locales", }, Object { "action": "plugin::upload.settings.read", "category": "media library", "displayName": "Access the Media Library settings page", "subCategory": "general", }, ], "singleTypes": Array [ Array [ Object { "actionId": "plugin::content-manager.explorer.create", "applyToProperties": Array [ "fields", "locales", ], "label": "Create", "subjects": Array [ "plugin::users-permissions.user", ], }, Object { "actionId": "plugin::content-manager.explorer.read", "applyToProperties": Array [ "fields", "locales", ], "label": "Read", "subjects": Array [ "plugin::users-permissions.user", ], }, Object { "actionId": "plugin::content-manager.explorer.update", "applyToProperties": Array [ "fields", "locales", ], "label": "Update", "subjects": Array [ "plugin::users-permissions.user", ], }, Object { "actionId": "plugin::content-manager.explorer.delete", "applyToProperties": Array [ "locales", ], "label": "Delete", "subjects": Array [ "plugin::users-permissions.user", ], }, Object { "actionId": "plugin::content-manager.explorer.publish", "applyToProperties": Array [ "locales", ], "label": "Publish", "subjects": Array [], }, ], Array [], ], }, } `); } else { // eslint-disable-next-line node/no-extraneous-require const { features } = require('@strapi/strapi/lib/utils/ee'); const hasSSO = features.isEnabled('sso'); if (hasSSO) { expect(sortedData).toMatchInlineSnapshot(` Object { "conditions": Array [ Object { "category": "default", "displayName": "Is creator", "id": "admin::is-creator", }, Object { "category": "default", "displayName": "Has same role as creator", "id": "admin::has-same-role-as-creator", }, ], "sections": Object { "collectionTypes": Array [ Array [ Object { "actionId": "plugin::content-manager.explorer.create", "applyToProperties": Array [ "fields", "locales", ], "label": "Create", "subjects": Array [ "plugin::users-permissions.user", ], }, Object { "actionId": "plugin::content-manager.explorer.read", "applyToProperties": Array [ "fields", "locales", ], "label": "Read", "subjects": Array [ "plugin::users-permissions.user", ], }, Object { "actionId": "plugin::content-manager.explorer.update", "applyToProperties": Array [ "fields", "locales", ], "label": "Update", "subjects": Array [ "plugin::users-permissions.user", ], }, Object { "actionId": "plugin::content-manager.explorer.delete", "applyToProperties": Array [ "locales", ], "label": "Delete", "subjects": Array [ "plugin::users-permissions.user", ], }, Object { "actionId": "plugin::content-manager.explorer.publish", "applyToProperties": Array [ "locales", ], "label": "Publish", "subjects": Array [], }, ], Array [ Object { "label": "user", "properties": Array [ Object { "children": Array [ Object { "label": "username", "required": true, "value": "username", }, Object { "label": "email", "required": true, "value": "email", }, Object { "label": "provider", "value": "provider", }, Object { "label": "password", "value": "password", }, Object { "label": "resetPasswordToken", "value": "resetPasswordToken", }, Object { "label": "confirmationToken", "value": "confirmationToken", }, Object { "label": "confirmed", "value": "confirmed", }, Object { "label": "blocked", "value": "blocked", }, Object { "label": "role", "value": "role", }, ], "label": "Fields", "value": "fields", }, ], "uid": "plugin::users-permissions.user", }, ], ], "plugins": Array [ Object { "action": "plugin::content-manager.collection-types.configure-view", "displayName": "Configure view", "plugin": "content-manager", "subCategory": "collection types", }, Object { "action": "plugin::content-manager.components.configure-layout", "displayName": "Configure Layout", "plugin": "content-manager", "subCategory": "components", }, Object { "action": "plugin::content-manager.single-types.configure-view", "displayName": "Configure view", "plugin": "content-manager", "subCategory": "single types", }, Object { "action": "plugin::content-type-builder.read", "displayName": "Read", "plugin": "content-type-builder", "subCategory": "general", }, Object { "action": "plugin::documentation.read", "displayName": "Access the Documentation", "plugin": "documentation", "subCategory": "general", }, Object { "action": "plugin::documentation.settings.regenerate", "displayName": "Regenerate", "plugin": "documentation", "subCategory": "general", }, Object { "action": "plugin::documentation.settings.update", "displayName": "Update and delete", "plugin": "documentation", "subCategory": "general", }, Object { "action": "plugin::upload.assets.copy-link", "displayName": "Copy link", "plugin": "upload", "subCategory": "assets", }, Object { "action": "plugin::upload.assets.create", "displayName": "Create (upload)", "plugin": "upload", "subCategory": "assets", }, Object { "action": "plugin::upload.assets.download", "displayName": "Download", "plugin": "upload", "subCategory": "assets", }, Object { "action": "plugin::upload.assets.update", "displayName": "Update (crop, details, replace) + delete", "plugin": "upload", "subCategory": "assets", }, Object { "action": "plugin::upload.read", "displayName": "Access the Media Library", "plugin": "upload", "subCategory": "general", }, Object { "action": "plugin::users-permissions.advanced-settings.read", "displayName": "Read", "plugin": "users-permissions", "subCategory": "advancedSettings", }, Object { "action": "plugin::users-permissions.advanced-settings.update", "displayName": "Edit", "plugin": "users-permissions", "subCategory": "advancedSettings", }, Object { "action": "plugin::users-permissions.email-templates.read", "displayName": "Read", "plugin": "users-permissions", "subCategory": "emailTemplates", }, Object { "action": "plugin::users-permissions.email-templates.update", "displayName": "Edit", "plugin": "users-permissions", "subCategory": "emailTemplates", }, Object { "action": "plugin::users-permissions.providers.read", "displayName": "Read", "plugin": "users-permissions", "subCategory": "providers", }, Object { "action": "plugin::users-permissions.providers.update", "displayName": "Edit", "plugin": "users-permissions", "subCategory": "providers", }, Object { "action": "plugin::users-permissions.roles.create", "displayName": "Create", "plugin": "users-permissions", "subCategory": "roles", }, Object { "action": "plugin::users-permissions.roles.delete", "displayName": "Delete", "plugin": "users-permissions", "subCategory": "roles", }, Object { "action": "plugin::users-permissions.roles.read", "displayName": "Read", "plugin": "users-permissions", "subCategory": "roles", }, Object { "action": "plugin::users-permissions.roles.update", "displayName": "Update", "plugin": "users-permissions", "subCategory": "roles", }, ], "settings": Array [ Object { "action": "admin::api-tokens.create", "category": "api tokens", "displayName": "Create (generate)", "subCategory": "general", }, Object { "action": "admin::api-tokens.delete", "category": "api tokens", "displayName": "Delete (revoke)", "subCategory": "general", }, Object { "action": "admin::api-tokens.read", "category": "api tokens", "displayName": "Read", "subCategory": "general", }, Object { "action": "admin::api-tokens.update", "category": "api tokens", "displayName": "Update", "subCategory": "general", }, Object { "action": "admin::marketplace.plugins.install", "category": "plugins and marketplace", "displayName": "Install (only for dev env)", "subCategory": "plugins", }, Object { "action": "admin::marketplace.plugins.uninstall", "category": "plugins and marketplace", "displayName": "Uninstall (only for dev env)", "subCategory": "plugins", }, Object { "action": "admin::marketplace.read", "category": "plugins and marketplace", "displayName": "Access the marketplace", "subCategory": "marketplace", }, Object { "action": "admin::project-settings.update", "category": "project", "displayName": "Update the project level settings", "subCategory": "general", }, Object { "action": "admin::provider-login.read", "category": "single sign on", "displayName": "Read", "subCategory": "options", }, Object { "action": "admin::provider-login.update", "category": "single sign on", "displayName": "Update", "subCategory": "options", }, Object { "action": "admin::roles.create", "category": "users and roles", "displayName": "Create", "subCategory": "roles", }, Object { "action": "admin::roles.delete", "category": "users and roles", "displayName": "Delete", "subCategory": "roles", }, Object { "action": "admin::roles.read", "category": "users and roles", "displayName": "Read", "subCategory": "roles", }, Object { "action": "admin::roles.update", "category": "users and roles", "displayName": "Update", "subCategory": "roles", }, Object { "action": "admin::users.create", "category": "users and roles", "displayName": "Create (invite)", "subCategory": "users", }, Object { "action": "admin::users.delete", "category": "users and roles", "displayName": "Delete", "subCategory": "users", }, Object { "action": "admin::users.read", "category": "users and roles", "displayName": "Read", "subCategory": "users", }, Object { "action": "admin::users.update", "category": "users and roles", "displayName": "Update", "subCategory": "users", }, Object { "action": "admin::webhooks.create", "category": "webhooks", "displayName": "Create", "subCategory": "general", }, Object { "action": "admin::webhooks.delete", "category": "webhooks", "displayName": "Delete", "subCategory": "general", }, Object { "action": "admin::webhooks.read", "category": "webhooks", "displayName": "Read", "subCategory": "general", }, Object { "action": "admin::webhooks.update", "category": "webhooks", "displayName": "Update", "subCategory": "general", }, Object { "action": "plugin::documentation.settings.read", "category": "documentation", "displayName": "Access the documentation settings page", "subCategory": "general", }, Object { "action": "plugin::email.settings.read", "category": "email", "displayName": "Access the Email Settings page", "subCategory": "general", }, Object { "action": "plugin::i18n.locale.create", "category": "Internationalization", "displayName": "Create", "subCategory": "Locales", }, Object { "action": "plugin::i18n.locale.delete", "category": "Internationalization", "displayName": "Delete", "subCategory": "Locales", }, Object { "action": "plugin::i18n.locale.read", "category": "Internationalization", "displayName": "Read", "subCategory": "Locales", }, Object { "action": "plugin::i18n.locale.update", "category": "Internationalization", "displayName": "Update", "subCategory": "Locales", }, Object { "action": "plugin::upload.settings.read", "category": "media library", "displayName": "Access the Media Library settings page", "subCategory": "general", }, ], "singleTypes": Array [ Array [ Object { "actionId": "plugin::content-manager.explorer.create", "applyToProperties": Array [ "fields", "locales", ], "label": "Create", "subjects": Array [ "plugin::users-permissions.user", ], }, Object { "actionId": "plugin::content-manager.explorer.read", "applyToProperties": Array [ "fields", "locales", ], "label": "Read", "subjects": Array [ "plugin::users-permissions.user", ], }, Object { "actionId": "plugin::content-manager.explorer.update", "applyToProperties": Array [ "fields", "locales", ], "label": "Update", "subjects": Array [ "plugin::users-permissions.user", ], }, Object { "actionId": "plugin::content-manager.explorer.delete", "applyToProperties": Array [ "locales", ], "label": "Delete", "subjects": Array [ "plugin::users-permissions.user", ], }, Object { "actionId": "plugin::content-manager.explorer.publish", "applyToProperties": Array [ "locales", ], "label": "Publish", "subjects": Array [], }, ], Array [], ], }, } `); } else { expect(sortedData).toMatchInlineSnapshot(` Object { "conditions": Array [ Object { "category": "default", "displayName": "Is creator", "id": "admin::is-creator", }, Object { "category": "default", "displayName": "Has same role as creator", "id": "admin::has-same-role-as-creator", }, ], "sections": Object { "contentTypes": Array [ Object { "action": "plugin::content-manager.explorer.create", "displayName": "Create", "subjects": Array [ "plugin::users-permissions.user", ], }, Object { "action": "plugin::content-manager.explorer.delete", "displayName": "Delete", "subjects": Array [ "plugin::users-permissions.user", ], }, Object { "action": "plugin::content-manager.explorer.publish", "displayName": "Publish", "subjects": Array [], }, Object { "action": "plugin::content-manager.explorer.read", "displayName": "Read", "subjects": Array [ "plugin::users-permissions.user", ], }, Object { "action": "plugin::content-manager.explorer.update", "displayName": "Update", "subjects": Array [ "plugin::users-permissions.user", ], }, ], "plugins": Array [ Object { "action": "plugin::content-manager.collection-types.configure-view", "displayName": "Configure view", "plugin": "plugin::content-manager", "subCategory": "collection types", }, Object { "action": "plugin::content-manager.components.configure-layout", "displayName": "Configure Layout", "plugin": "plugin::content-manager", "subCategory": "components", }, Object { "action": "plugin::content-manager.single-types.configure-view", "displayName": "Configure view", "plugin": "plugin::content-manager", "subCategory": "single types", }, Object { "action": "plugin::content-type-builder.read", "displayName": "Read", "plugin": "plugin::content-type-builder", "subCategory": "general", }, Object { "action": "plugin::documentation.read", "displayName": "Access the Documentation", "plugin": "plugin::documentation", "subCategory": "general", }, Object { "action": "plugin::documentation.settings.regenerate", "displayName": "Regenerate", "plugin": "plugin::documentation", "subCategory": "settings", }, Object { "action": "plugin::documentation.settings.update", "displayName": "Update and delete", "plugin": "plugin::documentation", "subCategory": "settings", }, Object { "action": "plugin::upload.assets.copy-link", "displayName": "Copy link", "plugin": "plugin::upload", "subCategory": "assets", }, Object { "action": "plugin::upload.assets.create", "displayName": "Create (upload)", "plugin": "plugin::upload", "subCategory": "assets", }, Object { "action": "plugin::upload.assets.download", "displayName": "Download", "plugin": "plugin::upload", "subCategory": "assets", }, Object { "action": "plugin::upload.assets.update", "displayName": "Update (crop, details, replace) + delete", "plugin": "plugin::upload", "subCategory": "assets", }, Object { "action": "plugin::upload.read", "displayName": "Access the Media Library", "plugin": "plugin::upload", "subCategory": "general", }, Object { "action": "plugin::users-permissions.advanced-settings.read", "displayName": "Read", "plugin": "plugin::users-permissions", "subCategory": "advancedSettings", }, Object { "action": "plugin::users-permissions.advanced-settings.update", "displayName": "Edit", "plugin": "plugin::users-permissions", "subCategory": "advancedSettings", }, Object { "action": "plugin::users-permissions.email-templates.read", "displayName": "Read", "plugin": "plugin::users-permissions", "subCategory": "emailTemplates", }, Object { "action": "plugin::users-permissions.email-templates.update", "displayName": "Edit", "plugin": "plugin::users-permissions", "subCategory": "emailTemplates", }, Object { "action": "plugin::users-permissions.providers.read", "displayName": "Read", "plugin": "plugin::users-permissions", "subCategory": "providers", }, Object { "action": "plugin::users-permissions.providers.update", "displayName": "Edit", "plugin": "plugin::users-permissions", "subCategory": "providers", }, Object { "action": "plugin::users-permissions.roles.create", "displayName": "Create", "plugin": "plugin::users-permissions", "subCategory": "roles", }, Object { "action": "plugin::users-permissions.roles.delete", "displayName": "Delete", "plugin": "plugin::users-permissions", "subCategory": "roles", }, Object { "action": "plugin::users-permissions.roles.read", "displayName": "Read", "plugin": "plugin::users-permissions", "subCategory": "roles", }, Object { "action": "plugin::users-permissions.roles.update", "displayName": "Update", "plugin": "plugin::users-permissions", "subCategory": "roles", }, ], "settings": Array [ Object { "action": "admin::api-tokens.create", "category": "api tokens", "displayName": "Create (generate)", "subCategory": "general", }, Object { "action": "admin::api-tokens.delete", "category": "api tokens", "displayName": "Delete (revoke)", "subCategory": "general", }, Object { "action": "admin::api-tokens.read", "category": "api tokens", "displayName": "Read", "subCategory": "general", }, Object { "action": "admin::api-tokens.update", "category": "api tokens", "displayName": "Update", "subCategory": "general", }, Object { "action": "admin::marketplace.plugins.install", "category": "plugins and marketplace", "displayName": "Install (only for dev env)", "subCategory": "plugins", }, Object { "action": "admin::marketplace.plugins.uninstall", "category": "plugins and marketplace", "displayName": "Uninstall (only for dev env)", "subCategory": "plugins", }, Object { "action": "admin::marketplace.read", "category": "plugins and marketplace", "displayName": "Access the marketplace", "subCategory": "marketplace", }, Object { "action": "admin::project-settings.update", "category": "project", "displayName": "Update the project level settings", "subCategory": "general", }, Object { "action": "admin::roles.create", "category": "users and roles", "displayName": "Create", "subCategory": "roles", }, Object { "action": "admin::roles.delete", "category": "users and roles", "displayName": "Delete", "subCategory": "roles", }, Object { "action": "admin::roles.read", "category": "users and roles", "displayName": "Read", "subCategory": "roles", }, Object { "action": "admin::roles.update", "category": "users and roles", "displayName": "Update", "subCategory": "roles", }, Object { "action": "admin::users.create", "category": "users and roles", "displayName": "Create (invite)", "subCategory": "users", }, Object { "action": "admin::users.delete", "category": "users and roles", "displayName": "Delete", "subCategory": "users", }, Object { "action": "admin::users.read", "category": "users and roles", "displayName": "Read", "subCategory": "users", }, Object { "action": "admin::users.update", "category": "users and roles", "displayName": "Update", "subCategory": "users", }, Object { "action": "admin::webhooks.create", "category": "webhooks", "displayName": "Create", "subCategory": "general", }, Object { "action": "admin::webhooks.delete", "category": "webhooks", "displayName": "Delete", "subCategory": "general", }, Object { "action": "admin::webhooks.read", "category": "webhooks", "displayName": "Read", "subCategory": "general", }, Object { "action": "admin::webhooks.update", "category": "webhooks", "displayName": "Update", "subCategory": "general", }, Object { "action": "plugin::email.settings.read", "category": "email", "displayName": "Access the Email Settings page", "subCategory": "general", }, Object { "action": "plugin::upload.settings.read", "category": "media library", "displayName": "Access the Media Library settings page", "subCategory": "general", }, ], }, } `); } } }); });
packages/core/admin/server/tests/admin-permission.test.e2e.js
1
https://github.com/strapi/strapi/commit/ce181eccf0a12a47c1e77517ffe0650a1cefe4ba
[ 0.9875176548957825, 0.020794861018657684, 0.00016202185361180454, 0.0002027009177254513, 0.1340448260307312 ]
{ "id": 3, "code_window": [ " \"displayName\": \"Access the marketplace\",\n", " \"subCategory\": \"marketplace\",\n", " },\n", " Object {\n", " \"action\": \"admin::project-settings.update\",\n", " \"category\": \"project\",\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " Object {\n", " \"action\": \"admin::project-settings.read\",\n", " \"category\": \"project\",\n", " \"displayName\": \"Read the project level settings\",\n", " \"subCategory\": \"general\",\n", " },\n" ], "file_path": "packages/core/admin/server/tests/admin-permission.test.e2e.js", "type": "add", "edit_start_line_idx": 822 }
import init from '../init'; describe('ADMIN | CONTAINERS | AUTH | init', () => { it('should return the initialState', () => { const initialState = { test: true, }; expect(init(initialState)).toEqual(initialState); }); });
packages/core/admin/admin/src/pages/AuthPage/tests/init.test.js
0
https://github.com/strapi/strapi/commit/ce181eccf0a12a47c1e77517ffe0650a1cefe4ba
[ 0.00016878773749340326, 0.00016852098633535206, 0.0001682542497292161, 0.00016852098633535206, 2.667438820935786e-7 ]
{ "id": 3, "code_window": [ " \"displayName\": \"Access the marketplace\",\n", " \"subCategory\": \"marketplace\",\n", " },\n", " Object {\n", " \"action\": \"admin::project-settings.update\",\n", " \"category\": \"project\",\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " Object {\n", " \"action\": \"admin::project-settings.read\",\n", " \"category\": \"project\",\n", " \"displayName\": \"Read the project level settings\",\n", " \"subCategory\": \"general\",\n", " },\n" ], "file_path": "packages/core/admin/server/tests/admin-permission.test.e2e.js", "type": "add", "edit_start_line_idx": 822 }
const baseConfig = require('../../../jest.base-config.front'); const pkg = require('./package.json'); module.exports = { ...baseConfig, displayName: (pkg.strapi && pkg.strapi.name) || pkg.name, roots: [__dirname], };
packages/core/helper-plugin/jest.config.front.js
0
https://github.com/strapi/strapi/commit/ce181eccf0a12a47c1e77517ffe0650a1cefe4ba
[ 0.00016948765551205724, 0.00016948765551205724, 0.00016948765551205724, 0.00016948765551205724, 0 ]
{ "id": 3, "code_window": [ " \"displayName\": \"Access the marketplace\",\n", " \"subCategory\": \"marketplace\",\n", " },\n", " Object {\n", " \"action\": \"admin::project-settings.update\",\n", " \"category\": \"project\",\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " Object {\n", " \"action\": \"admin::project-settings.read\",\n", " \"category\": \"project\",\n", " \"displayName\": \"Read the project level settings\",\n", " \"subCategory\": \"general\",\n", " },\n" ], "file_path": "packages/core/admin/server/tests/admin-permission.test.e2e.js", "type": "add", "edit_start_line_idx": 822 }
'use strict'; module.exports = {};
packages/generators/generators/lib/files/plugin/server/content-types/index.js
0
https://github.com/strapi/strapi/commit/ce181eccf0a12a47c1e77517ffe0650a1cefe4ba
[ 0.00017231701349373907, 0.00017231701349373907, 0.00017231701349373907, 0.00017231701349373907, 0 ]
{ "id": 0, "code_window": [ "// ConsoleWriter implements LoggerInterface and writes messages to terminal.\n", "type ConsoleWriter struct {\n", "\tlg *log.Logger\n", "\tLevel int `json:\"level\"`\n", "\tFormatting bool `json:\"formatting\"`\n", "}\n", "\n", "// create ConsoleWriter returning as LoggerInterface.\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "\tLevel LogLevel `json:\"level\"`\n", "\tFormatting bool `json:\"formatting\"`\n" ], "file_path": "pkg/log/console.go", "type": "replace", "edit_start_line_idx": 48 }
// Copyright 2014 The Gogs Authors. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. package log import ( "encoding/json" "fmt" "log" "os" "runtime" ) type Brush func(string) string func NewBrush(color string) Brush { pre := "\033[" reset := "\033[0m" return func(text string) string { return pre + color + "m" + text + reset } } var ( Red = NewBrush("1;31") Purple = NewBrush("1;35") Yellow = NewBrush("1;33") Green = NewBrush("1;32") Blue = NewBrush("1;34") Cyan = NewBrush("1;36") colors = []Brush{ Cyan, // Trace cyan Blue, // Debug blue Green, // Info green Yellow, // Warn yellow Red, // Error red Purple, // Critical purple Red, // Fatal red } consoleWriter = &ConsoleWriter{lg: log.New(os.Stdout, "", 0), Level: TRACE} ) // ConsoleWriter implements LoggerInterface and writes messages to terminal. type ConsoleWriter struct { lg *log.Logger Level int `json:"level"` Formatting bool `json:"formatting"` } // create ConsoleWriter returning as LoggerInterface. func NewConsole() LoggerInterface { return &ConsoleWriter{ lg: log.New(os.Stderr, "", log.Ldate|log.Ltime), Level: TRACE, Formatting: true, } } func (cw *ConsoleWriter) Init(config string) error { return json.Unmarshal([]byte(config), cw) } func (cw *ConsoleWriter) WriteMsg(msg string, skip, level int) error { if cw.Level > level { return nil } if runtime.GOOS == "windows" || !cw.Formatting { cw.lg.Println(msg) } else { cw.lg.Println(colors[level](msg)) } return nil } func (_ *ConsoleWriter) Flush() { } func (_ *ConsoleWriter) Destroy() { } func printConsole(level int, msg string) { consoleWriter.WriteMsg(msg, 0, level) } func printfConsole(level int, format string, v ...interface{}) { consoleWriter.WriteMsg(fmt.Sprintf(format, v...), 0, level) } // ConsoleTrace prints to stdout using TRACE colors func ConsoleTrace(s string) { printConsole(TRACE, s) } // ConsoleTracef prints a formatted string to stdout using TRACE colors func ConsoleTracef(format string, v ...interface{}) { printfConsole(TRACE, format, v...) } // ConsoleDebug prints to stdout using DEBUG colors func ConsoleDebug(s string) { printConsole(DEBUG, s) } // ConsoleDebugf prints a formatted string to stdout using DEBUG colors func ConsoleDebugf(format string, v ...interface{}) { printfConsole(DEBUG, format, v...) } // ConsoleInfo prints to stdout using INFO colors func ConsoleInfo(s string) { printConsole(INFO, s) } // ConsoleInfof prints a formatted string to stdout using INFO colors func ConsoleInfof(format string, v ...interface{}) { printfConsole(INFO, format, v...) } // ConsoleWarn prints to stdout using WARN colors func ConsoleWarn(s string) { printConsole(WARN, s) } // ConsoleWarnf prints a formatted string to stdout using WARN colors func ConsoleWarnf(format string, v ...interface{}) { printfConsole(WARN, format, v...) } // ConsoleError prints to stdout using ERROR colors func ConsoleError(s string) { printConsole(ERROR, s) } // ConsoleErrorf prints a formatted string to stdout using ERROR colors func ConsoleErrorf(format string, v ...interface{}) { printfConsole(ERROR, format, v...) } // ConsoleFatal prints to stdout using FATAL colors func ConsoleFatal(s string) { printConsole(FATAL, s) os.Exit(1) } // ConsoleFatalf prints a formatted string to stdout using FATAL colors func ConsoleFatalf(format string, v ...interface{}) { printfConsole(FATAL, format, v...) os.Exit(1) } func init() { Register("console", NewConsole) }
pkg/log/console.go
1
https://github.com/grafana/grafana/commit/bf943ddba38ced67da56f0cfd847760f41d31e61
[ 0.9945055842399597, 0.3071048855781555, 0.00016861609765328467, 0.009458031505346298, 0.44895562529563904 ]
{ "id": 0, "code_window": [ "// ConsoleWriter implements LoggerInterface and writes messages to terminal.\n", "type ConsoleWriter struct {\n", "\tlg *log.Logger\n", "\tLevel int `json:\"level\"`\n", "\tFormatting bool `json:\"formatting\"`\n", "}\n", "\n", "// create ConsoleWriter returning as LoggerInterface.\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "\tLevel LogLevel `json:\"level\"`\n", "\tFormatting bool `json:\"formatting\"`\n" ], "file_path": "pkg/log/console.go", "type": "replace", "edit_start_line_idx": 48 }
"<\t"
Godeps/_workspace/src/github.com/jmespath/go-jmespath/fuzz/corpus/expr-321
0
https://github.com/grafana/grafana/commit/bf943ddba38ced67da56f0cfd847760f41d31e61
[ 0.00017019291408360004, 0.00017019291408360004, 0.00017019291408360004, 0.00017019291408360004, 0 ]
{ "id": 0, "code_window": [ "// ConsoleWriter implements LoggerInterface and writes messages to terminal.\n", "type ConsoleWriter struct {\n", "\tlg *log.Logger\n", "\tLevel int `json:\"level\"`\n", "\tFormatting bool `json:\"formatting\"`\n", "}\n", "\n", "// create ConsoleWriter returning as LoggerInterface.\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "\tLevel LogLevel `json:\"level\"`\n", "\tFormatting bool `json:\"formatting\"`\n" ], "file_path": "pkg/log/console.go", "type": "replace", "edit_start_line_idx": 48 }
tL7
Godeps/_workspace/src/github.com/jmespath/go-jmespath/fuzz/corpus/expr-219
0
https://github.com/grafana/grafana/commit/bf943ddba38ced67da56f0cfd847760f41d31e61
[ 0.00017108634347096086, 0.00017108634347096086, 0.00017108634347096086, 0.00017108634347096086, 0 ]
{ "id": 0, "code_window": [ "// ConsoleWriter implements LoggerInterface and writes messages to terminal.\n", "type ConsoleWriter struct {\n", "\tlg *log.Logger\n", "\tLevel int `json:\"level\"`\n", "\tFormatting bool `json:\"formatting\"`\n", "}\n", "\n", "// create ConsoleWriter returning as LoggerInterface.\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "\tLevel LogLevel `json:\"level\"`\n", "\tFormatting bool `json:\"formatting\"`\n" ], "file_path": "pkg/log/console.go", "type": "replace", "edit_start_line_idx": 48 }
#! /usr/bin/env bash version=2.6.0 wget https://grafanarel.s3.amazonaws.com/builds/grafana_${version}_amd64.deb package_cloud push grafana/stable/debian/jessie grafana_${version}_amd64.deb package_cloud push grafana/stable/debian/wheezy grafana_${version}_amd64.deb package_cloud push grafana/testing/debian/jessie grafana_${version}_amd64.deb package_cloud push grafana/testing/debian/wheezy grafana_${version}_amd64.deb wget https://grafanarel.s3.amazonaws.com/builds/grafana-${version}-1.x86_64.rpm package_cloud push grafana/testing/el/6 grafana-${version}-1.x86_64.rpm package_cloud push grafana/testing/el/7 grafana-${version}-1.x86_64.rpm package_cloud push grafana/stable/el/7 grafana-${version}-1.x86_64.rpm package_cloud push grafana/stable/el/6 grafana-${version}-1.x86_64.rpm
packaging/publish/publish.sh
0
https://github.com/grafana/grafana/commit/bf943ddba38ced67da56f0cfd847760f41d31e61
[ 0.00017104475409723818, 0.0001704256283119321, 0.00016980648797471076, 0.0001704256283119321, 6.191330612637103e-7 ]
{ "id": 1, "code_window": [ "func (cw *ConsoleWriter) Init(config string) error {\n", "\treturn json.Unmarshal([]byte(config), cw)\n", "}\n", "\n", "func (cw *ConsoleWriter) WriteMsg(msg string, skip, level int) error {\n", "\tif cw.Level > level {\n", "\t\treturn nil\n", "\t}\n", "\tif runtime.GOOS == \"windows\" || !cw.Formatting {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "func (cw *ConsoleWriter) WriteMsg(msg string, skip int, level LogLevel) error {\n" ], "file_path": "pkg/log/console.go", "type": "replace", "edit_start_line_idx": 65 }
// Copyright 2014 The Gogs Authors. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. package log import ( "fmt" "os" "path/filepath" "runtime" "strings" "sync" ) var ( loggers []*Logger ) func NewLogger(bufLen int64, mode, config string) { logger := newLogger(bufLen) isExist := false for _, l := range loggers { if l.adapter == mode { isExist = true l = logger } } if !isExist { loggers = append(loggers, logger) } if err := logger.SetLogger(mode, config); err != nil { Fatal(1, "Fail to set logger(%s): %v", mode, err) } } func Trace(format string, v ...interface{}) { for _, logger := range loggers { logger.Trace(format, v...) } } func Debug(format string, v ...interface{}) { for _, logger := range loggers { logger.Debug(format, v...) } } func Info(format string, v ...interface{}) { for _, logger := range loggers { logger.Info(format, v...) } } func Warn(format string, v ...interface{}) { for _, logger := range loggers { logger.Warn(format, v...) } } func Error(skip int, format string, v ...interface{}) { for _, logger := range loggers { logger.Error(skip, format, v...) } } func Critical(skip int, format string, v ...interface{}) { for _, logger := range loggers { logger.Critical(skip, format, v...) } } func Fatal(skip int, format string, v ...interface{}) { Error(skip, format, v...) for _, l := range loggers { l.Close() } os.Exit(1) } func Close() { for _, l := range loggers { l.Close() // delete the logger. l = nil } // clear the loggers slice. loggers = nil } // .___ __ _____ // | | _____/ |_ ____________/ ____\____ ____ ____ // | |/ \ __\/ __ \_ __ \ __\\__ \ _/ ___\/ __ \ // | | | \ | \ ___/| | \/| | / __ \\ \__\ ___/ // |___|___| /__| \___ >__| |__| (____ /\___ >___ > // \/ \/ \/ \/ \/ type LogLevel int const ( TRACE = iota DEBUG INFO WARN ERROR CRITICAL FATAL ) // LoggerInterface represents behaviors of a logger provider. type LoggerInterface interface { Init(config string) error WriteMsg(msg string, skip, level int) error Destroy() Flush() } type loggerType func() LoggerInterface var adapters = make(map[string]loggerType) // Register registers given logger provider to adapters. func Register(name string, log loggerType) { if log == nil { panic("log: register provider is nil") } if _, dup := adapters[name]; dup { panic("log: register called twice for provider \"" + name + "\"") } adapters[name] = log } type logMsg struct { skip, level int msg string } // Logger is default logger in beego application. // it can contain several providers and log message into all providers. type Logger struct { adapter string lock sync.Mutex level int msg chan *logMsg outputs map[string]LoggerInterface quit chan bool } // newLogger initializes and returns a new logger. func newLogger(buffer int64) *Logger { l := &Logger{ msg: make(chan *logMsg, buffer), outputs: make(map[string]LoggerInterface), quit: make(chan bool), } go l.StartLogger() return l } // SetLogger sets new logger instanse with given logger adapter and config. func (l *Logger) SetLogger(adapter string, config string) error { l.lock.Lock() defer l.lock.Unlock() if log, ok := adapters[adapter]; ok { lg := log() if err := lg.Init(config); err != nil { return err } l.outputs[adapter] = lg l.adapter = adapter } else { panic("log: unknown adapter \"" + adapter + "\" (forgotten register?)") } return nil } // DelLogger removes a logger adapter instance. func (l *Logger) DelLogger(adapter string) error { l.lock.Lock() defer l.lock.Unlock() if lg, ok := l.outputs[adapter]; ok { lg.Destroy() delete(l.outputs, adapter) } else { panic("log: unknown adapter \"" + adapter + "\" (forgotten register?)") } return nil } func (l *Logger) writerMsg(skip, level int, msg string) error { if l.level > level { return nil } lm := &logMsg{ skip: skip, level: level, } // Only error information needs locate position for debugging. if lm.level >= ERROR { pc, file, line, ok := runtime.Caller(skip) if ok { // Get caller function name. fn := runtime.FuncForPC(pc) var fnName string if fn == nil { fnName = "?()" } else { fnName = strings.TrimLeft(filepath.Ext(fn.Name()), ".") + "()" } lm.msg = fmt.Sprintf("[%s:%d %s] %s", filepath.Base(file), line, fnName, msg) } else { lm.msg = msg } } else { lm.msg = msg } l.msg <- lm return nil } // StartLogger starts logger chan reading. func (l *Logger) StartLogger() { for { select { case bm := <-l.msg: for _, l := range l.outputs { if err := l.WriteMsg(bm.msg, bm.skip, bm.level); err != nil { fmt.Println("ERROR, unable to WriteMsg:", err) } } case <-l.quit: return } } } // Flush flushs all chan data. func (l *Logger) Flush() { for _, l := range l.outputs { l.Flush() } } // Close closes logger, flush all chan data and destroy all adapter instances. func (l *Logger) Close() { l.quit <- true for { if len(l.msg) > 0 { bm := <-l.msg for _, l := range l.outputs { if err := l.WriteMsg(bm.msg, bm.skip, bm.level); err != nil { fmt.Println("ERROR, unable to WriteMsg:", err) } } } else { break } } for _, l := range l.outputs { l.Flush() l.Destroy() } } func (l *Logger) Trace(format string, v ...interface{}) { msg := fmt.Sprintf("[T] "+format, v...) l.writerMsg(0, TRACE, msg) } func (l *Logger) Debug(format string, v ...interface{}) { msg := fmt.Sprintf("[D] "+format, v...) l.writerMsg(0, DEBUG, msg) } func (l *Logger) Info(format string, v ...interface{}) { msg := fmt.Sprintf("[I] "+format, v...) l.writerMsg(0, INFO, msg) } func (l *Logger) Warn(format string, v ...interface{}) { msg := fmt.Sprintf("[W] "+format, v...) l.writerMsg(0, WARN, msg) } func (l *Logger) Error(skip int, format string, v ...interface{}) { msg := fmt.Sprintf("[E] "+format, v...) l.writerMsg(skip, ERROR, msg) } func (l *Logger) Critical(skip int, format string, v ...interface{}) { msg := fmt.Sprintf("[C] "+format, v...) l.writerMsg(skip, CRITICAL, msg) } func (l *Logger) Fatal(skip int, format string, v ...interface{}) { msg := fmt.Sprintf("[F] "+format, v...) l.writerMsg(skip, FATAL, msg) l.Close() os.Exit(1) }
pkg/log/log.go
1
https://github.com/grafana/grafana/commit/bf943ddba38ced67da56f0cfd847760f41d31e61
[ 0.9976958632469177, 0.2647055685520172, 0.0001713091623969376, 0.007451278623193502, 0.3935542106628418 ]
{ "id": 1, "code_window": [ "func (cw *ConsoleWriter) Init(config string) error {\n", "\treturn json.Unmarshal([]byte(config), cw)\n", "}\n", "\n", "func (cw *ConsoleWriter) WriteMsg(msg string, skip, level int) error {\n", "\tif cw.Level > level {\n", "\t\treturn nil\n", "\t}\n", "\tif runtime.GOOS == \"windows\" || !cw.Formatting {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "func (cw *ConsoleWriter) WriteMsg(msg string, skip int, level LogLevel) error {\n" ], "file_path": "pkg/log/console.go", "type": "replace", "edit_start_line_idx": 65 }
package models import ( "testing" . "github.com/smartystreets/goconvey/convey" ) func TestDashboardModel(t *testing.T) { Convey("When generating slug", t, func() { dashboard := NewDashboard("Grafana Play Home") dashboard.UpdateSlug() So(dashboard.Slug, ShouldEqual, "grafana-play-home") }) Convey("Given a dashboard json", t, func() { json := map[string]interface{}{ "title": "test dash", } Convey("With tags as string value", func() { json["tags"] = "" dash := NewDashboardFromJson(json) So(len(dash.GetTags()), ShouldEqual, 0) }) }) }
pkg/models/dashboards_test.go
0
https://github.com/grafana/grafana/commit/bf943ddba38ced67da56f0cfd847760f41d31e61
[ 0.0008926207083277404, 0.0004562451795209199, 0.00018616291345097125, 0.0003730985044967383, 0.0002894294448196888 ]
{ "id": 1, "code_window": [ "func (cw *ConsoleWriter) Init(config string) error {\n", "\treturn json.Unmarshal([]byte(config), cw)\n", "}\n", "\n", "func (cw *ConsoleWriter) WriteMsg(msg string, skip, level int) error {\n", "\tif cw.Level > level {\n", "\t\treturn nil\n", "\t}\n", "\tif runtime.GOOS == \"windows\" || !cw.Formatting {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "func (cw *ConsoleWriter) WriteMsg(msg string, skip int, level LogLevel) error {\n" ], "file_path": "pkg/log/console.go", "type": "replace", "edit_start_line_idx": 65 }
package jmespath import ( "github.com/stretchr/testify/assert" "testing" ) func TestSlicePositiveStep(t *testing.T) { assert := assert.New(t) input := make([]interface{}, 5) input[0] = 0 input[1] = 1 input[2] = 2 input[3] = 3 input[4] = 4 result, err := slice(input, []sliceParam{sliceParam{0, true}, sliceParam{3, true}, sliceParam{1, true}}) assert.Nil(err) assert.Equal(input[:3], result) } func TestIsFalseJSONTypes(t *testing.T) { assert := assert.New(t) assert.True(isFalse(false)) assert.True(isFalse("")) var empty []interface{} assert.True(isFalse(empty)) m := make(map[string]interface{}) assert.True(isFalse(m)) assert.True(isFalse(nil)) } func TestIsFalseWithUserDefinedStructs(t *testing.T) { assert := assert.New(t) type nilStructType struct { SliceOfPointers []*string } nilStruct := nilStructType{SliceOfPointers: nil} assert.True(isFalse(nilStruct.SliceOfPointers)) // A user defined struct will never be false though, // even if it's fields are the zero type. assert.False(isFalse(nilStruct)) } func TestIsFalseWithNilInterface(t *testing.T) { assert := assert.New(t) var a *int = nil var nilInterface interface{} nilInterface = a assert.True(isFalse(nilInterface)) } func TestIsFalseWithMapOfUserStructs(t *testing.T) { assert := assert.New(t) type foo struct { Bar string Baz string } m := make(map[int]foo) assert.True(isFalse(m)) } func TestObjsEqual(t *testing.T) { assert := assert.New(t) assert.True(objsEqual("foo", "foo")) assert.True(objsEqual(20, 20)) assert.True(objsEqual([]int{1, 2, 3}, []int{1, 2, 3})) assert.True(objsEqual(nil, nil)) assert.True(!objsEqual(nil, "foo")) assert.True(objsEqual([]int{}, []int{})) assert.True(!objsEqual([]int{}, nil)) }
Godeps/_workspace/src/github.com/jmespath/go-jmespath/util_test.go
0
https://github.com/grafana/grafana/commit/bf943ddba38ced67da56f0cfd847760f41d31e61
[ 0.0006788963219150901, 0.00029677205020561814, 0.00017169705824926496, 0.00021303282119333744, 0.00017246551578864455 ]
{ "id": 1, "code_window": [ "func (cw *ConsoleWriter) Init(config string) error {\n", "\treturn json.Unmarshal([]byte(config), cw)\n", "}\n", "\n", "func (cw *ConsoleWriter) WriteMsg(msg string, skip, level int) error {\n", "\tif cw.Level > level {\n", "\t\treturn nil\n", "\t}\n", "\tif runtime.GOOS == \"windows\" || !cw.Formatting {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "func (cw *ConsoleWriter) WriteMsg(msg string, skip int, level LogLevel) error {\n" ], "file_path": "pkg/log/console.go", "type": "replace", "edit_start_line_idx": 65 }
package xorm import ( "crypto/tls" "errors" "fmt" "strconv" "strings" "time" "github.com/go-xorm/core" ) // func init() { // RegisterDialect("mysql", &mysql{}) // } var ( mysqlReservedWords = map[string]bool{ "ADD": true, "ALL": true, "ALTER": true, "ANALYZE": true, "AND": true, "AS": true, "ASC": true, "ASENSITIVE": true, "BEFORE": true, "BETWEEN": true, "BIGINT": true, "BINARY": true, "BLOB": true, "BOTH": true, "BY": true, "CALL": true, "CASCADE": true, "CASE": true, "CHANGE": true, "CHAR": true, "CHARACTER": true, "CHECK": true, "COLLATE": true, "COLUMN": true, "CONDITION": true, "CONNECTION": true, "CONSTRAINT": true, "CONTINUE": true, "CONVERT": true, "CREATE": true, "CROSS": true, "CURRENT_DATE": true, "CURRENT_TIME": true, "CURRENT_TIMESTAMP": true, "CURRENT_USER": true, "CURSOR": true, "DATABASE": true, "DATABASES": true, "DAY_HOUR": true, "DAY_MICROSECOND": true, "DAY_MINUTE": true, "DAY_SECOND": true, "DEC": true, "DECIMAL": true, "DECLARE": true, "DEFAULT": true, "DELAYED": true, "DELETE": true, "DESC": true, "DESCRIBE": true, "DETERMINISTIC": true, "DISTINCT": true, "DISTINCTROW": true, "DIV": true, "DOUBLE": true, "DROP": true, "DUAL": true, "EACH": true, "ELSE": true, "ELSEIF": true, "ENCLOSED": true, "ESCAPED": true, "EXISTS": true, "EXIT": true, "EXPLAIN": true, "FALSE": true, "FETCH": true, "FLOAT": true, "FLOAT4": true, "FLOAT8": true, "FOR": true, "FORCE": true, "FOREIGN": true, "FROM": true, "FULLTEXT": true, "GOTO": true, "GRANT": true, "GROUP": true, "HAVING": true, "HIGH_PRIORITY": true, "HOUR_MICROSECOND": true, "HOUR_MINUTE": true, "HOUR_SECOND": true, "IF": true, "IGNORE": true, "IN": true, "INDEX": true, "INFILE": true, "INNER": true, "INOUT": true, "INSENSITIVE": true, "INSERT": true, "INT": true, "INT1": true, "INT2": true, "INT3": true, "INT4": true, "INT8": true, "INTEGER": true, "INTERVAL": true, "INTO": true, "IS": true, "ITERATE": true, "JOIN": true, "KEY": true, "KEYS": true, "KILL": true, "LABEL": true, "LEADING": true, "LEAVE": true, "LEFT": true, "LIKE": true, "LIMIT": true, "LINEAR": true, "LINES": true, "LOAD": true, "LOCALTIME": true, "LOCALTIMESTAMP": true, "LOCK": true, "LONG": true, "LONGBLOB": true, "LONGTEXT": true, "LOOP": true, "LOW_PRIORITY": true, "MATCH": true, "MEDIUMBLOB": true, "MEDIUMINT": true, "MEDIUMTEXT": true, "MIDDLEINT": true, "MINUTE_MICROSECOND": true, "MINUTE_SECOND": true, "MOD": true, "MODIFIES": true, "NATURAL": true, "NOT": true, "NO_WRITE_TO_BINLOG": true, "NULL": true, "NUMERIC": true, "ON OPTIMIZE": true, "OPTION": true, "OPTIONALLY": true, "OR": true, "ORDER": true, "OUT": true, "OUTER": true, "OUTFILE": true, "PRECISION": true, "PRIMARY": true, "PROCEDURE": true, "PURGE": true, "RAID0": true, "RANGE": true, "READ": true, "READS": true, "REAL": true, "REFERENCES": true, "REGEXP": true, "RELEASE": true, "RENAME": true, "REPEAT": true, "REPLACE": true, "REQUIRE": true, "RESTRICT": true, "RETURN": true, "REVOKE": true, "RIGHT": true, "RLIKE": true, "SCHEMA": true, "SCHEMAS": true, "SECOND_MICROSECOND": true, "SELECT": true, "SENSITIVE": true, "SEPARATOR": true, "SET": true, "SHOW": true, "SMALLINT": true, "SPATIAL": true, "SPECIFIC": true, "SQL": true, "SQLEXCEPTION": true, "SQLSTATE": true, "SQLWARNING": true, "SQL_BIG_RESULT": true, "SQL_CALC_FOUND_ROWS": true, "SQL_SMALL_RESULT": true, "SSL": true, "STARTING": true, "STRAIGHT_JOIN": true, "TABLE": true, "TERMINATED": true, "THEN": true, "TINYBLOB": true, "TINYINT": true, "TINYTEXT": true, "TO": true, "TRAILING": true, "TRIGGER": true, "TRUE": true, "UNDO": true, "UNION": true, "UNIQUE": true, "UNLOCK": true, "UNSIGNED": true, "UPDATE": true, "USAGE": true, "USE": true, "USING": true, "UTC_DATE": true, "UTC_TIME": true, "UTC_TIMESTAMP": true, "VALUES": true, "VARBINARY": true, "VARCHAR": true, "VARCHARACTER": true, "VARYING": true, "WHEN": true, "WHERE": true, "WHILE": true, "WITH": true, "WRITE": true, "X509": true, "XOR": true, "YEAR_MONTH": true, "ZEROFILL": true, } ) type mysql struct { core.Base net string addr string params map[string]string loc *time.Location timeout time.Duration tls *tls.Config allowAllFiles bool allowOldPasswords bool clientFoundRows bool } func (db *mysql) Init(d *core.DB, uri *core.Uri, drivername, dataSourceName string) error { return db.Base.Init(d, db, uri, drivername, dataSourceName) } func (db *mysql) SqlType(c *core.Column) string { var res string switch t := c.SQLType.Name; t { case core.Bool: res = core.TinyInt c.Length = 1 case core.Serial: c.IsAutoIncrement = true c.IsPrimaryKey = true c.Nullable = false res = core.Int case core.BigSerial: c.IsAutoIncrement = true c.IsPrimaryKey = true c.Nullable = false res = core.BigInt case core.Bytea: res = core.Blob case core.TimeStampz: res = core.Char c.Length = 64 case core.Enum: //mysql enum res = core.Enum res += "(" opts := "" for v, _ := range c.EnumOptions { opts += fmt.Sprintf(",'%v'", v) } res += strings.TrimLeft(opts, ",") res += ")" case core.Set: //mysql set res = core.Set res += "(" opts := "" for v, _ := range c.SetOptions { opts += fmt.Sprintf(",'%v'", v) } res += strings.TrimLeft(opts, ",") res += ")" case core.NVarchar: res = core.Varchar case core.Uuid: res = core.Varchar c.Length = 40 default: res = t } var hasLen1 bool = (c.Length > 0) var hasLen2 bool = (c.Length2 > 0) if res == core.BigInt && !hasLen1 && !hasLen2 { c.Length = 20 hasLen1 = true } if hasLen2 { res += "(" + strconv.Itoa(c.Length) + "," + strconv.Itoa(c.Length2) + ")" } else if hasLen1 { res += "(" + strconv.Itoa(c.Length) + ")" } return res } func (db *mysql) SupportInsertMany() bool { return true } func (db *mysql) IsReserved(name string) bool { _, ok := mysqlReservedWords[name] return ok } func (db *mysql) Quote(name string) string { return "`" + name + "`" } func (db *mysql) QuoteStr() string { return "`" } func (db *mysql) SupportEngine() bool { return true } func (db *mysql) AutoIncrStr() string { return "AUTO_INCREMENT" } func (db *mysql) SupportCharset() bool { return true } func (db *mysql) IndexOnTable() bool { return true } func (db *mysql) IndexCheckSql(tableName, idxName string) (string, []interface{}) { args := []interface{}{db.DbName, tableName, idxName} sql := "SELECT `INDEX_NAME` FROM `INFORMATION_SCHEMA`.`STATISTICS`" sql += " WHERE `TABLE_SCHEMA` = ? AND `TABLE_NAME` = ? AND `INDEX_NAME`=?" return sql, args } /*func (db *mysql) ColumnCheckSql(tableName, colName string) (string, []interface{}) { args := []interface{}{db.DbName, tableName, colName} sql := "SELECT `COLUMN_NAME` FROM `INFORMATION_SCHEMA`.`COLUMNS` WHERE `TABLE_SCHEMA` = ? AND `TABLE_NAME` = ? AND `COLUMN_NAME` = ?" return sql, args }*/ func (db *mysql) TableCheckSql(tableName string) (string, []interface{}) { args := []interface{}{db.DbName, tableName} sql := "SELECT `TABLE_NAME` from `INFORMATION_SCHEMA`.`TABLES` WHERE `TABLE_SCHEMA`=? and `TABLE_NAME`=?" return sql, args } func (db *mysql) GetColumns(tableName string) ([]string, map[string]*core.Column, error) { args := []interface{}{db.DbName, tableName} s := "SELECT `COLUMN_NAME`, `IS_NULLABLE`, `COLUMN_DEFAULT`, `COLUMN_TYPE`," + " `COLUMN_KEY`, `EXTRA` FROM `INFORMATION_SCHEMA`.`COLUMNS` WHERE `TABLE_SCHEMA` = ? AND `TABLE_NAME` = ?" rows, err := db.DB().Query(s, args...) if db.Logger != nil { db.Logger.Info("[sql]", s, args) } if err != nil { return nil, nil, err } defer rows.Close() cols := make(map[string]*core.Column) colSeq := make([]string, 0) for rows.Next() { col := new(core.Column) col.Indexes = make(map[string]bool) var columnName, isNullable, colType, colKey, extra string var colDefault *string err = rows.Scan(&columnName, &isNullable, &colDefault, &colType, &colKey, &extra) if err != nil { return nil, nil, err } col.Name = strings.Trim(columnName, "` ") if "YES" == isNullable { col.Nullable = true } if colDefault != nil { col.Default = *colDefault if col.Default == "" { col.DefaultIsEmpty = true } } cts := strings.Split(colType, "(") colName := cts[0] colType = strings.ToUpper(colName) var len1, len2 int if len(cts) == 2 { idx := strings.Index(cts[1], ")") if colType == core.Enum && cts[1][0] == '\'' { //enum options := strings.Split(cts[1][0:idx], ",") col.EnumOptions = make(map[string]int) for k, v := range options { v = strings.TrimSpace(v) v = strings.Trim(v, "'") col.EnumOptions[v] = k } } else if colType == core.Set && cts[1][0] == '\'' { options := strings.Split(cts[1][0:idx], ",") col.SetOptions = make(map[string]int) for k, v := range options { v = strings.TrimSpace(v) v = strings.Trim(v, "'") col.SetOptions[v] = k } } else { lens := strings.Split(cts[1][0:idx], ",") len1, err = strconv.Atoi(strings.TrimSpace(lens[0])) if err != nil { return nil, nil, err } if len(lens) == 2 { len2, err = strconv.Atoi(lens[1]) if err != nil { return nil, nil, err } } } } if colType == "FLOAT UNSIGNED" { colType = "FLOAT" } col.Length = len1 col.Length2 = len2 if _, ok := core.SqlTypes[colType]; ok { col.SQLType = core.SQLType{colType, len1, len2} } else { return nil, nil, errors.New(fmt.Sprintf("unkonw colType %v", colType)) } if colKey == "PRI" { col.IsPrimaryKey = true } if colKey == "UNI" { //col.is } if extra == "auto_increment" { col.IsAutoIncrement = true } if col.SQLType.IsText() || col.SQLType.IsTime() { if col.Default != "" { col.Default = "'" + col.Default + "'" } else { if col.DefaultIsEmpty { col.Default = "''" } } } cols[col.Name] = col colSeq = append(colSeq, col.Name) } return colSeq, cols, nil } func (db *mysql) GetTables() ([]*core.Table, error) { args := []interface{}{db.DbName} s := "SELECT `TABLE_NAME`, `ENGINE`, `TABLE_ROWS`, `AUTO_INCREMENT` from " + "`INFORMATION_SCHEMA`.`TABLES` WHERE `TABLE_SCHEMA`=? AND (`ENGINE`='MyISAM' OR `ENGINE` = 'InnoDB')" rows, err := db.DB().Query(s, args...) if db.Logger != nil { db.Logger.Info("[sql]", s, args) } if err != nil { return nil, err } defer rows.Close() tables := make([]*core.Table, 0) for rows.Next() { table := core.NewEmptyTable() var name, engine, tableRows string var autoIncr *string err = rows.Scan(&name, &engine, &tableRows, &autoIncr) if err != nil { return nil, err } table.Name = name table.StoreEngine = engine tables = append(tables, table) } return tables, nil } func (db *mysql) GetIndexes(tableName string) (map[string]*core.Index, error) { args := []interface{}{db.DbName, tableName} s := "SELECT `INDEX_NAME`, `NON_UNIQUE`, `COLUMN_NAME` FROM `INFORMATION_SCHEMA`.`STATISTICS` WHERE `TABLE_SCHEMA` = ? AND `TABLE_NAME` = ?" rows, err := db.DB().Query(s, args...) if db.Logger != nil { db.Logger.Info("[sql]", s, args) } if err != nil { return nil, err } defer rows.Close() indexes := make(map[string]*core.Index, 0) for rows.Next() { var indexType int var indexName, colName, nonUnique string err = rows.Scan(&indexName, &nonUnique, &colName) if err != nil { return nil, err } if indexName == "PRIMARY" { continue } if "YES" == nonUnique || nonUnique == "1" { indexType = core.IndexType } else { indexType = core.UniqueType } colName = strings.Trim(colName, "` ") var isRegular bool if strings.HasPrefix(indexName, "IDX_"+tableName) || strings.HasPrefix(indexName, "UQE_"+tableName) { indexName = indexName[5+len(tableName) : len(indexName)] isRegular = true } var index *core.Index var ok bool if index, ok = indexes[indexName]; !ok { index = new(core.Index) index.IsRegular = isRegular index.Type = indexType index.Name = indexName indexes[indexName] = index } index.AddColumn(colName) } return indexes, nil } func (db *mysql) Filters() []core.Filter { return []core.Filter{&core.IdFilter{}} }
Godeps/_workspace/src/github.com/go-xorm/xorm/mysql_dialect.go
0
https://github.com/grafana/grafana/commit/bf943ddba38ced67da56f0cfd847760f41d31e61
[ 0.19276116788387299, 0.00414194306358695, 0.00017092442431021482, 0.00022047420497983694, 0.026946350932121277 ]
{ "id": 2, "code_window": [ "}\n", "\n", "func (_ *ConsoleWriter) Destroy() {\n", "}\n", "\n", "func printConsole(level int, msg string) {\n", "\tconsoleWriter.WriteMsg(msg, 0, level)\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "func printConsole(level LogLevel, msg string) {\n" ], "file_path": "pkg/log/console.go", "type": "replace", "edit_start_line_idx": 84 }
// Copyright 2014 The Gogs Authors. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. package log import ( "encoding/json" "fmt" "log" "os" "runtime" ) type Brush func(string) string func NewBrush(color string) Brush { pre := "\033[" reset := "\033[0m" return func(text string) string { return pre + color + "m" + text + reset } } var ( Red = NewBrush("1;31") Purple = NewBrush("1;35") Yellow = NewBrush("1;33") Green = NewBrush("1;32") Blue = NewBrush("1;34") Cyan = NewBrush("1;36") colors = []Brush{ Cyan, // Trace cyan Blue, // Debug blue Green, // Info green Yellow, // Warn yellow Red, // Error red Purple, // Critical purple Red, // Fatal red } consoleWriter = &ConsoleWriter{lg: log.New(os.Stdout, "", 0), Level: TRACE} ) // ConsoleWriter implements LoggerInterface and writes messages to terminal. type ConsoleWriter struct { lg *log.Logger Level int `json:"level"` Formatting bool `json:"formatting"` } // create ConsoleWriter returning as LoggerInterface. func NewConsole() LoggerInterface { return &ConsoleWriter{ lg: log.New(os.Stderr, "", log.Ldate|log.Ltime), Level: TRACE, Formatting: true, } } func (cw *ConsoleWriter) Init(config string) error { return json.Unmarshal([]byte(config), cw) } func (cw *ConsoleWriter) WriteMsg(msg string, skip, level int) error { if cw.Level > level { return nil } if runtime.GOOS == "windows" || !cw.Formatting { cw.lg.Println(msg) } else { cw.lg.Println(colors[level](msg)) } return nil } func (_ *ConsoleWriter) Flush() { } func (_ *ConsoleWriter) Destroy() { } func printConsole(level int, msg string) { consoleWriter.WriteMsg(msg, 0, level) } func printfConsole(level int, format string, v ...interface{}) { consoleWriter.WriteMsg(fmt.Sprintf(format, v...), 0, level) } // ConsoleTrace prints to stdout using TRACE colors func ConsoleTrace(s string) { printConsole(TRACE, s) } // ConsoleTracef prints a formatted string to stdout using TRACE colors func ConsoleTracef(format string, v ...interface{}) { printfConsole(TRACE, format, v...) } // ConsoleDebug prints to stdout using DEBUG colors func ConsoleDebug(s string) { printConsole(DEBUG, s) } // ConsoleDebugf prints a formatted string to stdout using DEBUG colors func ConsoleDebugf(format string, v ...interface{}) { printfConsole(DEBUG, format, v...) } // ConsoleInfo prints to stdout using INFO colors func ConsoleInfo(s string) { printConsole(INFO, s) } // ConsoleInfof prints a formatted string to stdout using INFO colors func ConsoleInfof(format string, v ...interface{}) { printfConsole(INFO, format, v...) } // ConsoleWarn prints to stdout using WARN colors func ConsoleWarn(s string) { printConsole(WARN, s) } // ConsoleWarnf prints a formatted string to stdout using WARN colors func ConsoleWarnf(format string, v ...interface{}) { printfConsole(WARN, format, v...) } // ConsoleError prints to stdout using ERROR colors func ConsoleError(s string) { printConsole(ERROR, s) } // ConsoleErrorf prints a formatted string to stdout using ERROR colors func ConsoleErrorf(format string, v ...interface{}) { printfConsole(ERROR, format, v...) } // ConsoleFatal prints to stdout using FATAL colors func ConsoleFatal(s string) { printConsole(FATAL, s) os.Exit(1) } // ConsoleFatalf prints a formatted string to stdout using FATAL colors func ConsoleFatalf(format string, v ...interface{}) { printfConsole(FATAL, format, v...) os.Exit(1) } func init() { Register("console", NewConsole) }
pkg/log/console.go
1
https://github.com/grafana/grafana/commit/bf943ddba38ced67da56f0cfd847760f41d31e61
[ 0.9989508390426636, 0.49716198444366455, 0.00016973380115814507, 0.48503023386001587, 0.49366188049316406 ]
{ "id": 2, "code_window": [ "}\n", "\n", "func (_ *ConsoleWriter) Destroy() {\n", "}\n", "\n", "func printConsole(level int, msg string) {\n", "\tconsoleWriter.WriteMsg(msg, 0, level)\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "func printConsole(level LogLevel, msg string) {\n" ], "file_path": "pkg/log/console.go", "type": "replace", "edit_start_line_idx": 84 }
//LRUCacher implements Cacher according to LRU algorithm package xorm import ( "container/list" "fmt" "sync" "time" "github.com/go-xorm/core" ) type LRUCacher struct { idList *list.List sqlList *list.List idIndex map[string]map[string]*list.Element sqlIndex map[string]map[string]*list.Element store core.CacheStore mutex sync.Mutex // maxSize int MaxElementSize int Expired time.Duration GcInterval time.Duration } func NewLRUCacher(store core.CacheStore, maxElementSize int) *LRUCacher { return NewLRUCacher2(store, 3600*time.Second, maxElementSize) } func NewLRUCacher2(store core.CacheStore, expired time.Duration, maxElementSize int) *LRUCacher { cacher := &LRUCacher{store: store, idList: list.New(), sqlList: list.New(), Expired: expired, GcInterval: core.CacheGcInterval, MaxElementSize: maxElementSize, sqlIndex: make(map[string]map[string]*list.Element), idIndex: make(map[string]map[string]*list.Element), } cacher.RunGC() return cacher } //func NewLRUCacher3(store CacheStore, expired time.Duration, maxSize int) *LRUCacher { // return newLRUCacher(store, expired, maxSize, 0) //} // RunGC run once every m.GcInterval func (m *LRUCacher) RunGC() { time.AfterFunc(m.GcInterval, func() { m.RunGC() m.GC() }) } // GC check ids lit and sql list to remove all element expired func (m *LRUCacher) GC() { //fmt.Println("begin gc ...") //defer fmt.Println("end gc ...") m.mutex.Lock() defer m.mutex.Unlock() var removedNum int for e := m.idList.Front(); e != nil; { if removedNum <= core.CacheGcMaxRemoved && time.Now().Sub(e.Value.(*idNode).lastVisit) > m.Expired { removedNum++ next := e.Next() //fmt.Println("removing ...", e.Value) node := e.Value.(*idNode) m.delBean(node.tbName, node.id) e = next } else { //fmt.Printf("removing %d cache nodes ..., left %d\n", removedNum, m.idList.Len()) break } } removedNum = 0 for e := m.sqlList.Front(); e != nil; { if removedNum <= core.CacheGcMaxRemoved && time.Now().Sub(e.Value.(*sqlNode).lastVisit) > m.Expired { removedNum++ next := e.Next() //fmt.Println("removing ...", e.Value) node := e.Value.(*sqlNode) m.delIds(node.tbName, node.sql) e = next } else { //fmt.Printf("removing %d cache nodes ..., left %d\n", removedNum, m.sqlList.Len()) break } } } // Get all bean's ids according to sql and parameter from cache func (m *LRUCacher) GetIds(tableName, sql string) interface{} { m.mutex.Lock() defer m.mutex.Unlock() if _, ok := m.sqlIndex[tableName]; !ok { m.sqlIndex[tableName] = make(map[string]*list.Element) } if v, err := m.store.Get(sql); err == nil { if el, ok := m.sqlIndex[tableName][sql]; !ok { el = m.sqlList.PushBack(newSqlNode(tableName, sql)) m.sqlIndex[tableName][sql] = el } else { lastTime := el.Value.(*sqlNode).lastVisit // if expired, remove the node and return nil if time.Now().Sub(lastTime) > m.Expired { m.delIds(tableName, sql) return nil } m.sqlList.MoveToBack(el) el.Value.(*sqlNode).lastVisit = time.Now() } return v } else { m.delIds(tableName, sql) } return nil } // Get bean according tableName and id from cache func (m *LRUCacher) GetBean(tableName string, id string) interface{} { m.mutex.Lock() defer m.mutex.Unlock() if _, ok := m.idIndex[tableName]; !ok { m.idIndex[tableName] = make(map[string]*list.Element) } tid := genId(tableName, id) if v, err := m.store.Get(tid); err == nil { if el, ok := m.idIndex[tableName][id]; ok { lastTime := el.Value.(*idNode).lastVisit // if expired, remove the node and return nil if time.Now().Sub(lastTime) > m.Expired { m.delBean(tableName, id) //m.clearIds(tableName) return nil } m.idList.MoveToBack(el) el.Value.(*idNode).lastVisit = time.Now() } else { el = m.idList.PushBack(newIdNode(tableName, id)) m.idIndex[tableName][id] = el } return v } else { // store bean is not exist, then remove memory's index m.delBean(tableName, id) //m.clearIds(tableName) return nil } } // Clear all sql-ids mapping on table tableName from cache func (m *LRUCacher) clearIds(tableName string) { if tis, ok := m.sqlIndex[tableName]; ok { for sql, v := range tis { m.sqlList.Remove(v) m.store.Del(sql) } } m.sqlIndex[tableName] = make(map[string]*list.Element) } func (m *LRUCacher) ClearIds(tableName string) { m.mutex.Lock() defer m.mutex.Unlock() m.clearIds(tableName) } func (m *LRUCacher) clearBeans(tableName string) { if tis, ok := m.idIndex[tableName]; ok { for id, v := range tis { m.idList.Remove(v) tid := genId(tableName, id) m.store.Del(tid) } } m.idIndex[tableName] = make(map[string]*list.Element) } func (m *LRUCacher) ClearBeans(tableName string) { m.mutex.Lock() defer m.mutex.Unlock() m.clearBeans(tableName) } func (m *LRUCacher) PutIds(tableName, sql string, ids interface{}) { m.mutex.Lock() defer m.mutex.Unlock() if _, ok := m.sqlIndex[tableName]; !ok { m.sqlIndex[tableName] = make(map[string]*list.Element) } if el, ok := m.sqlIndex[tableName][sql]; !ok { el = m.sqlList.PushBack(newSqlNode(tableName, sql)) m.sqlIndex[tableName][sql] = el } else { el.Value.(*sqlNode).lastVisit = time.Now() } m.store.Put(sql, ids) if m.sqlList.Len() > m.MaxElementSize { e := m.sqlList.Front() node := e.Value.(*sqlNode) m.delIds(node.tbName, node.sql) } } func (m *LRUCacher) PutBean(tableName string, id string, obj interface{}) { m.mutex.Lock() defer m.mutex.Unlock() var el *list.Element var ok bool if el, ok = m.idIndex[tableName][id]; !ok { el = m.idList.PushBack(newIdNode(tableName, id)) m.idIndex[tableName][id] = el } else { el.Value.(*idNode).lastVisit = time.Now() } m.store.Put(genId(tableName, id), obj) if m.idList.Len() > m.MaxElementSize { e := m.idList.Front() node := e.Value.(*idNode) m.delBean(node.tbName, node.id) } } func (m *LRUCacher) delIds(tableName, sql string) { if _, ok := m.sqlIndex[tableName]; ok { if el, ok := m.sqlIndex[tableName][sql]; ok { delete(m.sqlIndex[tableName], sql) m.sqlList.Remove(el) } } m.store.Del(sql) } func (m *LRUCacher) DelIds(tableName, sql string) { m.mutex.Lock() defer m.mutex.Unlock() m.delIds(tableName, sql) } func (m *LRUCacher) delBean(tableName string, id string) { tid := genId(tableName, id) if el, ok := m.idIndex[tableName][id]; ok { delete(m.idIndex[tableName], id) m.idList.Remove(el) m.clearIds(tableName) } m.store.Del(tid) } func (m *LRUCacher) DelBean(tableName string, id string) { m.mutex.Lock() defer m.mutex.Unlock() m.delBean(tableName, id) } type idNode struct { tbName string id string lastVisit time.Time } type sqlNode struct { tbName string sql string lastVisit time.Time } func genSqlKey(sql string, args interface{}) string { return fmt.Sprintf("%v-%v", sql, args) } func genId(prefix string, id string) string { return fmt.Sprintf("%v-%v", prefix, id) } func newIdNode(tbName string, id string) *idNode { return &idNode{tbName, id, time.Now()} } func newSqlNode(tbName, sql string) *sqlNode { return &sqlNode{tbName, sql, time.Now()} }
Godeps/_workspace/src/github.com/go-xorm/xorm/lru_cacher.go
0
https://github.com/grafana/grafana/commit/bf943ddba38ced67da56f0cfd847760f41d31e61
[ 0.9774460196495056, 0.0766894519329071, 0.00016644870629534125, 0.00017179269343614578, 0.23153243958950043 ]
{ "id": 2, "code_window": [ "}\n", "\n", "func (_ *ConsoleWriter) Destroy() {\n", "}\n", "\n", "func printConsole(level int, msg string) {\n", "\tconsoleWriter.WriteMsg(msg, 0, level)\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "func printConsole(level LogLevel, msg string) {\n" ], "file_path": "pkg/log/console.go", "type": "replace", "edit_start_line_idx": 84 }
package request_test import ( "bytes" "encoding/json" "fmt" "io" "io/ioutil" "net/http" "runtime" "testing" "time" "github.com/stretchr/testify/assert" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/aws/credentials" "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/awstesting" ) type testData struct { Data string } func body(str string) io.ReadCloser { return ioutil.NopCloser(bytes.NewReader([]byte(str))) } func unmarshal(req *request.Request) { defer req.HTTPResponse.Body.Close() if req.Data != nil { json.NewDecoder(req.HTTPResponse.Body).Decode(req.Data) } return } func unmarshalError(req *request.Request) { bodyBytes, err := ioutil.ReadAll(req.HTTPResponse.Body) if err != nil { req.Error = awserr.New("UnmarshaleError", req.HTTPResponse.Status, err) return } if len(bodyBytes) == 0 { req.Error = awserr.NewRequestFailure( awserr.New("UnmarshaleError", req.HTTPResponse.Status, fmt.Errorf("empty body")), req.HTTPResponse.StatusCode, "", ) return } var jsonErr jsonErrorResponse if err := json.Unmarshal(bodyBytes, &jsonErr); err != nil { req.Error = awserr.New("UnmarshaleError", "JSON unmarshal", err) return } req.Error = awserr.NewRequestFailure( awserr.New(jsonErr.Code, jsonErr.Message, nil), req.HTTPResponse.StatusCode, "", ) } type jsonErrorResponse struct { Code string `json:"__type"` Message string `json:"message"` } // test that retries occur for 5xx status codes func TestRequestRecoverRetry5xx(t *testing.T) { reqNum := 0 reqs := []http.Response{ {StatusCode: 500, Body: body(`{"__type":"UnknownError","message":"An error occurred."}`)}, {StatusCode: 501, Body: body(`{"__type":"UnknownError","message":"An error occurred."}`)}, {StatusCode: 200, Body: body(`{"data":"valid"}`)}, } s := awstesting.NewClient(aws.NewConfig().WithMaxRetries(10)) s.Handlers.Validate.Clear() s.Handlers.Unmarshal.PushBack(unmarshal) s.Handlers.UnmarshalError.PushBack(unmarshalError) s.Handlers.Send.Clear() // mock sending s.Handlers.Send.PushBack(func(r *request.Request) { r.HTTPResponse = &reqs[reqNum] reqNum++ }) out := &testData{} r := s.NewRequest(&request.Operation{Name: "Operation"}, nil, out) err := r.Send() assert.Nil(t, err) assert.Equal(t, 2, int(r.RetryCount)) assert.Equal(t, "valid", out.Data) } // test that retries occur for 4xx status codes with a response type that can be retried - see `shouldRetry` func TestRequestRecoverRetry4xxRetryable(t *testing.T) { reqNum := 0 reqs := []http.Response{ {StatusCode: 400, Body: body(`{"__type":"Throttling","message":"Rate exceeded."}`)}, {StatusCode: 429, Body: body(`{"__type":"ProvisionedThroughputExceededException","message":"Rate exceeded."}`)}, {StatusCode: 200, Body: body(`{"data":"valid"}`)}, } s := awstesting.NewClient(aws.NewConfig().WithMaxRetries(10)) s.Handlers.Validate.Clear() s.Handlers.Unmarshal.PushBack(unmarshal) s.Handlers.UnmarshalError.PushBack(unmarshalError) s.Handlers.Send.Clear() // mock sending s.Handlers.Send.PushBack(func(r *request.Request) { r.HTTPResponse = &reqs[reqNum] reqNum++ }) out := &testData{} r := s.NewRequest(&request.Operation{Name: "Operation"}, nil, out) err := r.Send() assert.Nil(t, err) assert.Equal(t, 2, int(r.RetryCount)) assert.Equal(t, "valid", out.Data) } // test that retries don't occur for 4xx status codes with a response type that can't be retried func TestRequest4xxUnretryable(t *testing.T) { s := awstesting.NewClient(aws.NewConfig().WithMaxRetries(10)) s.Handlers.Validate.Clear() s.Handlers.Unmarshal.PushBack(unmarshal) s.Handlers.UnmarshalError.PushBack(unmarshalError) s.Handlers.Send.Clear() // mock sending s.Handlers.Send.PushBack(func(r *request.Request) { r.HTTPResponse = &http.Response{StatusCode: 401, Body: body(`{"__type":"SignatureDoesNotMatch","message":"Signature does not match."}`)} }) out := &testData{} r := s.NewRequest(&request.Operation{Name: "Operation"}, nil, out) err := r.Send() assert.NotNil(t, err) if e, ok := err.(awserr.RequestFailure); ok { assert.Equal(t, 401, e.StatusCode()) } else { assert.Fail(t, "Expected error to be a service failure") } assert.Equal(t, "SignatureDoesNotMatch", err.(awserr.Error).Code()) assert.Equal(t, "Signature does not match.", err.(awserr.Error).Message()) assert.Equal(t, 0, int(r.RetryCount)) } func TestRequestExhaustRetries(t *testing.T) { delays := []time.Duration{} sleepDelay := func(delay time.Duration) { delays = append(delays, delay) } reqNum := 0 reqs := []http.Response{ {StatusCode: 500, Body: body(`{"__type":"UnknownError","message":"An error occurred."}`)}, {StatusCode: 500, Body: body(`{"__type":"UnknownError","message":"An error occurred."}`)}, {StatusCode: 500, Body: body(`{"__type":"UnknownError","message":"An error occurred."}`)}, {StatusCode: 500, Body: body(`{"__type":"UnknownError","message":"An error occurred."}`)}, } s := awstesting.NewClient(aws.NewConfig().WithSleepDelay(sleepDelay)) s.Handlers.Validate.Clear() s.Handlers.Unmarshal.PushBack(unmarshal) s.Handlers.UnmarshalError.PushBack(unmarshalError) s.Handlers.Send.Clear() // mock sending s.Handlers.Send.PushBack(func(r *request.Request) { r.HTTPResponse = &reqs[reqNum] reqNum++ }) r := s.NewRequest(&request.Operation{Name: "Operation"}, nil, nil) err := r.Send() assert.NotNil(t, err) if e, ok := err.(awserr.RequestFailure); ok { assert.Equal(t, 500, e.StatusCode()) } else { assert.Fail(t, "Expected error to be a service failure") } assert.Equal(t, "UnknownError", err.(awserr.Error).Code()) assert.Equal(t, "An error occurred.", err.(awserr.Error).Message()) assert.Equal(t, 3, int(r.RetryCount)) expectDelays := []struct{ min, max time.Duration }{{30, 59}, {60, 118}, {120, 236}} for i, v := range delays { min := expectDelays[i].min * time.Millisecond max := expectDelays[i].max * time.Millisecond assert.True(t, min <= v && v <= max, "Expect delay to be within range, i:%d, v:%s, min:%s, max:%s", i, v, min, max) } } // test that the request is retried after the credentials are expired. func TestRequestRecoverExpiredCreds(t *testing.T) { reqNum := 0 reqs := []http.Response{ {StatusCode: 400, Body: body(`{"__type":"ExpiredTokenException","message":"expired token"}`)}, {StatusCode: 200, Body: body(`{"data":"valid"}`)}, } s := awstesting.NewClient(&aws.Config{MaxRetries: aws.Int(10), Credentials: credentials.NewStaticCredentials("AKID", "SECRET", "")}) s.Handlers.Validate.Clear() s.Handlers.Unmarshal.PushBack(unmarshal) s.Handlers.UnmarshalError.PushBack(unmarshalError) credExpiredBeforeRetry := false credExpiredAfterRetry := false s.Handlers.AfterRetry.PushBack(func(r *request.Request) { credExpiredAfterRetry = r.Config.Credentials.IsExpired() }) s.Handlers.Sign.Clear() s.Handlers.Sign.PushBack(func(r *request.Request) { r.Config.Credentials.Get() }) s.Handlers.Send.Clear() // mock sending s.Handlers.Send.PushBack(func(r *request.Request) { r.HTTPResponse = &reqs[reqNum] reqNum++ }) out := &testData{} r := s.NewRequest(&request.Operation{Name: "Operation"}, nil, out) err := r.Send() assert.Nil(t, err) assert.False(t, credExpiredBeforeRetry, "Expect valid creds before retry check") assert.True(t, credExpiredAfterRetry, "Expect expired creds after retry check") assert.False(t, s.Config.Credentials.IsExpired(), "Expect valid creds after cred expired recovery") assert.Equal(t, 1, int(r.RetryCount)) assert.Equal(t, "valid", out.Data) } func TestMakeAddtoUserAgentHandler(t *testing.T) { fn := request.MakeAddToUserAgentHandler("name", "version", "extra1", "extra2") r := &request.Request{HTTPRequest: &http.Request{Header: http.Header{}}} r.HTTPRequest.Header.Set("User-Agent", "foo/bar") fn(r) assert.Equal(t, "foo/bar name/version (extra1; extra2)", r.HTTPRequest.Header.Get("User-Agent")) } func TestMakeAddtoUserAgentFreeFormHandler(t *testing.T) { fn := request.MakeAddToUserAgentFreeFormHandler("name/version (extra1; extra2)") r := &request.Request{HTTPRequest: &http.Request{Header: http.Header{}}} r.HTTPRequest.Header.Set("User-Agent", "foo/bar") fn(r) assert.Equal(t, "foo/bar name/version (extra1; extra2)", r.HTTPRequest.Header.Get("User-Agent")) } func TestRequestUserAgent(t *testing.T) { s := awstesting.NewClient(&aws.Config{Region: aws.String("us-east-1")}) // s.Handlers.Validate.Clear() req := s.NewRequest(&request.Operation{Name: "Operation"}, nil, &testData{}) req.HTTPRequest.Header.Set("User-Agent", "foo/bar") assert.NoError(t, req.Build()) expectUA := fmt.Sprintf("foo/bar %s/%s (%s; %s; %s)", aws.SDKName, aws.SDKVersion, runtime.Version(), runtime.GOOS, runtime.GOARCH) assert.Equal(t, expectUA, req.HTTPRequest.Header.Get("User-Agent")) }
Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/request/request_test.go
0
https://github.com/grafana/grafana/commit/bf943ddba38ced67da56f0cfd847760f41d31e61
[ 0.00019417778821662068, 0.00017061599646694958, 0.00016520023928023875, 0.00016967895498964936, 0.000005074301498098066 ]
{ "id": 2, "code_window": [ "}\n", "\n", "func (_ *ConsoleWriter) Destroy() {\n", "}\n", "\n", "func printConsole(level int, msg string) {\n", "\tconsoleWriter.WriteMsg(msg, 0, level)\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "func printConsole(level LogLevel, msg string) {\n" ], "file_path": "pkg/log/console.go", "type": "replace", "edit_start_line_idx": 84 }
package plugins import ( "github.com/grafana/grafana/pkg/bus" m "github.com/grafana/grafana/pkg/models" ) func GetOrgAppSettings(orgId int64) (map[string]*m.AppSettings, error) { query := m.GetAppSettingsQuery{OrgId: orgId} if err := bus.Dispatch(&query); err != nil { return nil, err } orgAppsMap := make(map[string]*m.AppSettings) for _, orgApp := range query.Result { orgAppsMap[orgApp.AppId] = orgApp } return orgAppsMap, nil } func GetEnabledPlugins(orgId int64) (*EnabledPlugins, error) { enabledPlugins := NewEnabledPlugins() orgApps, err := GetOrgAppSettings(orgId) if err != nil { return nil, err } enabledApps := make(map[string]bool) for appId, installedApp := range Apps { var app AppPlugin app = *installedApp // check if the app is stored in the DB for this org and if so, use the // state stored there. if b, ok := orgApps[appId]; ok { app.Enabled = b.Enabled app.Pinned = b.Pinned } if app.Enabled { enabledApps[app.Id] = true enabledPlugins.Apps = append(enabledPlugins.Apps, &app) } } isPluginEnabled := func(appId string) bool { if appId == "" { return true } _, ok := enabledApps[appId] return ok } // add all plugins that are not part of an App. for dsId, ds := range DataSources { if isPluginEnabled(ds.IncludedInAppId) { enabledPlugins.DataSources[dsId] = ds } } for _, panel := range Panels { if isPluginEnabled(panel.IncludedInAppId) { enabledPlugins.Panels = append(enabledPlugins.Panels, panel) } } return &enabledPlugins, nil }
pkg/plugins/queries.go
0
https://github.com/grafana/grafana/commit/bf943ddba38ced67da56f0cfd847760f41d31e61
[ 0.0013834290439262986, 0.0003226845874451101, 0.00016621127724647522, 0.00017021963139995933, 0.0004009488911833614 ]
{ "id": 3, "code_window": [ "\tconsoleWriter.WriteMsg(msg, 0, level)\n", "}\n", "\n", "func printfConsole(level int, format string, v ...interface{}) {\n", "\tconsoleWriter.WriteMsg(fmt.Sprintf(format, v...), 0, level)\n", "}\n", "\n", "// ConsoleTrace prints to stdout using TRACE colors\n", "func ConsoleTrace(s string) {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "func printfConsole(level LogLevel, format string, v ...interface{}) {\n" ], "file_path": "pkg/log/console.go", "type": "replace", "edit_start_line_idx": 88 }
// Copyright 2014 The Gogs Authors. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. package log import ( "encoding/json" "fmt" "log" "os" "runtime" ) type Brush func(string) string func NewBrush(color string) Brush { pre := "\033[" reset := "\033[0m" return func(text string) string { return pre + color + "m" + text + reset } } var ( Red = NewBrush("1;31") Purple = NewBrush("1;35") Yellow = NewBrush("1;33") Green = NewBrush("1;32") Blue = NewBrush("1;34") Cyan = NewBrush("1;36") colors = []Brush{ Cyan, // Trace cyan Blue, // Debug blue Green, // Info green Yellow, // Warn yellow Red, // Error red Purple, // Critical purple Red, // Fatal red } consoleWriter = &ConsoleWriter{lg: log.New(os.Stdout, "", 0), Level: TRACE} ) // ConsoleWriter implements LoggerInterface and writes messages to terminal. type ConsoleWriter struct { lg *log.Logger Level int `json:"level"` Formatting bool `json:"formatting"` } // create ConsoleWriter returning as LoggerInterface. func NewConsole() LoggerInterface { return &ConsoleWriter{ lg: log.New(os.Stderr, "", log.Ldate|log.Ltime), Level: TRACE, Formatting: true, } } func (cw *ConsoleWriter) Init(config string) error { return json.Unmarshal([]byte(config), cw) } func (cw *ConsoleWriter) WriteMsg(msg string, skip, level int) error { if cw.Level > level { return nil } if runtime.GOOS == "windows" || !cw.Formatting { cw.lg.Println(msg) } else { cw.lg.Println(colors[level](msg)) } return nil } func (_ *ConsoleWriter) Flush() { } func (_ *ConsoleWriter) Destroy() { } func printConsole(level int, msg string) { consoleWriter.WriteMsg(msg, 0, level) } func printfConsole(level int, format string, v ...interface{}) { consoleWriter.WriteMsg(fmt.Sprintf(format, v...), 0, level) } // ConsoleTrace prints to stdout using TRACE colors func ConsoleTrace(s string) { printConsole(TRACE, s) } // ConsoleTracef prints a formatted string to stdout using TRACE colors func ConsoleTracef(format string, v ...interface{}) { printfConsole(TRACE, format, v...) } // ConsoleDebug prints to stdout using DEBUG colors func ConsoleDebug(s string) { printConsole(DEBUG, s) } // ConsoleDebugf prints a formatted string to stdout using DEBUG colors func ConsoleDebugf(format string, v ...interface{}) { printfConsole(DEBUG, format, v...) } // ConsoleInfo prints to stdout using INFO colors func ConsoleInfo(s string) { printConsole(INFO, s) } // ConsoleInfof prints a formatted string to stdout using INFO colors func ConsoleInfof(format string, v ...interface{}) { printfConsole(INFO, format, v...) } // ConsoleWarn prints to stdout using WARN colors func ConsoleWarn(s string) { printConsole(WARN, s) } // ConsoleWarnf prints a formatted string to stdout using WARN colors func ConsoleWarnf(format string, v ...interface{}) { printfConsole(WARN, format, v...) } // ConsoleError prints to stdout using ERROR colors func ConsoleError(s string) { printConsole(ERROR, s) } // ConsoleErrorf prints a formatted string to stdout using ERROR colors func ConsoleErrorf(format string, v ...interface{}) { printfConsole(ERROR, format, v...) } // ConsoleFatal prints to stdout using FATAL colors func ConsoleFatal(s string) { printConsole(FATAL, s) os.Exit(1) } // ConsoleFatalf prints a formatted string to stdout using FATAL colors func ConsoleFatalf(format string, v ...interface{}) { printfConsole(FATAL, format, v...) os.Exit(1) } func init() { Register("console", NewConsole) }
pkg/log/console.go
1
https://github.com/grafana/grafana/commit/bf943ddba38ced67da56f0cfd847760f41d31e61
[ 0.9986007809638977, 0.5551701784133911, 0.00016819217125885189, 0.9437285661697388, 0.48772993683815 ]
{ "id": 3, "code_window": [ "\tconsoleWriter.WriteMsg(msg, 0, level)\n", "}\n", "\n", "func printfConsole(level int, format string, v ...interface{}) {\n", "\tconsoleWriter.WriteMsg(fmt.Sprintf(format, v...), 0, level)\n", "}\n", "\n", "// ConsoleTrace prints to stdout using TRACE colors\n", "func ConsoleTrace(s string) {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "func printfConsole(level LogLevel, format string, v ...interface{}) {\n" ], "file_path": "pkg/log/console.go", "type": "replace", "edit_start_line_idx": 88 }
package migrations import . "github.com/grafana/grafana/pkg/services/sqlstore/migrator" func addOrgMigrations(mg *Migrator) { orgV1 := Table{ Name: "org", Columns: []*Column{ {Name: "id", Type: DB_BigInt, IsPrimaryKey: true, IsAutoIncrement: true}, {Name: "version", Type: DB_Int, Nullable: false}, {Name: "name", Type: DB_NVarchar, Length: 255, Nullable: false}, {Name: "address1", Type: DB_NVarchar, Length: 255, Nullable: true}, {Name: "address2", Type: DB_NVarchar, Length: 255, Nullable: true}, {Name: "city", Type: DB_NVarchar, Length: 255, Nullable: true}, {Name: "state", Type: DB_NVarchar, Length: 255, Nullable: true}, {Name: "zip_code", Type: DB_NVarchar, Length: 50, Nullable: true}, {Name: "country", Type: DB_NVarchar, Length: 255, Nullable: true}, {Name: "billing_email", Type: DB_NVarchar, Length: 255, Nullable: true}, {Name: "created", Type: DB_DateTime, Nullable: false}, {Name: "updated", Type: DB_DateTime, Nullable: false}, }, Indices: []*Index{ {Cols: []string{"name"}, Type: UniqueIndex}, }, } // add org v1 mg.AddMigration("create org table v1", NewAddTableMigration(orgV1)) addTableIndicesMigrations(mg, "v1", orgV1) orgUserV1 := Table{ Name: "org_user", Columns: []*Column{ {Name: "id", Type: DB_BigInt, IsPrimaryKey: true, IsAutoIncrement: true}, {Name: "org_id", Type: DB_BigInt}, {Name: "user_id", Type: DB_BigInt}, {Name: "role", Type: DB_NVarchar, Length: 20}, {Name: "created", Type: DB_DateTime}, {Name: "updated", Type: DB_DateTime}, }, Indices: []*Index{ {Cols: []string{"org_id"}}, {Cols: []string{"org_id", "user_id"}, Type: UniqueIndex}, }, } //------- org_user table ------------------- mg.AddMigration("create org_user table v1", NewAddTableMigration(orgUserV1)) addTableIndicesMigrations(mg, "v1", orgUserV1) //------- copy data from old table------------------- mg.AddMigration("copy data account to org", NewCopyTableDataMigration("org", "account", map[string]string{ "id": "id", "version": "version", "name": "name", "created": "created", "updated": "updated", }).IfTableExists("account")) mg.AddMigration("copy data account_user to org_user", NewCopyTableDataMigration("org_user", "account_user", map[string]string{ "id": "id", "org_id": "account_id", "user_id": "user_id", "role": "role", "created": "created", "updated": "updated", }).IfTableExists("account_user")) mg.AddMigration("Drop old table account", NewDropTableMigration("account")) mg.AddMigration("Drop old table account_user", NewDropTableMigration("account_user")) }
pkg/services/sqlstore/migrations/org_mig.go
0
https://github.com/grafana/grafana/commit/bf943ddba38ced67da56f0cfd847760f41d31e61
[ 0.0001756145793478936, 0.0001709295902401209, 0.000166063939104788, 0.00017185314209200442, 0.0000031016072625789093 ]
{ "id": 3, "code_window": [ "\tconsoleWriter.WriteMsg(msg, 0, level)\n", "}\n", "\n", "func printfConsole(level int, format string, v ...interface{}) {\n", "\tconsoleWriter.WriteMsg(fmt.Sprintf(format, v...), 0, level)\n", "}\n", "\n", "// ConsoleTrace prints to stdout using TRACE colors\n", "func ConsoleTrace(s string) {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "func printfConsole(level LogLevel, format string, v ...interface{}) {\n" ], "file_path": "pkg/log/console.go", "type": "replace", "edit_start_line_idx": 88 }
foo[*].bar[2]
Godeps/_workspace/src/github.com/jmespath/go-jmespath/fuzz/corpus/expr-612
0
https://github.com/grafana/grafana/commit/bf943ddba38ced67da56f0cfd847760f41d31e61
[ 0.00017683886107988656, 0.00017683886107988656, 0.00017683886107988656, 0.00017683886107988656, 0 ]
{ "id": 3, "code_window": [ "\tconsoleWriter.WriteMsg(msg, 0, level)\n", "}\n", "\n", "func printfConsole(level int, format string, v ...interface{}) {\n", "\tconsoleWriter.WriteMsg(fmt.Sprintf(format, v...), 0, level)\n", "}\n", "\n", "// ConsoleTrace prints to stdout using TRACE colors\n", "func ConsoleTrace(s string) {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "func printfConsole(level LogLevel, format string, v ...interface{}) {\n" ], "file_path": "pkg/log/console.go", "type": "replace", "edit_start_line_idx": 88 }
define([ 'angular', 'lodash', 'jquery', 'app/core/config', 'app/core/utils/datemath', './query_ctrl', './func_editor', './add_graphite_func', ], function (angular, _, $, config, dateMath) { 'use strict'; /** @ngInject */ function GraphiteDatasource(instanceSettings, $q, backendSrv, templateSrv) { this.basicAuth = instanceSettings.basicAuth; this.url = instanceSettings.url; this.name = instanceSettings.name; this.cacheTimeout = instanceSettings.cacheTimeout; this.withCredentials = instanceSettings.withCredentials; this.render_method = instanceSettings.render_method || 'POST'; this.query = function(options) { try { var graphOptions = { from: this.translateTime(options.rangeRaw.from, false), until: this.translateTime(options.rangeRaw.to, true), targets: options.targets, format: options.format, cacheTimeout: options.cacheTimeout || this.cacheTimeout, maxDataPoints: options.maxDataPoints, }; var params = this.buildGraphiteParams(graphOptions, options.scopedVars); if (params.length === 0) { return $q.when([]); } if (options.format === 'png') { return $q.when(this.url + '/render' + '?' + params.join('&')); } var httpOptions = { method: this.render_method, url: '/render' }; if (httpOptions.method === 'GET') { httpOptions.url = httpOptions.url + '?' + params.join('&'); } else { httpOptions.data = params.join('&'); httpOptions.headers = { 'Content-Type': 'application/x-www-form-urlencoded' }; } return this.doGraphiteRequest(httpOptions).then(this.convertDataPointsToMs); } catch(err) { return $q.reject(err); } }; this.convertDataPointsToMs = function(result) { if (!result || !result.data) { return []; } for (var i = 0; i < result.data.length; i++) { var series = result.data[i]; for (var y = 0; y < series.datapoints.length; y++) { series.datapoints[y][1] *= 1000; } } return result; }; this.annotationQuery = function(options) { // Graphite metric as annotation if (options.annotation.target) { var target = templateSrv.replace(options.annotation.target); var graphiteQuery = { rangeRaw: options.rangeRaw, targets: [{ target: target }], format: 'json', maxDataPoints: 100 }; return this.query(graphiteQuery) .then(function(result) { var list = []; for (var i = 0; i < result.data.length; i++) { var target = result.data[i]; for (var y = 0; y < target.datapoints.length; y++) { var datapoint = target.datapoints[y]; if (!datapoint[0]) { continue; } list.push({ annotation: options.annotation, time: datapoint[1], title: target.target }); } } return list; }); } // Graphite event as annotation else { var tags = templateSrv.replace(options.annotation.tags); return this.events({range: options.rangeRaw, tags: tags}).then(function(results) { var list = []; for (var i = 0; i < results.data.length; i++) { var e = results.data[i]; list.push({ annotation: options.annotation, time: e.when * 1000, title: e.what, tags: e.tags, text: e.data }); } return list; }); } }; this.events = function(options) { try { var tags = ''; if (options.tags) { tags = '&tags=' + options.tags; } return this.doGraphiteRequest({ method: 'GET', url: '/events/get_data?from=' + this.translateTime(options.range.from, false) + '&until=' + this.translateTime(options.range.to, true) + tags, }); } catch(err) { return $q.reject(err); } }; this.translateTime = function(date, roundUp) { if (_.isString(date)) { if (date === 'now') { return 'now'; } else if (date.indexOf('now-') >= 0 && date.indexOf('/') === -1) { date = date.substring(3); date = date.replace('m', 'min'); date = date.replace('M', 'mon'); return date; } date = dateMath.parse(date, roundUp); } // graphite' s from filter is exclusive // here we step back one minute in order // to guarantee that we get all the data that // exists for the specified range if (roundUp) { if (date.get('s')) { date.add(1, 'm'); } } else if (roundUp === false) { if (date.get('s')) { date.subtract(1, 'm'); } } return date.unix(); }; this.metricFindQuery = function(query) { var interpolated; try { interpolated = encodeURIComponent(templateSrv.replace(query)); } catch(err) { return $q.reject(err); } return this.doGraphiteRequest({method: 'GET', url: '/metrics/find/?query=' + interpolated }) .then(function(results) { return _.map(results.data, function(metric) { return { text: metric.text, expandable: metric.expandable ? true : false }; }); }); }; this.testDatasource = function() { return this.metricFindQuery('*').then(function () { return { status: "success", message: "Data source is working", title: "Success" }; }); }; this.listDashboards = function(query) { return this.doGraphiteRequest({ method: 'GET', url: '/dashboard/find/', params: {query: query || ''} }) .then(function(results) { return results.data.dashboards; }); }; this.loadDashboard = function(dashName) { return this.doGraphiteRequest({method: 'GET', url: '/dashboard/load/' + encodeURIComponent(dashName) }); }; this.doGraphiteRequest = function(options) { if (this.basicAuth || this.withCredentials) { options.withCredentials = true; } if (this.basicAuth) { options.headers = options.headers || {}; options.headers.Authorization = this.basicAuth; } options.url = this.url + options.url; options.inspect = { type: 'graphite' }; return backendSrv.datasourceRequest(options); }; this._seriesRefLetters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; this.buildGraphiteParams = function(options, scopedVars) { var graphite_options = ['from', 'until', 'rawData', 'format', 'maxDataPoints', 'cacheTimeout']; var clean_options = [], targets = {}; var target, targetValue, i; var regex = /\#([A-Z])/g; var intervalFormatFixRegex = /'(\d+)m'/gi; var hasTargets = false; if (options.format !== 'png') { options['format'] = 'json'; } function fixIntervalFormat(match) { return match.replace('m', 'min').replace('M', 'mon'); } for (i = 0; i < options.targets.length; i++) { target = options.targets[i]; if (!target.target) { continue; } if (!target.refId) { target.refId = this._seriesRefLetters[i]; } targetValue = templateSrv.replace(target.target, scopedVars); targetValue = targetValue.replace(intervalFormatFixRegex, fixIntervalFormat); targets[target.refId] = targetValue; } function nestedSeriesRegexReplacer(match, g1) { return targets[g1]; } for (i = 0; i < options.targets.length; i++) { target = options.targets[i]; if (!target.target) { continue; } targetValue = targets[target.refId]; targetValue = targetValue.replace(regex, nestedSeriesRegexReplacer); targets[target.refId] = targetValue; if (!target.hide) { hasTargets = true; clean_options.push("target=" + encodeURIComponent(targetValue)); } } _.each(options, function (value, key) { if ($.inArray(key, graphite_options) === -1) { return; } if (value) { clean_options.push(key + "=" + encodeURIComponent(value)); } }); if (!hasTargets) { return []; } return clean_options; }; } return GraphiteDatasource; });
public/app/plugins/datasource/graphite/datasource.js
0
https://github.com/grafana/grafana/commit/bf943ddba38ced67da56f0cfd847760f41d31e61
[ 0.00017483082774560899, 0.00017097598174586892, 0.00016665770090185106, 0.00017121282871812582, 0.000001969118329725461 ]
{ "id": 4, "code_window": [ "\n", "\tstartLock sync.Mutex // Only one log can write to the file\n", "\n", "\tLevel int `json:\"level\"`\n", "}\n", "\n", "// an *os.File writer with locker.\n", "type MuxWriter struct {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tLevel LogLevel `json:\"level\"`\n" ], "file_path": "pkg/log/file.go", "type": "replace", "edit_start_line_idx": 43 }
// Copyright 2014 The Gogs Authors. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. package log import ( "fmt" "os" "path/filepath" "runtime" "strings" "sync" ) var ( loggers []*Logger ) func NewLogger(bufLen int64, mode, config string) { logger := newLogger(bufLen) isExist := false for _, l := range loggers { if l.adapter == mode { isExist = true l = logger } } if !isExist { loggers = append(loggers, logger) } if err := logger.SetLogger(mode, config); err != nil { Fatal(1, "Fail to set logger(%s): %v", mode, err) } } func Trace(format string, v ...interface{}) { for _, logger := range loggers { logger.Trace(format, v...) } } func Debug(format string, v ...interface{}) { for _, logger := range loggers { logger.Debug(format, v...) } } func Info(format string, v ...interface{}) { for _, logger := range loggers { logger.Info(format, v...) } } func Warn(format string, v ...interface{}) { for _, logger := range loggers { logger.Warn(format, v...) } } func Error(skip int, format string, v ...interface{}) { for _, logger := range loggers { logger.Error(skip, format, v...) } } func Critical(skip int, format string, v ...interface{}) { for _, logger := range loggers { logger.Critical(skip, format, v...) } } func Fatal(skip int, format string, v ...interface{}) { Error(skip, format, v...) for _, l := range loggers { l.Close() } os.Exit(1) } func Close() { for _, l := range loggers { l.Close() // delete the logger. l = nil } // clear the loggers slice. loggers = nil } // .___ __ _____ // | | _____/ |_ ____________/ ____\____ ____ ____ // | |/ \ __\/ __ \_ __ \ __\\__ \ _/ ___\/ __ \ // | | | \ | \ ___/| | \/| | / __ \\ \__\ ___/ // |___|___| /__| \___ >__| |__| (____ /\___ >___ > // \/ \/ \/ \/ \/ type LogLevel int const ( TRACE = iota DEBUG INFO WARN ERROR CRITICAL FATAL ) // LoggerInterface represents behaviors of a logger provider. type LoggerInterface interface { Init(config string) error WriteMsg(msg string, skip, level int) error Destroy() Flush() } type loggerType func() LoggerInterface var adapters = make(map[string]loggerType) // Register registers given logger provider to adapters. func Register(name string, log loggerType) { if log == nil { panic("log: register provider is nil") } if _, dup := adapters[name]; dup { panic("log: register called twice for provider \"" + name + "\"") } adapters[name] = log } type logMsg struct { skip, level int msg string } // Logger is default logger in beego application. // it can contain several providers and log message into all providers. type Logger struct { adapter string lock sync.Mutex level int msg chan *logMsg outputs map[string]LoggerInterface quit chan bool } // newLogger initializes and returns a new logger. func newLogger(buffer int64) *Logger { l := &Logger{ msg: make(chan *logMsg, buffer), outputs: make(map[string]LoggerInterface), quit: make(chan bool), } go l.StartLogger() return l } // SetLogger sets new logger instanse with given logger adapter and config. func (l *Logger) SetLogger(adapter string, config string) error { l.lock.Lock() defer l.lock.Unlock() if log, ok := adapters[adapter]; ok { lg := log() if err := lg.Init(config); err != nil { return err } l.outputs[adapter] = lg l.adapter = adapter } else { panic("log: unknown adapter \"" + adapter + "\" (forgotten register?)") } return nil } // DelLogger removes a logger adapter instance. func (l *Logger) DelLogger(adapter string) error { l.lock.Lock() defer l.lock.Unlock() if lg, ok := l.outputs[adapter]; ok { lg.Destroy() delete(l.outputs, adapter) } else { panic("log: unknown adapter \"" + adapter + "\" (forgotten register?)") } return nil } func (l *Logger) writerMsg(skip, level int, msg string) error { if l.level > level { return nil } lm := &logMsg{ skip: skip, level: level, } // Only error information needs locate position for debugging. if lm.level >= ERROR { pc, file, line, ok := runtime.Caller(skip) if ok { // Get caller function name. fn := runtime.FuncForPC(pc) var fnName string if fn == nil { fnName = "?()" } else { fnName = strings.TrimLeft(filepath.Ext(fn.Name()), ".") + "()" } lm.msg = fmt.Sprintf("[%s:%d %s] %s", filepath.Base(file), line, fnName, msg) } else { lm.msg = msg } } else { lm.msg = msg } l.msg <- lm return nil } // StartLogger starts logger chan reading. func (l *Logger) StartLogger() { for { select { case bm := <-l.msg: for _, l := range l.outputs { if err := l.WriteMsg(bm.msg, bm.skip, bm.level); err != nil { fmt.Println("ERROR, unable to WriteMsg:", err) } } case <-l.quit: return } } } // Flush flushs all chan data. func (l *Logger) Flush() { for _, l := range l.outputs { l.Flush() } } // Close closes logger, flush all chan data and destroy all adapter instances. func (l *Logger) Close() { l.quit <- true for { if len(l.msg) > 0 { bm := <-l.msg for _, l := range l.outputs { if err := l.WriteMsg(bm.msg, bm.skip, bm.level); err != nil { fmt.Println("ERROR, unable to WriteMsg:", err) } } } else { break } } for _, l := range l.outputs { l.Flush() l.Destroy() } } func (l *Logger) Trace(format string, v ...interface{}) { msg := fmt.Sprintf("[T] "+format, v...) l.writerMsg(0, TRACE, msg) } func (l *Logger) Debug(format string, v ...interface{}) { msg := fmt.Sprintf("[D] "+format, v...) l.writerMsg(0, DEBUG, msg) } func (l *Logger) Info(format string, v ...interface{}) { msg := fmt.Sprintf("[I] "+format, v...) l.writerMsg(0, INFO, msg) } func (l *Logger) Warn(format string, v ...interface{}) { msg := fmt.Sprintf("[W] "+format, v...) l.writerMsg(0, WARN, msg) } func (l *Logger) Error(skip int, format string, v ...interface{}) { msg := fmt.Sprintf("[E] "+format, v...) l.writerMsg(skip, ERROR, msg) } func (l *Logger) Critical(skip int, format string, v ...interface{}) { msg := fmt.Sprintf("[C] "+format, v...) l.writerMsg(skip, CRITICAL, msg) } func (l *Logger) Fatal(skip int, format string, v ...interface{}) { msg := fmt.Sprintf("[F] "+format, v...) l.writerMsg(skip, FATAL, msg) l.Close() os.Exit(1) }
pkg/log/log.go
1
https://github.com/grafana/grafana/commit/bf943ddba38ced67da56f0cfd847760f41d31e61
[ 0.00847538746893406, 0.0015921067679300904, 0.0001680333080003038, 0.0005274256109260023, 0.0023984163999557495 ]
{ "id": 4, "code_window": [ "\n", "\tstartLock sync.Mutex // Only one log can write to the file\n", "\n", "\tLevel int `json:\"level\"`\n", "}\n", "\n", "// an *os.File writer with locker.\n", "type MuxWriter struct {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tLevel LogLevel `json:\"level\"`\n" ], "file_path": "pkg/log/file.go", "type": "replace", "edit_start_line_idx": 43 }
'✓'
Godeps/_workspace/src/github.com/jmespath/go-jmespath/fuzz/corpus/expr-414
0
https://github.com/grafana/grafana/commit/bf943ddba38ced67da56f0cfd847760f41d31e61
[ 0.00017211356316693127, 0.00017211356316693127, 0.00017211356316693127, 0.00017211356316693127, 0 ]
{ "id": 4, "code_window": [ "\n", "\tstartLock sync.Mutex // Only one log can write to the file\n", "\n", "\tLevel int `json:\"level\"`\n", "}\n", "\n", "// an *os.File writer with locker.\n", "type MuxWriter struct {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tLevel LogLevel `json:\"level\"`\n" ], "file_path": "pkg/log/file.go", "type": "replace", "edit_start_line_idx": 43 }
<navbar icon="fa fa-fw fa-user" title="Users" title-url="admin/users" subnav="true"> <ul class="nav"> <li class="active"><a href="admin/users/create">Add user</a></li> </ul> </navbar> <div class="page-container"> <div class="page"> <h2> Add new user </h2> <form name="userForm"> <div> <div class="tight-form"> <ul class="tight-form-list"> <li class="tight-form-item" style="width: 100px"> <strong>Name</strong> </li> <li> <input type="text" required ng-model="user.name" class="input-xxlarge tight-form-input last" > </li> </ul> <div class="clearfix"></div> </div> <div class="tight-form"> <ul class="tight-form-list"> <li class="tight-form-item" style="width: 100px"> <strong>Email</strong> </li> <li> <input type="email" ng-model="user.email" class="input-xxlarge tight-form-input last" > </li> </ul> <div class="clearfix"></div> </div> <div class="tight-form"> <ul class="tight-form-list"> <li class="tight-form-item" style="width: 100px"> <strong>Username</strong> </li> <li> <input type="text" ng-model="user.login" class="input-xxlarge tight-form-input last" > </li> </ul> <div class="clearfix"></div> </div> <div class="tight-form"> <ul class="tight-form-list"> <li class="tight-form-item" style="width: 100px"> <strong>Password</strong> </li> <li> <input type="password" required ng-model="user.password" class="input-xxlarge tight-form-input last" > </li> </ul> <div class="clearfix"></div> </div> </div> <br> <button type="submit" class="pull-right btn btn-success" ng-click="create()">Create</button> </form> </div> </div>
public/app/features/admin/partials/new_user.html
0
https://github.com/grafana/grafana/commit/bf943ddba38ced67da56f0cfd847760f41d31e61
[ 0.0001717340637696907, 0.00017030435265041888, 0.00016860838513821363, 0.0001703283196548, 0.000001143037479778286 ]
{ "id": 4, "code_window": [ "\n", "\tstartLock sync.Mutex // Only one log can write to the file\n", "\n", "\tLevel int `json:\"level\"`\n", "}\n", "\n", "// an *os.File writer with locker.\n", "type MuxWriter struct {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tLevel LogLevel `json:\"level\"`\n" ], "file_path": "pkg/log/file.go", "type": "replace", "edit_start_line_idx": 43 }
[Unit] Description=Starts and stops a single grafana instance on this system Documentation=http://docs.grafana.org Wants=network-online.target After=network-online.target [Service] EnvironmentFile=/etc/sysconfig/grafana-server User=grafana Group=grafana Type=simple Restart=on-failure WorkingDirectory=/usr/share/grafana ExecStart=/usr/sbin/grafana-server \ --config=${CONF_FILE} \ --pidfile=${PID_FILE} \ cfg:default.paths.logs=${LOG_DIR} \ cfg:default.paths.data=${DATA_DIR} \ cfg:default.paths.plugins=${PLUGINS_DIR} LimitNOFILE=10000 TimeoutStopSec=20 [Install] WantedBy=multi-user.target
packaging/rpm/systemd/grafana-server.service
0
https://github.com/grafana/grafana/commit/bf943ddba38ced67da56f0cfd847760f41d31e61
[ 0.0007664476288482547, 0.0003677019558381289, 0.00016793256509117782, 0.00016872561536729336, 0.0002819559595081955 ]
{ "id": 5, "code_window": [ "\tw.maxsize_cursize += size\n", "}\n", "\n", "// write logger message into file.\n", "func (w *FileLogWriter) WriteMsg(msg string, skip, level int) error {\n", "\tif level < w.Level {\n", "\t\treturn nil\n", "\t}\n", "\tn := 24 + len(msg) // 24 stand for the length \"2013/06/23 21:00:22 [T] \"\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "func (w *FileLogWriter) WriteMsg(msg string, skip int, level LogLevel) error {\n" ], "file_path": "pkg/log/file.go", "type": "replace", "edit_start_line_idx": 134 }
//+build !windows,!nacl,!plan9 package log import ( "encoding/json" "errors" "log/syslog" ) type SyslogWriter struct { syslog *syslog.Writer Network string `json:"network"` Address string `json:"address"` Facility string `json:"facility"` Tag string `json:"tag"` } func NewSyslog() LoggerInterface { return new(SyslogWriter) } func (sw *SyslogWriter) Init(config string) error { if err := json.Unmarshal([]byte(config), sw); err != nil { return err } prio, err := parseFacility(sw.Facility) if err != nil { return err } w, err := syslog.Dial(sw.Network, sw.Address, prio, sw.Tag) if err != nil { return err } sw.syslog = w return nil } func (sw *SyslogWriter) WriteMsg(msg string, skip, level int) error { var err error switch level { case TRACE, DEBUG: err = sw.syslog.Debug(msg) case INFO: err = sw.syslog.Info(msg) case WARN: err = sw.syslog.Warning(msg) case ERROR: err = sw.syslog.Err(msg) case CRITICAL: err = sw.syslog.Crit(msg) case FATAL: err = sw.syslog.Alert(msg) default: err = errors.New("invalid syslog level") } return err } func (sw *SyslogWriter) Destroy() { sw.syslog.Close() } func (sw *SyslogWriter) Flush() {} var facilities = map[string]syslog.Priority{ "user": syslog.LOG_USER, "daemon": syslog.LOG_DAEMON, "local0": syslog.LOG_LOCAL0, "local1": syslog.LOG_LOCAL1, "local2": syslog.LOG_LOCAL2, "local3": syslog.LOG_LOCAL3, "local4": syslog.LOG_LOCAL4, "local5": syslog.LOG_LOCAL5, "local6": syslog.LOG_LOCAL6, "local7": syslog.LOG_LOCAL7, } func parseFacility(facility string) (syslog.Priority, error) { prio, ok := facilities[facility] if !ok { return syslog.LOG_LOCAL0, errors.New("invalid syslog facility") } return prio, nil } func init() { Register("syslog", NewSyslog) }
pkg/log/syslog.go
1
https://github.com/grafana/grafana/commit/bf943ddba38ced67da56f0cfd847760f41d31e61
[ 0.973282516002655, 0.12579110264778137, 0.00023868367134127766, 0.023942850530147552, 0.2851886451244354 ]
{ "id": 5, "code_window": [ "\tw.maxsize_cursize += size\n", "}\n", "\n", "// write logger message into file.\n", "func (w *FileLogWriter) WriteMsg(msg string, skip, level int) error {\n", "\tif level < w.Level {\n", "\t\treturn nil\n", "\t}\n", "\tn := 24 + len(msg) // 24 stand for the length \"2013/06/23 21:00:22 [T] \"\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "func (w *FileLogWriter) WriteMsg(msg string, skip int, level LogLevel) error {\n" ], "file_path": "pkg/log/file.go", "type": "replace", "edit_start_line_idx": 134 }
package migrations import ( . "github.com/grafana/grafana/pkg/services/sqlstore/migrator" ) func addQuotaMigration(mg *Migrator) { var quotaV1 = Table{ Name: "quota", Columns: []*Column{ {Name: "id", Type: DB_BigInt, IsPrimaryKey: true, IsAutoIncrement: true}, {Name: "org_id", Type: DB_BigInt, Nullable: true}, {Name: "user_id", Type: DB_BigInt, Nullable: true}, {Name: "target", Type: DB_NVarchar, Length: 255, Nullable: false}, {Name: "limit", Type: DB_BigInt, Nullable: false}, {Name: "created", Type: DB_DateTime, Nullable: false}, {Name: "updated", Type: DB_DateTime, Nullable: false}, }, Indices: []*Index{ {Cols: []string{"org_id", "user_id", "target"}, Type: UniqueIndex}, }, } mg.AddMigration("create quota table v1", NewAddTableMigration(quotaV1)) //------- indexes ------------------ addTableIndicesMigrations(mg, "v1", quotaV1) }
pkg/services/sqlstore/migrations/quota_mig.go
0
https://github.com/grafana/grafana/commit/bf943ddba38ced67da56f0cfd847760f41d31e61
[ 0.0003233023453503847, 0.0002567098999861628, 0.00020919482631143183, 0.00023763254284858704, 0.00004849804827244952 ]
{ "id": 5, "code_window": [ "\tw.maxsize_cursize += size\n", "}\n", "\n", "// write logger message into file.\n", "func (w *FileLogWriter) WriteMsg(msg string, skip, level int) error {\n", "\tif level < w.Level {\n", "\t\treturn nil\n", "\t}\n", "\tn := 24 + len(msg) // 24 stand for the length \"2013/06/23 21:00:22 [T] \"\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "func (w *FileLogWriter) WriteMsg(msg string, skip int, level LogLevel) error {\n" ], "file_path": "pkg/log/file.go", "type": "replace", "edit_start_line_idx": 134 }
// Copyright 2014 The Macaron Authors // // Licensed under the Apache License, Version 2.0 (the "License"): you may // not use this file except in compliance with the License. You may obtain // a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations // under the License. package macaron import ( "net/http" "strings" "sync" ) var ( // Known HTTP methods. _HTTP_METHODS = map[string]bool{ "GET": true, "POST": true, "PUT": true, "DELETE": true, "PATCH": true, "OPTIONS": true, "HEAD": true, } ) // routeMap represents a thread-safe map for route tree. type routeMap struct { lock sync.RWMutex routes map[string]map[string]*Leaf } // NewRouteMap initializes and returns a new routeMap. func NewRouteMap() *routeMap { rm := &routeMap{ routes: make(map[string]map[string]*Leaf), } for m := range _HTTP_METHODS { rm.routes[m] = make(map[string]*Leaf) } return rm } // getLeaf returns Leaf object if a route has been registered. func (rm *routeMap) getLeaf(method, pattern string) *Leaf { rm.lock.RLock() defer rm.lock.RUnlock() return rm.routes[method][pattern] } // add adds new route to route tree map. func (rm *routeMap) add(method, pattern string, leaf *Leaf) { rm.lock.Lock() defer rm.lock.Unlock() rm.routes[method][pattern] = leaf } type group struct { pattern string handlers []Handler } // Router represents a Macaron router layer. type Router struct { m *Macaron autoHead bool routers map[string]*Tree *routeMap namedRoutes map[string]*Leaf groups []group notFound http.HandlerFunc internalServerError func(*Context, error) } func NewRouter() *Router { return &Router{ routers: make(map[string]*Tree), routeMap: NewRouteMap(), namedRoutes: make(map[string]*Leaf), } } // SetAutoHead sets the value who determines whether add HEAD method automatically // when GET method is added. Combo router will not be affected by this value. func (r *Router) SetAutoHead(v bool) { r.autoHead = v } type Params map[string]string // Handle is a function that can be registered to a route to handle HTTP requests. // Like http.HandlerFunc, but has a third parameter for the values of wildcards (variables). type Handle func(http.ResponseWriter, *http.Request, Params) // Route represents a wrapper of leaf route and upper level router. type Route struct { router *Router leaf *Leaf } // Name sets name of route. func (r *Route) Name(name string) { if len(name) == 0 { panic("route name cannot be empty") } else if r.router.namedRoutes[name] != nil { panic("route with given name already exists") } r.router.namedRoutes[name] = r.leaf } // handle adds new route to the router tree. func (r *Router) handle(method, pattern string, handle Handle) *Route { method = strings.ToUpper(method) var leaf *Leaf // Prevent duplicate routes. if leaf = r.getLeaf(method, pattern); leaf != nil { return &Route{r, leaf} } // Validate HTTP methods. if !_HTTP_METHODS[method] && method != "*" { panic("unknown HTTP method: " + method) } // Generate methods need register. methods := make(map[string]bool) if method == "*" { for m := range _HTTP_METHODS { methods[m] = true } } else { methods[method] = true } // Add to router tree. for m := range methods { if t, ok := r.routers[m]; ok { leaf = t.Add(pattern, handle) } else { t := NewTree() leaf = t.Add(pattern, handle) r.routers[m] = t } r.add(m, pattern, leaf) } return &Route{r, leaf} } // Handle registers a new request handle with the given pattern, method and handlers. func (r *Router) Handle(method string, pattern string, handlers []Handler) *Route { if len(r.groups) > 0 { groupPattern := "" h := make([]Handler, 0) for _, g := range r.groups { groupPattern += g.pattern h = append(h, g.handlers...) } pattern = groupPattern + pattern h = append(h, handlers...) handlers = h } validateHandlers(handlers) return r.handle(method, pattern, func(resp http.ResponseWriter, req *http.Request, params Params) { c := r.m.createContext(resp, req) c.params = params c.handlers = make([]Handler, 0, len(r.m.handlers)+len(handlers)) c.handlers = append(c.handlers, r.m.handlers...) c.handlers = append(c.handlers, handlers...) c.run() }) } func (r *Router) Group(pattern string, fn func(), h ...Handler) { r.groups = append(r.groups, group{pattern, h}) fn() r.groups = r.groups[:len(r.groups)-1] } // Get is a shortcut for r.Handle("GET", pattern, handlers) func (r *Router) Get(pattern string, h ...Handler) (leaf *Route) { leaf = r.Handle("GET", pattern, h) if r.autoHead { r.Head(pattern, h...) } return leaf } // Patch is a shortcut for r.Handle("PATCH", pattern, handlers) func (r *Router) Patch(pattern string, h ...Handler) *Route { return r.Handle("PATCH", pattern, h) } // Post is a shortcut for r.Handle("POST", pattern, handlers) func (r *Router) Post(pattern string, h ...Handler) *Route { return r.Handle("POST", pattern, h) } // Put is a shortcut for r.Handle("PUT", pattern, handlers) func (r *Router) Put(pattern string, h ...Handler) *Route { return r.Handle("PUT", pattern, h) } // Delete is a shortcut for r.Handle("DELETE", pattern, handlers) func (r *Router) Delete(pattern string, h ...Handler) *Route { return r.Handle("DELETE", pattern, h) } // Options is a shortcut for r.Handle("OPTIONS", pattern, handlers) func (r *Router) Options(pattern string, h ...Handler) *Route { return r.Handle("OPTIONS", pattern, h) } // Head is a shortcut for r.Handle("HEAD", pattern, handlers) func (r *Router) Head(pattern string, h ...Handler) *Route { return r.Handle("HEAD", pattern, h) } // Any is a shortcut for r.Handle("*", pattern, handlers) func (r *Router) Any(pattern string, h ...Handler) *Route { return r.Handle("*", pattern, h) } // Route is a shortcut for same handlers but different HTTP methods. // // Example: // m.Route("/", "GET,POST", h) func (r *Router) Route(pattern, methods string, h ...Handler) (route *Route) { for _, m := range strings.Split(methods, ",") { route = r.Handle(strings.TrimSpace(m), pattern, h) } return route } // Combo returns a combo router. func (r *Router) Combo(pattern string, h ...Handler) *ComboRouter { return &ComboRouter{r, pattern, h, map[string]bool{}, nil} } // Configurable http.HandlerFunc which is called when no matching route is // found. If it is not set, http.NotFound is used. // Be sure to set 404 response code in your handler. func (r *Router) NotFound(handlers ...Handler) { validateHandlers(handlers) r.notFound = func(rw http.ResponseWriter, req *http.Request) { c := r.m.createContext(rw, req) c.handlers = append(r.m.handlers, handlers...) c.run() } } // Configurable handler which is called when route handler returns // error. If it is not set, default handler is used. // Be sure to set 500 response code in your handler. func (r *Router) InternalServerError(handlers ...Handler) { validateHandlers(handlers) r.internalServerError = func(c *Context, err error) { c.index = 0 c.handlers = handlers c.Map(err) c.run() } } func (r *Router) ServeHTTP(rw http.ResponseWriter, req *http.Request) { if t, ok := r.routers[req.Method]; ok { h, p, ok := t.Match(req.URL.Path) if ok { if splat, ok := p["*0"]; ok { p["*"] = splat // Easy name. } h(rw, req, p) return } } r.notFound(rw, req) } // URLFor builds path part of URL by given pair values. func (r *Router) URLFor(name string, pairs ...string) string { leaf, ok := r.namedRoutes[name] if !ok { panic("route with given name does not exists: " + name) } return leaf.URLPath(pairs...) } // ComboRouter represents a combo router. type ComboRouter struct { router *Router pattern string handlers []Handler methods map[string]bool // Registered methods. lastRoute *Route } func (cr *ComboRouter) checkMethod(name string) { if cr.methods[name] { panic("method '" + name + "' has already been registered") } cr.methods[name] = true } func (cr *ComboRouter) route(fn func(string, ...Handler) *Route, method string, h ...Handler) *ComboRouter { cr.checkMethod(method) cr.lastRoute = fn(cr.pattern, append(cr.handlers, h...)...) return cr } func (cr *ComboRouter) Get(h ...Handler) *ComboRouter { return cr.route(cr.router.Get, "GET", h...) } func (cr *ComboRouter) Patch(h ...Handler) *ComboRouter { return cr.route(cr.router.Patch, "PATCH", h...) } func (cr *ComboRouter) Post(h ...Handler) *ComboRouter { return cr.route(cr.router.Post, "POST", h...) } func (cr *ComboRouter) Put(h ...Handler) *ComboRouter { return cr.route(cr.router.Put, "PUT", h...) } func (cr *ComboRouter) Delete(h ...Handler) *ComboRouter { return cr.route(cr.router.Delete, "DELETE", h...) } func (cr *ComboRouter) Options(h ...Handler) *ComboRouter { return cr.route(cr.router.Options, "OPTIONS", h...) } func (cr *ComboRouter) Head(h ...Handler) *ComboRouter { return cr.route(cr.router.Head, "HEAD", h...) } // Name sets name of ComboRouter route. func (cr *ComboRouter) Name(name string) { if cr.lastRoute == nil { panic("no corresponding route to be named") } cr.lastRoute.Name(name) }
Godeps/_workspace/src/gopkg.in/macaron.v1/router.go
0
https://github.com/grafana/grafana/commit/bf943ddba38ced67da56f0cfd847760f41d31e61
[ 0.009362777695059776, 0.0017458283109590411, 0.00017051764007192105, 0.0005541814025491476, 0.0024148712400346994 ]
{ "id": 5, "code_window": [ "\tw.maxsize_cursize += size\n", "}\n", "\n", "// write logger message into file.\n", "func (w *FileLogWriter) WriteMsg(msg string, skip, level int) error {\n", "\tif level < w.Level {\n", "\t\treturn nil\n", "\t}\n", "\tn := 24 + len(msg) // 24 stand for the length \"2013/06/23 21:00:22 [T] \"\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "func (w *FileLogWriter) WriteMsg(msg string, skip int, level LogLevel) error {\n" ], "file_path": "pkg/log/file.go", "type": "replace", "edit_start_line_idx": 134 }
input[type=text].input-fluid { width: 100%; box-sizing: border-box; padding: 10px; font-size: 16px; -moz-box-sizing: border-box; height: 100%; } input[type="checkbox"].cr1 { display: none; } .editor-option label.cr1 { display: inline-block; margin: 5px 0 1px 0; } label.cr1 { display: inline-block; height: 18px; position: relative; top: -2px; clear: none; text-indent: 2px; margin: 0 0 0px 0; padding: 0 0 0 23px; vertical-align:middle; background: url(@checkboxImageUrl) left top no-repeat; cursor:pointer; } input[type="checkbox"]:checked+label { background: url(@checkboxImageUrl) 0px -18px no-repeat; } .gf-form { padding-bottom: 10px; .checkbox-label { padding-left: 7px; display: inline; } } .gf-fluid-input { border: none; display: block; overflow: hidden; padding-right: 10px; input[type=text] { width: 100%; padding: 5px 6px; height: 100%; box-sizing: border-box; } textarea { width: 100%; padding: 5px 6px; height: 100%; box-sizing: border-box; } }
public/less/forms.less
0
https://github.com/grafana/grafana/commit/bf943ddba38ced67da56f0cfd847760f41d31e61
[ 0.0004002374189440161, 0.00025247022858820856, 0.00017044937703758478, 0.00021016263053752482, 0.00008515886293025687 ]
{ "id": 6, "code_window": [ "// \\/ \\/ \\/ \\/ \\/\n", "\n", "type LogLevel int\n", "\n", "const (\n", "\tTRACE = iota\n", "\tDEBUG\n", "\tINFO\n", "\tWARN\n", "\tERROR\n", "\tCRITICAL\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tTRACE LogLevel = iota\n" ], "file_path": "pkg/log/log.go", "type": "replace", "edit_start_line_idx": 101 }
// Copyright 2014 The Gogs Authors. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. package log import ( "encoding/json" "fmt" "log" "os" "runtime" ) type Brush func(string) string func NewBrush(color string) Brush { pre := "\033[" reset := "\033[0m" return func(text string) string { return pre + color + "m" + text + reset } } var ( Red = NewBrush("1;31") Purple = NewBrush("1;35") Yellow = NewBrush("1;33") Green = NewBrush("1;32") Blue = NewBrush("1;34") Cyan = NewBrush("1;36") colors = []Brush{ Cyan, // Trace cyan Blue, // Debug blue Green, // Info green Yellow, // Warn yellow Red, // Error red Purple, // Critical purple Red, // Fatal red } consoleWriter = &ConsoleWriter{lg: log.New(os.Stdout, "", 0), Level: TRACE} ) // ConsoleWriter implements LoggerInterface and writes messages to terminal. type ConsoleWriter struct { lg *log.Logger Level int `json:"level"` Formatting bool `json:"formatting"` } // create ConsoleWriter returning as LoggerInterface. func NewConsole() LoggerInterface { return &ConsoleWriter{ lg: log.New(os.Stderr, "", log.Ldate|log.Ltime), Level: TRACE, Formatting: true, } } func (cw *ConsoleWriter) Init(config string) error { return json.Unmarshal([]byte(config), cw) } func (cw *ConsoleWriter) WriteMsg(msg string, skip, level int) error { if cw.Level > level { return nil } if runtime.GOOS == "windows" || !cw.Formatting { cw.lg.Println(msg) } else { cw.lg.Println(colors[level](msg)) } return nil } func (_ *ConsoleWriter) Flush() { } func (_ *ConsoleWriter) Destroy() { } func printConsole(level int, msg string) { consoleWriter.WriteMsg(msg, 0, level) } func printfConsole(level int, format string, v ...interface{}) { consoleWriter.WriteMsg(fmt.Sprintf(format, v...), 0, level) } // ConsoleTrace prints to stdout using TRACE colors func ConsoleTrace(s string) { printConsole(TRACE, s) } // ConsoleTracef prints a formatted string to stdout using TRACE colors func ConsoleTracef(format string, v ...interface{}) { printfConsole(TRACE, format, v...) } // ConsoleDebug prints to stdout using DEBUG colors func ConsoleDebug(s string) { printConsole(DEBUG, s) } // ConsoleDebugf prints a formatted string to stdout using DEBUG colors func ConsoleDebugf(format string, v ...interface{}) { printfConsole(DEBUG, format, v...) } // ConsoleInfo prints to stdout using INFO colors func ConsoleInfo(s string) { printConsole(INFO, s) } // ConsoleInfof prints a formatted string to stdout using INFO colors func ConsoleInfof(format string, v ...interface{}) { printfConsole(INFO, format, v...) } // ConsoleWarn prints to stdout using WARN colors func ConsoleWarn(s string) { printConsole(WARN, s) } // ConsoleWarnf prints a formatted string to stdout using WARN colors func ConsoleWarnf(format string, v ...interface{}) { printfConsole(WARN, format, v...) } // ConsoleError prints to stdout using ERROR colors func ConsoleError(s string) { printConsole(ERROR, s) } // ConsoleErrorf prints a formatted string to stdout using ERROR colors func ConsoleErrorf(format string, v ...interface{}) { printfConsole(ERROR, format, v...) } // ConsoleFatal prints to stdout using FATAL colors func ConsoleFatal(s string) { printConsole(FATAL, s) os.Exit(1) } // ConsoleFatalf prints a formatted string to stdout using FATAL colors func ConsoleFatalf(format string, v ...interface{}) { printfConsole(FATAL, format, v...) os.Exit(1) } func init() { Register("console", NewConsole) }
pkg/log/console.go
1
https://github.com/grafana/grafana/commit/bf943ddba38ced67da56f0cfd847760f41d31e61
[ 0.9977466464042664, 0.12526896595954895, 0.0001671199715929106, 0.0013577323406934738, 0.32698556780815125 ]
{ "id": 6, "code_window": [ "// \\/ \\/ \\/ \\/ \\/\n", "\n", "type LogLevel int\n", "\n", "const (\n", "\tTRACE = iota\n", "\tDEBUG\n", "\tINFO\n", "\tWARN\n", "\tERROR\n", "\tCRITICAL\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tTRACE LogLevel = iota\n" ], "file_path": "pkg/log/log.go", "type": "replace", "edit_start_line_idx": 101 }
package util import ( "net/url" "strings" ) type UrlQueryReader struct { values url.Values } func NewUrlQueryReader(url *url.URL) *UrlQueryReader { return &UrlQueryReader{ values: url.Query(), } } func (r *UrlQueryReader) Get(name string, def string) string { val := r.values[name] if len(val) == 0 { return def } return val[0] } func JoinUrlFragments(a, b string) string { aslash := strings.HasSuffix(a, "/") bslash := strings.HasPrefix(b, "/") if len(b) == 0 { return a } switch { case aslash && bslash: return a + b[1:] case !aslash && !bslash: return a + "/" + b } return a + b }
pkg/util/url.go
0
https://github.com/grafana/grafana/commit/bf943ddba38ced67da56f0cfd847760f41d31e61
[ 0.00043248015572316945, 0.00022383146279025823, 0.000167971957125701, 0.00017366299289278686, 0.00010435198055347428 ]
{ "id": 6, "code_window": [ "// \\/ \\/ \\/ \\/ \\/\n", "\n", "type LogLevel int\n", "\n", "const (\n", "\tTRACE = iota\n", "\tDEBUG\n", "\tINFO\n", "\tWARN\n", "\tERROR\n", "\tCRITICAL\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tTRACE LogLevel = iota\n" ], "file_path": "pkg/log/log.go", "type": "replace", "edit_start_line_idx": 101 }
{ "data": [ { "credential": { "_class": "OAuth2Credentials", "_module": "oauth2client.client", "access_token": "foo_access_token", "client_id": "foo_client_id", "client_secret": "foo_client_secret", "id_token": { "at_hash": "foo_at_hash", "aud": "foo_aud", "azp": "foo_azp", "cid": "foo_cid", "email": "[email protected]", "email_verified": true, "exp": 1420573614, "iat": 1420569714, "id": "1337", "iss": "accounts.google.com", "sub": "1337", "token_hash": "foo_token_hash", "verified_email": true }, "invalid": false, "refresh_token": "foo_refresh_token", "revoke_uri": "https://accounts.google.com/o/oauth2/revoke", "token_expiry": "2015-01-09T00:51:51Z", "token_response": { "access_token": "foo_access_token", "expires_in": 3600, "id_token": "foo_id_token", "token_type": "Bearer" }, "token_uri": "https://accounts.google.com/o/oauth2/token", "user_agent": "Cloud SDK Command Line Tool" }, "key": { "account": "[email protected]", "clientId": "foo_client_id", "scope": "https://www.googleapis.com/auth/appengine.admin https://www.googleapis.com/auth/bigquery https://www.googleapis.com/auth/compute https://www.googleapis.com/auth/devstorage.full_control https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/ndev.cloudman https://www.googleapis.com/auth/cloud-platform https://www.googleapis.com/auth/sqlservice.admin https://www.googleapis.com/auth/prediction https://www.googleapis.com/auth/projecthosting", "type": "google-cloud-sdk" } }, { "credential": { "_class": "OAuth2Credentials", "_module": "oauth2client.client", "access_token": "bar_access_token", "client_id": "bar_client_id", "client_secret": "bar_client_secret", "id_token": { "at_hash": "bar_at_hash", "aud": "bar_aud", "azp": "bar_azp", "cid": "bar_cid", "email": "[email protected]", "email_verified": true, "exp": 1420573614, "iat": 1420569714, "id": "1337", "iss": "accounts.google.com", "sub": "1337", "token_hash": "bar_token_hash", "verified_email": true }, "invalid": false, "refresh_token": "bar_refresh_token", "revoke_uri": "https://accounts.google.com/o/oauth2/revoke", "token_expiry": "2015-01-09T00:51:51Z", "token_response": { "access_token": "bar_access_token", "expires_in": 3600, "id_token": "bar_id_token", "token_type": "Bearer" }, "token_uri": "https://accounts.google.com/o/oauth2/token", "user_agent": "Cloud SDK Command Line Tool" }, "key": { "account": "[email protected]", "clientId": "bar_client_id", "scope": "https://www.googleapis.com/auth/appengine.admin https://www.googleapis.com/auth/bigquery https://www.googleapis.com/auth/compute https://www.googleapis.com/auth/devstorage.full_control https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/ndev.cloudman https://www.googleapis.com/auth/cloud-platform https://www.googleapis.com/auth/sqlservice.admin https://www.googleapis.com/auth/prediction https://www.googleapis.com/auth/projecthosting", "type": "google-cloud-sdk" } }, { "credential": { "_class": "ServiceAccountCredentials", "_kwargs": {}, "_module": "oauth2client.client", "_private_key_id": "00000000000000000000000000000000", "_private_key_pkcs8_text": "-----BEGIN RSA PRIVATE KEY-----\nMIICWwIBAAKBgQCt3fpiynPSaUhWSIKMGV331zudwJ6GkGmvQtwsoK2S2LbvnSwU\nNxgj4fp08kIDR5p26wF4+t/HrKydMwzftXBfZ9UmLVJgRdSswmS5SmChCrfDS5OE\nvFFcN5+6w1w8/Nu657PF/dse8T0bV95YrqyoR0Osy8WHrUOMSIIbC3hRuwIDAQAB\nAoGAJrGE/KFjn0sQ7yrZ6sXmdLawrM3mObo/2uI9T60+k7SpGbBX0/Pi6nFrJMWZ\nTVONG7P3Mu5aCPzzuVRYJB0j8aldSfzABTY3HKoWCczqw1OztJiEseXGiYz4QOyr\nYU3qDyEpdhS6q6wcoLKGH+hqRmz6pcSEsc8XzOOu7s4xW8kCQQDkc75HjhbarCnd\nJJGMe3U76+6UGmdK67ltZj6k6xoB5WbTNChY9TAyI2JC+ppYV89zv3ssj4L+02u3\nHIHFGxsHAkEAwtU1qYb1tScpchPobnYUFiVKJ7KA8EZaHVaJJODW/cghTCV7BxcJ\nbgVvlmk4lFKn3lPKAgWw7PdQsBTVBUcCrQJATPwoIirizrv3u5soJUQxZIkENAqV\nxmybZx9uetrzP7JTrVbFRf0SScMcyN90hdLJiQL8+i4+gaszgFht7sNMnwJAAbfj\nq0UXcauQwALQ7/h2oONfTg5S+MuGC/AxcXPSMZbMRGGoPh3D5YaCv27aIuS/ukQ+\n6dmm/9AGlCb64fsIWQJAPaokbjIifo+LwC5gyK73Mc4t8nAOSZDenzd/2f6TCq76\nS1dcnKiPxaED7W/y6LJiuBT2rbZiQ2L93NJpFZD/UA==\n-----END RSA PRIVATE KEY-----\n", "_revoke_uri": "https://accounts.google.com/o/oauth2/revoke", "_scopes": "https://www.googleapis.com/auth/appengine.admin https://www.googleapis.com/auth/bigquery https://www.googleapis.com/auth/compute https://www.googleapis.com/auth/devstorage.full_control https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/ndev.cloudman https://www.googleapis.com/auth/cloud-platform https://www.googleapis.com/auth/sqlservice.admin https://www.googleapis.com/auth/prediction https://www.googleapis.com/auth/projecthosting", "_service_account_email": "[email protected]", "_service_account_id": "baz.serviceaccount.example.com", "_token_uri": "https://accounts.google.com/o/oauth2/token", "_user_agent": "Cloud SDK Command Line Tool", "access_token": null, "assertion_type": null, "client_id": null, "client_secret": null, "id_token": null, "invalid": false, "refresh_token": null, "revoke_uri": "https://accounts.google.com/o/oauth2/revoke", "service_account_name": "[email protected]", "token_expiry": null, "token_response": null, "user_agent": "Cloud SDK Command Line Tool" }, "key": { "account": "[email protected]", "clientId": "baz_client_id", "scope": "https://www.googleapis.com/auth/appengine.admin https://www.googleapis.com/auth/bigquery https://www.googleapis.com/auth/compute https://www.googleapis.com/auth/devstorage.full_control https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/ndev.cloudman https://www.googleapis.com/auth/cloud-platform https://www.googleapis.com/auth/sqlservice.admin https://www.googleapis.com/auth/prediction https://www.googleapis.com/auth/projecthosting", "type": "google-cloud-sdk" } } ], "file_version": 1 }
Godeps/_workspace/src/golang.org/x/oauth2/google/testdata/gcloud/credentials
0
https://github.com/grafana/grafana/commit/bf943ddba38ced67da56f0cfd847760f41d31e61
[ 0.000290109368506819, 0.00017949087487068027, 0.00016778755525592715, 0.00017086431034840643, 0.00003196033139829524 ]
{ "id": 6, "code_window": [ "// \\/ \\/ \\/ \\/ \\/\n", "\n", "type LogLevel int\n", "\n", "const (\n", "\tTRACE = iota\n", "\tDEBUG\n", "\tINFO\n", "\tWARN\n", "\tERROR\n", "\tCRITICAL\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tTRACE LogLevel = iota\n" ], "file_path": "pkg/log/log.go", "type": "replace", "edit_start_line_idx": 101 }
import {describe, beforeEach, it, sinon, expect, angularMocks} from 'test/lib/common'; import helpers from 'test/specs/helpers'; import Datasource from "../datasource"; describe('opentsdb', function() { var ctx = new helpers.ServiceTestContext(); var instanceSettings = {url: '' }; beforeEach(angularMocks.module('grafana.core')); beforeEach(angularMocks.module('grafana.services')); beforeEach(ctx.providePhase(['backendSrv'])); beforeEach(angularMocks.inject(function($q, $rootScope, $httpBackend, $injector) { ctx.$q = $q; ctx.$httpBackend = $httpBackend; ctx.$rootScope = $rootScope; ctx.ds = $injector.instantiate(Datasource, {instanceSettings: instanceSettings}); })); describe('When performing metricFindQuery', function() { var results; var requestOptions; beforeEach(function() { ctx.backendSrv.datasourceRequest = function(options) { requestOptions = options; return ctx.$q.when({data: [{ target: 'prod1.count', datapoints: [[10, 1], [12,1]] }]}); }; }); it('metrics() should generate api suggest query', function() { ctx.ds.metricFindQuery('metrics(pew)').then(function(data) { results = data; }); ctx.$rootScope.$apply(); expect(requestOptions.url).to.be('/api/suggest'); expect(requestOptions.params.type).to.be('metrics'); expect(requestOptions.params.q).to.be('pew'); }); it('tag_names(cpu) should generate lookup query', function() { ctx.ds.metricFindQuery('tag_names(cpu)').then(function(data) { results = data; }); ctx.$rootScope.$apply(); expect(requestOptions.url).to.be('/api/search/lookup'); expect(requestOptions.params.m).to.be('cpu'); }); it('tag_values(cpu, test) should generate lookup query', function() { ctx.ds.metricFindQuery('tag_values(cpu, hostname)').then(function(data) { results = data; }); ctx.$rootScope.$apply(); expect(requestOptions.url).to.be('/api/search/lookup'); expect(requestOptions.params.m).to.be('cpu{hostname=*}'); }); it('suggest_tagk() should generate api suggest query', function() { ctx.ds.metricFindQuery('suggest_tagk(foo)').then(function(data) { results = data; }); ctx.$rootScope.$apply(); expect(requestOptions.url).to.be('/api/suggest'); expect(requestOptions.params.type).to.be('tagk'); expect(requestOptions.params.q).to.be('foo'); }); it('suggest_tagv() should generate api suggest query', function() { ctx.ds.metricFindQuery('suggest_tagv(bar)').then(function(data) { results = data; }); ctx.$rootScope.$apply(); expect(requestOptions.url).to.be('/api/suggest'); expect(requestOptions.params.type).to.be('tagv'); expect(requestOptions.params.q).to.be('bar'); }); }); });
public/app/plugins/datasource/opentsdb/specs/datasource-specs.ts
0
https://github.com/grafana/grafana/commit/bf943ddba38ced67da56f0cfd847760f41d31e61
[ 0.0001899331691674888, 0.000175057677552104, 0.0001705153554212302, 0.0001736745034577325, 0.000005738292657042621 ]
{ "id": 7, "code_window": [ "// LoggerInterface represents behaviors of a logger provider.\n", "type LoggerInterface interface {\n", "\tInit(config string) error\n", "\tWriteMsg(msg string, skip, level int) error\n", "\tDestroy()\n", "\tFlush()\n", "}\n", "\n", "type loggerType func() LoggerInterface\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tWriteMsg(msg string, skip int, level LogLevel) error\n" ], "file_path": "pkg/log/log.go", "type": "replace", "edit_start_line_idx": 113 }
// Copyright 2014 The Gogs Authors. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. package log import ( "encoding/json" "errors" "fmt" "io/ioutil" "log" "os" "path/filepath" "strings" "sync" "time" ) // FileLogWriter implements LoggerInterface. // It writes messages by lines limit, file size limit, or time frequency. type FileLogWriter struct { *log.Logger mw *MuxWriter // The opened file Filename string `json:"filename"` Maxlines int `json:"maxlines"` maxlines_curlines int // Rotate at size Maxsize int `json:"maxsize"` maxsize_cursize int // Rotate daily Daily bool `json:"daily"` Maxdays int64 `json:"maxdays"` daily_opendate int Rotate bool `json:"rotate"` startLock sync.Mutex // Only one log can write to the file Level int `json:"level"` } // an *os.File writer with locker. type MuxWriter struct { sync.Mutex fd *os.File } // write to os.File. func (l *MuxWriter) Write(b []byte) (int, error) { l.Lock() defer l.Unlock() return l.fd.Write(b) } // set os.File in writer. func (l *MuxWriter) SetFd(fd *os.File) { if l.fd != nil { l.fd.Close() } l.fd = fd } // create a FileLogWriter returning as LoggerInterface. func NewFileWriter() LoggerInterface { w := &FileLogWriter{ Filename: "", Maxlines: 1000000, Maxsize: 1 << 28, //256 MB Daily: true, Maxdays: 7, Rotate: true, Level: TRACE, } // use MuxWriter instead direct use os.File for lock write when rotate w.mw = new(MuxWriter) // set MuxWriter as Logger's io.Writer w.Logger = log.New(w.mw, "", log.Ldate|log.Ltime) return w } // Init file logger with json config. // config like: // { // "filename":"log/gogs.log", // "maxlines":10000, // "maxsize":1<<30, // "daily":true, // "maxdays":15, // "rotate":true // } func (w *FileLogWriter) Init(config string) error { if err := json.Unmarshal([]byte(config), w); err != nil { return err } if len(w.Filename) == 0 { return errors.New("config must have filename") } return w.StartLogger() } // start file logger. create log file and set to locker-inside file writer. func (w *FileLogWriter) StartLogger() error { fd, err := w.createLogFile() if err != nil { return err } w.mw.SetFd(fd) if err = w.initFd(); err != nil { return err } return nil } func (w *FileLogWriter) docheck(size int) { w.startLock.Lock() defer w.startLock.Unlock() if w.Rotate && ((w.Maxlines > 0 && w.maxlines_curlines >= w.Maxlines) || (w.Maxsize > 0 && w.maxsize_cursize >= w.Maxsize) || (w.Daily && time.Now().Day() != w.daily_opendate)) { if err := w.DoRotate(); err != nil { fmt.Fprintf(os.Stderr, "FileLogWriter(%q): %s\n", w.Filename, err) return } } w.maxlines_curlines++ w.maxsize_cursize += size } // write logger message into file. func (w *FileLogWriter) WriteMsg(msg string, skip, level int) error { if level < w.Level { return nil } n := 24 + len(msg) // 24 stand for the length "2013/06/23 21:00:22 [T] " w.docheck(n) w.Logger.Println(msg) return nil } func (w *FileLogWriter) createLogFile() (*os.File, error) { // Open the log file return os.OpenFile(w.Filename, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0644) } func (w *FileLogWriter) initFd() error { fd := w.mw.fd finfo, err := fd.Stat() if err != nil { return fmt.Errorf("get stat: %s\n", err) } w.maxsize_cursize = int(finfo.Size()) w.daily_opendate = time.Now().Day() if finfo.Size() > 0 { content, err := ioutil.ReadFile(w.Filename) if err != nil { return err } w.maxlines_curlines = len(strings.Split(string(content), "\n")) } else { w.maxlines_curlines = 0 } return nil } // DoRotate means it need to write file in new file. // new file name like xx.log.2013-01-01.2 func (w *FileLogWriter) DoRotate() error { _, err := os.Lstat(w.Filename) if err == nil { // file exists // Find the next available number num := 1 fname := "" for ; err == nil && num <= 999; num++ { fname = w.Filename + fmt.Sprintf(".%s.%03d", time.Now().Format("2006-01-02"), num) _, err = os.Lstat(fname) } // return error if the last file checked still existed if err == nil { return fmt.Errorf("rotate: cannot find free log number to rename %s\n", w.Filename) } // block Logger's io.Writer w.mw.Lock() defer w.mw.Unlock() fd := w.mw.fd fd.Close() // close fd before rename // Rename the file to its newfound home if err = os.Rename(w.Filename, fname); err != nil { return fmt.Errorf("Rotate: %s\n", err) } // re-start logger if err = w.StartLogger(); err != nil { return fmt.Errorf("Rotate StartLogger: %s\n", err) } go w.deleteOldLog() } return nil } func (w *FileLogWriter) deleteOldLog() { dir := filepath.Dir(w.Filename) filepath.Walk(dir, func(path string, info os.FileInfo, err error) (returnErr error) { defer func() { if r := recover(); r != nil { returnErr = fmt.Errorf("Unable to delete old log '%s', error: %+v", path, r) } }() if !info.IsDir() && info.ModTime().Unix() < (time.Now().Unix()-60*60*24*w.Maxdays) { if strings.HasPrefix(filepath.Base(path), filepath.Base(w.Filename)) { os.Remove(path) } } return returnErr }) } // destroy file logger, close file writer. func (w *FileLogWriter) Destroy() { w.mw.fd.Close() } // flush file logger. // there are no buffering messages in file logger in memory. // flush file means sync file from disk. func (w *FileLogWriter) Flush() { w.mw.fd.Sync() } func init() { Register("file", NewFileWriter) }
pkg/log/file.go
1
https://github.com/grafana/grafana/commit/bf943ddba38ced67da56f0cfd847760f41d31e61
[ 0.9831998348236084, 0.04905848577618599, 0.0001654144434724003, 0.0003138318134006113, 0.19574113190174103 ]
{ "id": 7, "code_window": [ "// LoggerInterface represents behaviors of a logger provider.\n", "type LoggerInterface interface {\n", "\tInit(config string) error\n", "\tWriteMsg(msg string, skip, level int) error\n", "\tDestroy()\n", "\tFlush()\n", "}\n", "\n", "type loggerType func() LoggerInterface\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tWriteMsg(msg string, skip int, level LogLevel) error\n" ], "file_path": "pkg/log/log.go", "type": "replace", "edit_start_line_idx": 113 }
/** * @license AngularJS v1.5.0-rc.0 * (c) 2010-2015 Google, Inc. http://angularjs.org * License: MIT */ (function(window, angular, undefined) {'use strict'; /** * @ngdoc module * @name ngRoute * @description * * # ngRoute * * The `ngRoute` module provides routing and deeplinking services and directives for angular apps. * * ## Example * See {@link ngRoute.$route#example $route} for an example of configuring and using `ngRoute`. * * * <div doc-module-components="ngRoute"></div> */ /* global -ngRouteModule */ var ngRouteModule = angular.module('ngRoute', ['ng']). provider('$route', $RouteProvider), $routeMinErr = angular.$$minErr('ngRoute'); /** * @ngdoc provider * @name $routeProvider * * @description * * Used for configuring routes. * * ## Example * See {@link ngRoute.$route#example $route} for an example of configuring and using `ngRoute`. * * ## Dependencies * Requires the {@link ngRoute `ngRoute`} module to be installed. */ function $RouteProvider() { function inherit(parent, extra) { return angular.extend(Object.create(parent), extra); } var routes = {}; /** * @ngdoc method * @name $routeProvider#when * * @param {string} path Route path (matched against `$location.path`). If `$location.path` * contains redundant trailing slash or is missing one, the route will still match and the * `$location.path` will be updated to add or drop the trailing slash to exactly match the * route definition. * * * `path` can contain named groups starting with a colon: e.g. `:name`. All characters up * to the next slash are matched and stored in `$routeParams` under the given `name` * when the route matches. * * `path` can contain named groups starting with a colon and ending with a star: * e.g.`:name*`. All characters are eagerly stored in `$routeParams` under the given `name` * when the route matches. * * `path` can contain optional named groups with a question mark: e.g.`:name?`. * * For example, routes like `/color/:color/largecode/:largecode*\/edit` will match * `/color/brown/largecode/code/with/slashes/edit` and extract: * * * `color: brown` * * `largecode: code/with/slashes`. * * * @param {Object} route Mapping information to be assigned to `$route.current` on route * match. * * Object properties: * * - `controller` – `{(string|function()=}` – Controller fn that should be associated with * newly created scope or the name of a {@link angular.Module#controller registered * controller} if passed as a string. * - `controllerAs` – `{string=}` – An identifier name for a reference to the controller. * If present, the controller will be published to scope under the `controllerAs` name. * - `template` – `{string=|function()=}` – html template as a string or a function that * returns an html template as a string which should be used by {@link * ngRoute.directive:ngView ngView} or {@link ng.directive:ngInclude ngInclude} directives. * This property takes precedence over `templateUrl`. * * If `template` is a function, it will be called with the following parameters: * * - `{Array.<Object>}` - route parameters extracted from the current * `$location.path()` by applying the current route * * - `templateUrl` – `{string=|function()=}` – path or function that returns a path to an html * template that should be used by {@link ngRoute.directive:ngView ngView}. * * If `templateUrl` is a function, it will be called with the following parameters: * * - `{Array.<Object>}` - route parameters extracted from the current * `$location.path()` by applying the current route * * - `resolve` - `{Object.<string, function>=}` - An optional map of dependencies which should * be injected into the controller. If any of these dependencies are promises, the router * will wait for them all to be resolved or one to be rejected before the controller is * instantiated. * If all the promises are resolved successfully, the values of the resolved promises are * injected and {@link ngRoute.$route#$routeChangeSuccess $routeChangeSuccess} event is * fired. If any of the promises are rejected the * {@link ngRoute.$route#$routeChangeError $routeChangeError} event is fired. The map object * is: * * - `key` – `{string}`: a name of a dependency to be injected into the controller. * - `factory` - `{string|function}`: If `string` then it is an alias for a service. * Otherwise if function, then it is {@link auto.$injector#invoke injected} * and the return value is treated as the dependency. If the result is a promise, it is * resolved before its value is injected into the controller. Be aware that * `ngRoute.$routeParams` will still refer to the previous route within these resolve * functions. Use `$route.current.params` to access the new route parameters, instead. * * - `redirectTo` – {(string|function())=} – value to update * {@link ng.$location $location} path with and trigger route redirection. * * If `redirectTo` is a function, it will be called with the following parameters: * * - `{Object.<string>}` - route parameters extracted from the current * `$location.path()` by applying the current route templateUrl. * - `{string}` - current `$location.path()` * - `{Object}` - current `$location.search()` * * The custom `redirectTo` function is expected to return a string which will be used * to update `$location.path()` and `$location.search()`. * * - `[reloadOnSearch=true]` - {boolean=} - reload route when only `$location.search()` * or `$location.hash()` changes. * * If the option is set to `false` and url in the browser changes, then * `$routeUpdate` event is broadcasted on the root scope. * * - `[caseInsensitiveMatch=false]` - {boolean=} - match routes without being case sensitive * * If the option is set to `true`, then the particular route can be matched without being * case sensitive * * @returns {Object} self * * @description * Adds a new route definition to the `$route` service. */ this.when = function(path, route) { //copy original route object to preserve params inherited from proto chain var routeCopy = angular.copy(route); if (angular.isUndefined(routeCopy.reloadOnSearch)) { routeCopy.reloadOnSearch = true; } if (angular.isUndefined(routeCopy.caseInsensitiveMatch)) { routeCopy.caseInsensitiveMatch = this.caseInsensitiveMatch; } routes[path] = angular.extend( routeCopy, path && pathRegExp(path, routeCopy) ); // create redirection for trailing slashes if (path) { var redirectPath = (path[path.length - 1] == '/') ? path.substr(0, path.length - 1) : path + '/'; routes[redirectPath] = angular.extend( {redirectTo: path}, pathRegExp(redirectPath, routeCopy) ); } return this; }; /** * @ngdoc property * @name $routeProvider#caseInsensitiveMatch * @description * * A boolean property indicating if routes defined * using this provider should be matched using a case insensitive * algorithm. Defaults to `false`. */ this.caseInsensitiveMatch = false; /** * @param path {string} path * @param opts {Object} options * @return {?Object} * * @description * Normalizes the given path, returning a regular expression * and the original path. * * Inspired by pathRexp in visionmedia/express/lib/utils.js. */ function pathRegExp(path, opts) { var insensitive = opts.caseInsensitiveMatch, ret = { originalPath: path, regexp: path }, keys = ret.keys = []; path = path .replace(/([().])/g, '\\$1') .replace(/(\/)?:(\w+)([\?\*])?/g, function(_, slash, key, option) { var optional = option === '?' ? option : null; var star = option === '*' ? option : null; keys.push({ name: key, optional: !!optional }); slash = slash || ''; return '' + (optional ? '' : slash) + '(?:' + (optional ? slash : '') + (star && '(.+?)' || '([^/]+)') + (optional || '') + ')' + (optional || ''); }) .replace(/([\/$\*])/g, '\\$1'); ret.regexp = new RegExp('^' + path + '$', insensitive ? 'i' : ''); return ret; } /** * @ngdoc method * @name $routeProvider#otherwise * * @description * Sets route definition that will be used on route change when no other route definition * is matched. * * @param {Object|string} params Mapping information to be assigned to `$route.current`. * If called with a string, the value maps to `redirectTo`. * @returns {Object} self */ this.otherwise = function(params) { if (typeof params === 'string') { params = {redirectTo: params}; } this.when(null, params); return this; }; this.$get = ['$rootScope', '$location', '$routeParams', '$q', '$injector', '$templateRequest', '$sce', function($rootScope, $location, $routeParams, $q, $injector, $templateRequest, $sce) { /** * @ngdoc service * @name $route * @requires $location * @requires $routeParams * * @property {Object} current Reference to the current route definition. * The route definition contains: * * - `controller`: The controller constructor as define in route definition. * - `locals`: A map of locals which is used by {@link ng.$controller $controller} service for * controller instantiation. The `locals` contain * the resolved values of the `resolve` map. Additionally the `locals` also contain: * * - `$scope` - The current route scope. * - `$template` - The current route template HTML. * * @property {Object} routes Object with all route configuration Objects as its properties. * * @description * `$route` is used for deep-linking URLs to controllers and views (HTML partials). * It watches `$location.url()` and tries to map the path to an existing route definition. * * Requires the {@link ngRoute `ngRoute`} module to be installed. * * You can define routes through {@link ngRoute.$routeProvider $routeProvider}'s API. * * The `$route` service is typically used in conjunction with the * {@link ngRoute.directive:ngView `ngView`} directive and the * {@link ngRoute.$routeParams `$routeParams`} service. * * @example * This example shows how changing the URL hash causes the `$route` to match a route against the * URL, and the `ngView` pulls in the partial. * * <example name="$route-service" module="ngRouteExample" * deps="angular-route.js" fixBase="true"> * <file name="index.html"> * <div ng-controller="MainController"> * Choose: * <a href="Book/Moby">Moby</a> | * <a href="Book/Moby/ch/1">Moby: Ch1</a> | * <a href="Book/Gatsby">Gatsby</a> | * <a href="Book/Gatsby/ch/4?key=value">Gatsby: Ch4</a> | * <a href="Book/Scarlet">Scarlet Letter</a><br/> * * <div ng-view></div> * * <hr /> * * <pre>$location.path() = {{$location.path()}}</pre> * <pre>$route.current.templateUrl = {{$route.current.templateUrl}}</pre> * <pre>$route.current.params = {{$route.current.params}}</pre> * <pre>$route.current.scope.name = {{$route.current.scope.name}}</pre> * <pre>$routeParams = {{$routeParams}}</pre> * </div> * </file> * * <file name="book.html"> * controller: {{name}}<br /> * Book Id: {{params.bookId}}<br /> * </file> * * <file name="chapter.html"> * controller: {{name}}<br /> * Book Id: {{params.bookId}}<br /> * Chapter Id: {{params.chapterId}} * </file> * * <file name="script.js"> * angular.module('ngRouteExample', ['ngRoute']) * * .controller('MainController', function($scope, $route, $routeParams, $location) { * $scope.$route = $route; * $scope.$location = $location; * $scope.$routeParams = $routeParams; * }) * * .controller('BookController', function($scope, $routeParams) { * $scope.name = "BookController"; * $scope.params = $routeParams; * }) * * .controller('ChapterController', function($scope, $routeParams) { * $scope.name = "ChapterController"; * $scope.params = $routeParams; * }) * * .config(function($routeProvider, $locationProvider) { * $routeProvider * .when('/Book/:bookId', { * templateUrl: 'book.html', * controller: 'BookController', * resolve: { * // I will cause a 1 second delay * delay: function($q, $timeout) { * var delay = $q.defer(); * $timeout(delay.resolve, 1000); * return delay.promise; * } * } * }) * .when('/Book/:bookId/ch/:chapterId', { * templateUrl: 'chapter.html', * controller: 'ChapterController' * }); * * // configure html5 to get links working on jsfiddle * $locationProvider.html5Mode(true); * }); * * </file> * * <file name="protractor.js" type="protractor"> * it('should load and compile correct template', function() { * element(by.linkText('Moby: Ch1')).click(); * var content = element(by.css('[ng-view]')).getText(); * expect(content).toMatch(/controller\: ChapterController/); * expect(content).toMatch(/Book Id\: Moby/); * expect(content).toMatch(/Chapter Id\: 1/); * * element(by.partialLinkText('Scarlet')).click(); * * content = element(by.css('[ng-view]')).getText(); * expect(content).toMatch(/controller\: BookController/); * expect(content).toMatch(/Book Id\: Scarlet/); * }); * </file> * </example> */ /** * @ngdoc event * @name $route#$routeChangeStart * @eventType broadcast on root scope * @description * Broadcasted before a route change. At this point the route services starts * resolving all of the dependencies needed for the route change to occur. * Typically this involves fetching the view template as well as any dependencies * defined in `resolve` route property. Once all of the dependencies are resolved * `$routeChangeSuccess` is fired. * * The route change (and the `$location` change that triggered it) can be prevented * by calling `preventDefault` method of the event. See {@link ng.$rootScope.Scope#$on} * for more details about event object. * * @param {Object} angularEvent Synthetic event object. * @param {Route} next Future route information. * @param {Route} current Current route information. */ /** * @ngdoc event * @name $route#$routeChangeSuccess * @eventType broadcast on root scope * @description * Broadcasted after a route change has happened successfully. * The `resolve` dependencies are now available in the `current.locals` property. * * {@link ngRoute.directive:ngView ngView} listens for the directive * to instantiate the controller and render the view. * * @param {Object} angularEvent Synthetic event object. * @param {Route} current Current route information. * @param {Route|Undefined} previous Previous route information, or undefined if current is * first route entered. */ /** * @ngdoc event * @name $route#$routeChangeError * @eventType broadcast on root scope * @description * Broadcasted if any of the resolve promises are rejected. * * @param {Object} angularEvent Synthetic event object * @param {Route} current Current route information. * @param {Route} previous Previous route information. * @param {Route} rejection Rejection of the promise. Usually the error of the failed promise. */ /** * @ngdoc event * @name $route#$routeUpdate * @eventType broadcast on root scope * @description * The `reloadOnSearch` property has been set to false, and we are reusing the same * instance of the Controller. * * @param {Object} angularEvent Synthetic event object * @param {Route} current Current/previous route information. */ var forceReload = false, preparedRoute, preparedRouteIsUpdateOnly, $route = { routes: routes, /** * @ngdoc method * @name $route#reload * * @description * Causes `$route` service to reload the current route even if * {@link ng.$location $location} hasn't changed. * * As a result of that, {@link ngRoute.directive:ngView ngView} * creates new scope and reinstantiates the controller. */ reload: function() { forceReload = true; $rootScope.$evalAsync(function() { // Don't support cancellation of a reload for now... prepareRoute(); commitRoute(); }); }, /** * @ngdoc method * @name $route#updateParams * * @description * Causes `$route` service to update the current URL, replacing * current route parameters with those specified in `newParams`. * Provided property names that match the route's path segment * definitions will be interpolated into the location's path, while * remaining properties will be treated as query params. * * @param {!Object<string, string>} newParams mapping of URL parameter names to values */ updateParams: function(newParams) { if (this.current && this.current.$$route) { newParams = angular.extend({}, this.current.params, newParams); $location.path(interpolate(this.current.$$route.originalPath, newParams)); // interpolate modifies newParams, only query params are left $location.search(newParams); } else { throw $routeMinErr('norout', 'Tried updating route when with no current route'); } } }; $rootScope.$on('$locationChangeStart', prepareRoute); $rootScope.$on('$locationChangeSuccess', commitRoute); return $route; ///////////////////////////////////////////////////// /** * @param on {string} current url * @param route {Object} route regexp to match the url against * @return {?Object} * * @description * Check if the route matches the current url. * * Inspired by match in * visionmedia/express/lib/router/router.js. */ function switchRouteMatcher(on, route) { var keys = route.keys, params = {}; if (!route.regexp) return null; var m = route.regexp.exec(on); if (!m) return null; for (var i = 1, len = m.length; i < len; ++i) { var key = keys[i - 1]; var val = m[i]; if (key && val) { params[key.name] = val; } } return params; } function prepareRoute($locationEvent) { var lastRoute = $route.current; preparedRoute = parseRoute(); preparedRouteIsUpdateOnly = preparedRoute && lastRoute && preparedRoute.$$route === lastRoute.$$route && angular.equals(preparedRoute.pathParams, lastRoute.pathParams) && !preparedRoute.reloadOnSearch && !forceReload; if (!preparedRouteIsUpdateOnly && (lastRoute || preparedRoute)) { if ($rootScope.$broadcast('$routeChangeStart', preparedRoute, lastRoute).defaultPrevented) { if ($locationEvent) { $locationEvent.preventDefault(); } } } } function commitRoute() { var lastRoute = $route.current; var nextRoute = preparedRoute; if (preparedRouteIsUpdateOnly) { lastRoute.params = nextRoute.params; angular.copy(lastRoute.params, $routeParams); $rootScope.$broadcast('$routeUpdate', lastRoute); } else if (nextRoute || lastRoute) { forceReload = false; $route.current = nextRoute; if (nextRoute) { if (nextRoute.redirectTo) { if (angular.isString(nextRoute.redirectTo)) { $location.path(interpolate(nextRoute.redirectTo, nextRoute.params)).search(nextRoute.params) .replace(); } else { $location.url(nextRoute.redirectTo(nextRoute.pathParams, $location.path(), $location.search())) .replace(); } } } $q.when(nextRoute). then(function() { if (nextRoute) { var locals = angular.extend({}, nextRoute.resolve), template, templateUrl; angular.forEach(locals, function(value, key) { locals[key] = angular.isString(value) ? $injector.get(value) : $injector.invoke(value, null, null, key); }); if (angular.isDefined(template = nextRoute.template)) { if (angular.isFunction(template)) { template = template(nextRoute.params); } } else if (angular.isDefined(templateUrl = nextRoute.templateUrl)) { if (angular.isFunction(templateUrl)) { templateUrl = templateUrl(nextRoute.params); } if (angular.isDefined(templateUrl)) { nextRoute.loadedTemplateUrl = $sce.valueOf(templateUrl); template = $templateRequest(templateUrl); } } if (angular.isDefined(template)) { locals['$template'] = template; } return $q.all(locals); } }). then(function(locals) { // after route change if (nextRoute == $route.current) { if (nextRoute) { nextRoute.locals = locals; angular.copy(nextRoute.params, $routeParams); } $rootScope.$broadcast('$routeChangeSuccess', nextRoute, lastRoute); } }, function(error) { if (nextRoute == $route.current) { $rootScope.$broadcast('$routeChangeError', nextRoute, lastRoute, error); } }); } } /** * @returns {Object} the current active route, by matching it against the URL */ function parseRoute() { // Match a route var params, match; angular.forEach(routes, function(route, path) { if (!match && (params = switchRouteMatcher($location.path(), route))) { match = inherit(route, { params: angular.extend({}, $location.search(), params), pathParams: params}); match.$$route = route; } }); // No route matched; fallback to "otherwise" route return match || routes[null] && inherit(routes[null], {params: {}, pathParams:{}}); } /** * @returns {string} interpolation of the redirect path with the parameters */ function interpolate(string, params) { var result = []; angular.forEach((string || '').split(':'), function(segment, i) { if (i === 0) { result.push(segment); } else { var segmentMatch = segment.match(/(\w+)(?:[?*])?(.*)/); var key = segmentMatch[1]; result.push(params[key]); result.push(segmentMatch[2] || ''); delete params[key]; } }); return result.join(''); } }]; } ngRouteModule.provider('$routeParams', $RouteParamsProvider); /** * @ngdoc service * @name $routeParams * @requires $route * * @description * The `$routeParams` service allows you to retrieve the current set of route parameters. * * Requires the {@link ngRoute `ngRoute`} module to be installed. * * The route parameters are a combination of {@link ng.$location `$location`}'s * {@link ng.$location#search `search()`} and {@link ng.$location#path `path()`}. * The `path` parameters are extracted when the {@link ngRoute.$route `$route`} path is matched. * * In case of parameter name collision, `path` params take precedence over `search` params. * * The service guarantees that the identity of the `$routeParams` object will remain unchanged * (but its properties will likely change) even when a route change occurs. * * Note that the `$routeParams` are only updated *after* a route change completes successfully. * This means that you cannot rely on `$routeParams` being correct in route resolve functions. * Instead you can use `$route.current.params` to access the new route's parameters. * * @example * ```js * // Given: * // URL: http://server.com/index.html#/Chapter/1/Section/2?search=moby * // Route: /Chapter/:chapterId/Section/:sectionId * // * // Then * $routeParams ==> {chapterId:'1', sectionId:'2', search:'moby'} * ``` */ function $RouteParamsProvider() { this.$get = function() { return {}; }; } ngRouteModule.directive('ngView', ngViewFactory); ngRouteModule.directive('ngView', ngViewFillContentFactory); /** * @ngdoc directive * @name ngView * @restrict ECA * * @description * # Overview * `ngView` is a directive that complements the {@link ngRoute.$route $route} service by * including the rendered template of the current route into the main layout (`index.html`) file. * Every time the current route changes, the included view changes with it according to the * configuration of the `$route` service. * * Requires the {@link ngRoute `ngRoute`} module to be installed. * * @animations * enter - animation is used to bring new content into the browser. * leave - animation is used to animate existing content away. * * The enter and leave animation occur concurrently. * * @scope * @priority 400 * @param {string=} onload Expression to evaluate whenever the view updates. * * @param {string=} autoscroll Whether `ngView` should call {@link ng.$anchorScroll * $anchorScroll} to scroll the viewport after the view is updated. * * - If the attribute is not set, disable scrolling. * - If the attribute is set without value, enable scrolling. * - Otherwise enable scrolling only if the `autoscroll` attribute value evaluated * as an expression yields a truthy value. * @example <example name="ngView-directive" module="ngViewExample" deps="angular-route.js;angular-animate.js" animations="true" fixBase="true"> <file name="index.html"> <div ng-controller="MainCtrl as main"> Choose: <a href="Book/Moby">Moby</a> | <a href="Book/Moby/ch/1">Moby: Ch1</a> | <a href="Book/Gatsby">Gatsby</a> | <a href="Book/Gatsby/ch/4?key=value">Gatsby: Ch4</a> | <a href="Book/Scarlet">Scarlet Letter</a><br/> <div class="view-animate-container"> <div ng-view class="view-animate"></div> </div> <hr /> <pre>$location.path() = {{main.$location.path()}}</pre> <pre>$route.current.templateUrl = {{main.$route.current.templateUrl}}</pre> <pre>$route.current.params = {{main.$route.current.params}}</pre> <pre>$routeParams = {{main.$routeParams}}</pre> </div> </file> <file name="book.html"> <div> controller: {{book.name}}<br /> Book Id: {{book.params.bookId}}<br /> </div> </file> <file name="chapter.html"> <div> controller: {{chapter.name}}<br /> Book Id: {{chapter.params.bookId}}<br /> Chapter Id: {{chapter.params.chapterId}} </div> </file> <file name="animations.css"> .view-animate-container { position:relative; height:100px!important; background:white; border:1px solid black; height:40px; overflow:hidden; } .view-animate { padding:10px; } .view-animate.ng-enter, .view-animate.ng-leave { transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 1.5s; display:block; width:100%; border-left:1px solid black; position:absolute; top:0; left:0; right:0; bottom:0; padding:10px; } .view-animate.ng-enter { left:100%; } .view-animate.ng-enter.ng-enter-active { left:0; } .view-animate.ng-leave.ng-leave-active { left:-100%; } </file> <file name="script.js"> angular.module('ngViewExample', ['ngRoute', 'ngAnimate']) .config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) { $routeProvider .when('/Book/:bookId', { templateUrl: 'book.html', controller: 'BookCtrl', controllerAs: 'book' }) .when('/Book/:bookId/ch/:chapterId', { templateUrl: 'chapter.html', controller: 'ChapterCtrl', controllerAs: 'chapter' }); $locationProvider.html5Mode(true); }]) .controller('MainCtrl', ['$route', '$routeParams', '$location', function($route, $routeParams, $location) { this.$route = $route; this.$location = $location; this.$routeParams = $routeParams; }]) .controller('BookCtrl', ['$routeParams', function($routeParams) { this.name = "BookCtrl"; this.params = $routeParams; }]) .controller('ChapterCtrl', ['$routeParams', function($routeParams) { this.name = "ChapterCtrl"; this.params = $routeParams; }]); </file> <file name="protractor.js" type="protractor"> it('should load and compile correct template', function() { element(by.linkText('Moby: Ch1')).click(); var content = element(by.css('[ng-view]')).getText(); expect(content).toMatch(/controller\: ChapterCtrl/); expect(content).toMatch(/Book Id\: Moby/); expect(content).toMatch(/Chapter Id\: 1/); element(by.partialLinkText('Scarlet')).click(); content = element(by.css('[ng-view]')).getText(); expect(content).toMatch(/controller\: BookCtrl/); expect(content).toMatch(/Book Id\: Scarlet/); }); </file> </example> */ /** * @ngdoc event * @name ngView#$viewContentLoaded * @eventType emit on the current ngView scope * @description * Emitted every time the ngView content is reloaded. */ ngViewFactory.$inject = ['$route', '$anchorScroll', '$animate']; function ngViewFactory($route, $anchorScroll, $animate) { return { restrict: 'ECA', terminal: true, priority: 400, transclude: 'element', link: function(scope, $element, attr, ctrl, $transclude) { var currentScope, currentElement, previousLeaveAnimation, autoScrollExp = attr.autoscroll, onloadExp = attr.onload || ''; scope.$on('$routeChangeSuccess', update); update(); function cleanupLastView() { if (previousLeaveAnimation) { $animate.cancel(previousLeaveAnimation); previousLeaveAnimation = null; } if (currentScope) { currentScope.$destroy(); currentScope = null; } if (currentElement) { previousLeaveAnimation = $animate.leave(currentElement); previousLeaveAnimation.then(function() { previousLeaveAnimation = null; }); currentElement = null; } } function update() { var locals = $route.current && $route.current.locals, template = locals && locals.$template; if (angular.isDefined(template)) { var newScope = scope.$new(); var current = $route.current; // Note: This will also link all children of ng-view that were contained in the original // html. If that content contains controllers, ... they could pollute/change the scope. // However, using ng-view on an element with additional content does not make sense... // Note: We can't remove them in the cloneAttchFn of $transclude as that // function is called before linking the content, which would apply child // directives to non existing elements. var clone = $transclude(newScope, function(clone) { $animate.enter(clone, null, currentElement || $element).then(function onNgViewEnter() { if (angular.isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) { $anchorScroll(); } }); cleanupLastView(); }); currentElement = clone; currentScope = current.scope = newScope; currentScope.$emit('$viewContentLoaded'); currentScope.$eval(onloadExp); } else { cleanupLastView(); } } } }; } // This directive is called during the $transclude call of the first `ngView` directive. // It will replace and compile the content of the element with the loaded template. // We need this directive so that the element content is already filled when // the link function of another directive on the same element as ngView // is called. ngViewFillContentFactory.$inject = ['$compile', '$controller', '$route']; function ngViewFillContentFactory($compile, $controller, $route) { return { restrict: 'ECA', priority: -400, link: function(scope, $element) { var current = $route.current, locals = current.locals; $element.html(locals.$template); var link = $compile($element.contents()); if (current.controller) { locals.$scope = scope; var controller = $controller(current.controller, locals); if (current.controllerAs) { scope[current.controllerAs] = controller; } $element.data('$ngControllerController', controller); $element.children().data('$ngControllerController', controller); } scope[current.resolveAs || '$resolve'] = locals; link(scope); } }; } })(window, window.angular);
public/vendor/angular-route/angular-route.js
0
https://github.com/grafana/grafana/commit/bf943ddba38ced67da56f0cfd847760f41d31e61
[ 0.0004762429744005203, 0.00017754228611011058, 0.0001628579484531656, 0.00016889236576389521, 0.0000390173627238255 ]
{ "id": 7, "code_window": [ "// LoggerInterface represents behaviors of a logger provider.\n", "type LoggerInterface interface {\n", "\tInit(config string) error\n", "\tWriteMsg(msg string, skip, level int) error\n", "\tDestroy()\n", "\tFlush()\n", "}\n", "\n", "type loggerType func() LoggerInterface\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tWriteMsg(msg string, skip int, level LogLevel) error\n" ], "file_path": "pkg/log/log.go", "type": "replace", "edit_start_line_idx": 113 }
<div class="editor-row"> <div class="editor-option"> <label class="small">Graphite target expression</label> <input type="text" class="span10" ng-model='annotation.target' placeholder=""></input> </div> </div> <div class="editor-row"> <div class="editor-option"> <label class="small">Graphite event tags</label> <input type="text" ng-model='annotation.tags' placeholder=""></input> </div> </div>
public/app/plugins/datasource/graphite/partials/annotations.editor.html
0
https://github.com/grafana/grafana/commit/bf943ddba38ced67da56f0cfd847760f41d31e61
[ 0.00017079051758628339, 0.00016986351693049073, 0.00016893650172278285, 0.00016986351693049073, 9.270079317502677e-7 ]
{ "id": 7, "code_window": [ "// LoggerInterface represents behaviors of a logger provider.\n", "type LoggerInterface interface {\n", "\tInit(config string) error\n", "\tWriteMsg(msg string, skip, level int) error\n", "\tDestroy()\n", "\tFlush()\n", "}\n", "\n", "type loggerType func() LoggerInterface\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tWriteMsg(msg string, skip int, level LogLevel) error\n" ], "file_path": "pkg/log/log.go", "type": "replace", "edit_start_line_idx": 113 }
slug ==== Package `slug` generate slug from unicode string, URL-friendly slugify with multiple languages support. [![GoDoc](https://godoc.org/github.com/gosimple/slug?status.png)](https://godoc.org/github.com/gosimple/slug) [![Build Status](https://drone.io/github.com/gosimple/slug/status.png)](https://drone.io/github.com/gosimple/slug/latest) [Documentation online](http://godoc.org/github.com/gosimple/slug) ## Example package main import( "github.com/gosimple/slug" "fmt" ) func main () { text := slug.Make("Hellö Wörld хелло ворлд") fmt.Println(text) // Will print hello-world-khello-vorld someText := slug.Make("影師") fmt.Println(someText) // Will print: ying-shi enText := slug.MakeLang("This & that", "en") fmt.Println(enText) // Will print 'this-and-that' deText := slug.MakeLang("Diese & Dass", "de") fmt.Println(deText) // Will print 'diese-und-dass' slug.CustomSub = map[string]string{ "water": "sand", } textSub := slug.Make("water is hot") fmt.Println(textSub) // Will print 'sand-is-hot' } ### Requests or bugs? <https://github.com/gosimple/slug/issues> ## Installation go get -u github.com/gosimple/slug ## License The source files are distributed under the [Mozilla Public License, version 2.0](http://mozilla.org/MPL/2.0/), unless otherwise noted. Please read the [FAQ](http://www.mozilla.org/MPL/2.0/FAQ.html) if you have further questions regarding the license.
Godeps/_workspace/src/github.com/gosimple/slug/README.md
0
https://github.com/grafana/grafana/commit/bf943ddba38ced67da56f0cfd847760f41d31e61
[ 0.00017443102842662483, 0.00017149955965578556, 0.0001682680449448526, 0.00017178760026581585, 0.0000023684522147959797 ]
{ "id": 8, "code_window": [ "\t}\n", "\tadapters[name] = log\n", "}\n", "\n", "type logMsg struct {\n", "\tskip, level int\n", "\tmsg string\n", "}\n", "\n", "// Logger is default logger in beego application.\n", "// it can contain several providers and log message into all providers.\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tskip int\n", "\tlevel LogLevel\n", "\tmsg string\n" ], "file_path": "pkg/log/log.go", "type": "replace", "edit_start_line_idx": 134 }
// Copyright 2014 The Gogs Authors. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. package log import ( "encoding/json" "errors" "fmt" "io/ioutil" "log" "os" "path/filepath" "strings" "sync" "time" ) // FileLogWriter implements LoggerInterface. // It writes messages by lines limit, file size limit, or time frequency. type FileLogWriter struct { *log.Logger mw *MuxWriter // The opened file Filename string `json:"filename"` Maxlines int `json:"maxlines"` maxlines_curlines int // Rotate at size Maxsize int `json:"maxsize"` maxsize_cursize int // Rotate daily Daily bool `json:"daily"` Maxdays int64 `json:"maxdays"` daily_opendate int Rotate bool `json:"rotate"` startLock sync.Mutex // Only one log can write to the file Level int `json:"level"` } // an *os.File writer with locker. type MuxWriter struct { sync.Mutex fd *os.File } // write to os.File. func (l *MuxWriter) Write(b []byte) (int, error) { l.Lock() defer l.Unlock() return l.fd.Write(b) } // set os.File in writer. func (l *MuxWriter) SetFd(fd *os.File) { if l.fd != nil { l.fd.Close() } l.fd = fd } // create a FileLogWriter returning as LoggerInterface. func NewFileWriter() LoggerInterface { w := &FileLogWriter{ Filename: "", Maxlines: 1000000, Maxsize: 1 << 28, //256 MB Daily: true, Maxdays: 7, Rotate: true, Level: TRACE, } // use MuxWriter instead direct use os.File for lock write when rotate w.mw = new(MuxWriter) // set MuxWriter as Logger's io.Writer w.Logger = log.New(w.mw, "", log.Ldate|log.Ltime) return w } // Init file logger with json config. // config like: // { // "filename":"log/gogs.log", // "maxlines":10000, // "maxsize":1<<30, // "daily":true, // "maxdays":15, // "rotate":true // } func (w *FileLogWriter) Init(config string) error { if err := json.Unmarshal([]byte(config), w); err != nil { return err } if len(w.Filename) == 0 { return errors.New("config must have filename") } return w.StartLogger() } // start file logger. create log file and set to locker-inside file writer. func (w *FileLogWriter) StartLogger() error { fd, err := w.createLogFile() if err != nil { return err } w.mw.SetFd(fd) if err = w.initFd(); err != nil { return err } return nil } func (w *FileLogWriter) docheck(size int) { w.startLock.Lock() defer w.startLock.Unlock() if w.Rotate && ((w.Maxlines > 0 && w.maxlines_curlines >= w.Maxlines) || (w.Maxsize > 0 && w.maxsize_cursize >= w.Maxsize) || (w.Daily && time.Now().Day() != w.daily_opendate)) { if err := w.DoRotate(); err != nil { fmt.Fprintf(os.Stderr, "FileLogWriter(%q): %s\n", w.Filename, err) return } } w.maxlines_curlines++ w.maxsize_cursize += size } // write logger message into file. func (w *FileLogWriter) WriteMsg(msg string, skip, level int) error { if level < w.Level { return nil } n := 24 + len(msg) // 24 stand for the length "2013/06/23 21:00:22 [T] " w.docheck(n) w.Logger.Println(msg) return nil } func (w *FileLogWriter) createLogFile() (*os.File, error) { // Open the log file return os.OpenFile(w.Filename, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0644) } func (w *FileLogWriter) initFd() error { fd := w.mw.fd finfo, err := fd.Stat() if err != nil { return fmt.Errorf("get stat: %s\n", err) } w.maxsize_cursize = int(finfo.Size()) w.daily_opendate = time.Now().Day() if finfo.Size() > 0 { content, err := ioutil.ReadFile(w.Filename) if err != nil { return err } w.maxlines_curlines = len(strings.Split(string(content), "\n")) } else { w.maxlines_curlines = 0 } return nil } // DoRotate means it need to write file in new file. // new file name like xx.log.2013-01-01.2 func (w *FileLogWriter) DoRotate() error { _, err := os.Lstat(w.Filename) if err == nil { // file exists // Find the next available number num := 1 fname := "" for ; err == nil && num <= 999; num++ { fname = w.Filename + fmt.Sprintf(".%s.%03d", time.Now().Format("2006-01-02"), num) _, err = os.Lstat(fname) } // return error if the last file checked still existed if err == nil { return fmt.Errorf("rotate: cannot find free log number to rename %s\n", w.Filename) } // block Logger's io.Writer w.mw.Lock() defer w.mw.Unlock() fd := w.mw.fd fd.Close() // close fd before rename // Rename the file to its newfound home if err = os.Rename(w.Filename, fname); err != nil { return fmt.Errorf("Rotate: %s\n", err) } // re-start logger if err = w.StartLogger(); err != nil { return fmt.Errorf("Rotate StartLogger: %s\n", err) } go w.deleteOldLog() } return nil } func (w *FileLogWriter) deleteOldLog() { dir := filepath.Dir(w.Filename) filepath.Walk(dir, func(path string, info os.FileInfo, err error) (returnErr error) { defer func() { if r := recover(); r != nil { returnErr = fmt.Errorf("Unable to delete old log '%s', error: %+v", path, r) } }() if !info.IsDir() && info.ModTime().Unix() < (time.Now().Unix()-60*60*24*w.Maxdays) { if strings.HasPrefix(filepath.Base(path), filepath.Base(w.Filename)) { os.Remove(path) } } return returnErr }) } // destroy file logger, close file writer. func (w *FileLogWriter) Destroy() { w.mw.fd.Close() } // flush file logger. // there are no buffering messages in file logger in memory. // flush file means sync file from disk. func (w *FileLogWriter) Flush() { w.mw.fd.Sync() } func init() { Register("file", NewFileWriter) }
pkg/log/file.go
1
https://github.com/grafana/grafana/commit/bf943ddba38ced67da56f0cfd847760f41d31e61
[ 0.21439716219902039, 0.016223113983869553, 0.0001670153287705034, 0.000615347467828542, 0.04593818262219429 ]
{ "id": 8, "code_window": [ "\t}\n", "\tadapters[name] = log\n", "}\n", "\n", "type logMsg struct {\n", "\tskip, level int\n", "\tmsg string\n", "}\n", "\n", "// Logger is default logger in beego application.\n", "// it can contain several providers and log message into all providers.\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tskip int\n", "\tlevel LogLevel\n", "\tmsg string\n" ], "file_path": "pkg/log/log.go", "type": "replace", "edit_start_line_idx": 134 }
{bar: bar, baz: baz}
Godeps/_workspace/src/github.com/jmespath/go-jmespath/fuzz/corpus/expr-434
0
https://github.com/grafana/grafana/commit/bf943ddba38ced67da56f0cfd847760f41d31e61
[ 0.00016861945914570242, 0.00016861945914570242, 0.00016861945914570242, 0.00016861945914570242, 0 ]