hunk
dict
file
stringlengths
0
11.8M
file_path
stringlengths
2
234
label
int64
0
1
commit_url
stringlengths
74
103
dependency_score
listlengths
5
5
{ "id": 1, "code_window": [ " function getSemanticDiagnostics(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] {\n", " return getDiagnosticsHelper(sourceFile, getSemanticDiagnosticsForFile, cancellationToken);\n", " }\n", "\n", " function getDeclarationDiagnostics(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] {\n", " return getDiagnosticsHelper(sourceFile, getDeclarationDiagnosticsForFile, cancellationToken);\n", " }\n", "\n", " function getSyntacticDiagnosticsForFile(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " const options = program.getCompilerOptions();\n", " if (!sourceFile || options.out || options.outFile) {\n", " return getDeclarationDiagnosticsWorker(sourceFile, cancellationToken);\n", " }\n", " else {\n", " return getDiagnosticsHelper(sourceFile, getDeclarationDiagnosticsForFile, cancellationToken);\n", " }\n" ], "file_path": "src/compiler/program.ts", "type": "replace", "edit_start_line_idx": 1000 }
/// <reference path='fourslash.ts'/> //// class C extends D { //// [|prop1|]: string; //// } //// //// class D extends C { //// prop1: string; //// } //// //// var c: C; //// c.[|prop1|]; const ranges = test.ranges(); verify.assertHasRanges(ranges); for (const range of ranges) { goTo.position(range.start); verify.renameLocations(/*findInStrings*/ false, /*findInComments*/ false); }
tests/cases/fourslash/renameInheritedProperties7.ts
0
https://github.com/microsoft/TypeScript/commit/8e77f40ace2155b16bb0ac5a417467edbec86843
[ 0.0001741896994644776, 0.00017281985492445529, 0.0001714500249363482, 0.00017281985492445529, 0.0000013698372640646994 ]
{ "id": 1, "code_window": [ " function getSemanticDiagnostics(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] {\n", " return getDiagnosticsHelper(sourceFile, getSemanticDiagnosticsForFile, cancellationToken);\n", " }\n", "\n", " function getDeclarationDiagnostics(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] {\n", " return getDiagnosticsHelper(sourceFile, getDeclarationDiagnosticsForFile, cancellationToken);\n", " }\n", "\n", " function getSyntacticDiagnosticsForFile(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " const options = program.getCompilerOptions();\n", " if (!sourceFile || options.out || options.outFile) {\n", " return getDeclarationDiagnosticsWorker(sourceFile, cancellationToken);\n", " }\n", " else {\n", " return getDiagnosticsHelper(sourceFile, getDeclarationDiagnosticsForFile, cancellationToken);\n", " }\n" ], "file_path": "src/compiler/program.ts", "type": "replace", "edit_start_line_idx": 1000 }
tests/cases/conformance/es6/memberFunctionDeclarations/MemberFunctionDeclaration7_es6.ts(2,4): error TS1220: Generators are only available when targeting ECMAScript 6 or higher. ==== tests/cases/conformance/es6/memberFunctionDeclarations/MemberFunctionDeclaration7_es6.ts (1 errors) ==== class C { *foo<T>() { } ~ !!! error TS1220: Generators are only available when targeting ECMAScript 6 or higher. }
tests/baselines/reference/MemberFunctionDeclaration7_es6.errors.txt
0
https://github.com/microsoft/TypeScript/commit/8e77f40ace2155b16bb0ac5a417467edbec86843
[ 0.0001732139935484156, 0.0001732139935484156, 0.0001732139935484156, 0.0001732139935484156, 0 ]
{ "id": 2, "code_window": [ " });\n", " }\n", "\n", " function getDeclarationDiagnosticsForFile(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] {\n", " return runWithCancellationToken(() => {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ " function getDeclarationDiagnosticsWorker(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] {\n" ], "file_path": "src/compiler/program.ts", "type": "replace", "edit_start_line_idx": 1214 }
/// <reference path="sys.ts" /> /// <reference path="emitter.ts" /> /// <reference path="core.ts" /> namespace ts { /* @internal */ export let programTime = 0; /* @internal */ export let emitTime = 0; /* @internal */ export let ioReadTime = 0; /* @internal */ export let ioWriteTime = 0; /** The version of the TypeScript compiler release */ const emptyArray: any[] = []; export const version = "1.9.0"; export function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean): string { let fileName = "tsconfig.json"; while (true) { if (fileExists(fileName)) { return fileName; } const parentPath = getDirectoryPath(searchPath); if (parentPath === searchPath) { break; } searchPath = parentPath; fileName = "../" + fileName; } return undefined; } export function resolveTripleslashReference(moduleName: string, containingFile: string): string { const basePath = getDirectoryPath(containingFile); const referencedFileName = isRootedDiskPath(moduleName) ? moduleName : combinePaths(basePath, moduleName); return normalizePath(referencedFileName); } function trace(host: ModuleResolutionHost, message: DiagnosticMessage, ...args: any[]): void; function trace(host: ModuleResolutionHost, message: DiagnosticMessage): void { host.trace(formatMessage.apply(undefined, arguments)); } function isTraceEnabled(compilerOptions: CompilerOptions, host: ModuleResolutionHost): boolean { return compilerOptions.traceModuleResolution && host.trace !== undefined; } function startsWith(str: string, prefix: string): boolean { return str.lastIndexOf(prefix, 0) === 0; } function endsWith(str: string, suffix: string): boolean { const expectedPos = str.length - suffix.length; return str.indexOf(suffix, expectedPos) === expectedPos; } function hasZeroOrOneAsteriskCharacter(str: string): boolean { let seenAsterisk = false; for (let i = 0; i < str.length; i++) { if (str.charCodeAt(i) === CharacterCodes.asterisk) { if (!seenAsterisk) { seenAsterisk = true; } else { // have already seen asterisk return false; } } } return true; } function createResolvedModule(resolvedFileName: string, isExternalLibraryImport: boolean, failedLookupLocations: string[]): ResolvedModuleWithFailedLookupLocations { return { resolvedModule: resolvedFileName ? { resolvedFileName, isExternalLibraryImport } : undefined, failedLookupLocations }; } function moduleHasNonRelativeName(moduleName: string): boolean { if (isRootedDiskPath(moduleName)) { return false; } const i = moduleName.lastIndexOf("./", 1); const startsWithDotSlashOrDotDotSlash = i === 0 || (i === 1 && moduleName.charCodeAt(0) === CharacterCodes.dot); return !startsWithDotSlashOrDotDotSlash; } interface ModuleResolutionState { host: ModuleResolutionHost; compilerOptions: CompilerOptions; traceEnabled: boolean; // skip .tsx files if jsx is not enabled skipTsx: boolean; } export function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations { const traceEnabled = isTraceEnabled(compilerOptions, host); if (traceEnabled) { trace(host, Diagnostics.Resolving_module_0_from_1, moduleName, containingFile); } let moduleResolution = compilerOptions.moduleResolution; if (moduleResolution === undefined) { moduleResolution = getEmitModuleKind(compilerOptions) === ModuleKind.CommonJS ? ModuleResolutionKind.NodeJs : ModuleResolutionKind.Classic; if (traceEnabled) { trace(host, Diagnostics.Module_resolution_kind_is_not_specified_using_0, ModuleResolutionKind[moduleResolution]); } } else { if (traceEnabled) { trace(host, Diagnostics.Explicitly_specified_module_resolution_kind_Colon_0, ModuleResolutionKind[moduleResolution]); } } let result: ResolvedModuleWithFailedLookupLocations; switch (moduleResolution) { case ModuleResolutionKind.NodeJs: result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host); break; case ModuleResolutionKind.Classic: result = classicNameResolver(moduleName, containingFile, compilerOptions, host); break; } if (traceEnabled) { if (result.resolvedModule) { trace(host, Diagnostics.Module_name_0_was_successfully_resolved_to_1, moduleName, result.resolvedModule.resolvedFileName); } else { trace(host, Diagnostics.Module_name_0_was_not_resolved, moduleName); } } return result; } /* * Every module resolution kind can has its specific understanding how to load module from a specific path on disk * I.e. for path '/a/b/c': * - Node loader will first to try to check if '/a/b/c' points to a file with some supported extension and if this fails * it will try to load module from directory: directory '/a/b/c' should exist and it should have either 'package.json' with * 'typings' entry or file 'index' with some supported extension * - Classic loader will only try to interpret '/a/b/c' as file. */ type ResolutionKindSpecificLoader = (candidate: string, extensions: string[], failedLookupLocations: string[], onlyRecordFailures: boolean, state: ModuleResolutionState) => string; /** * Any module resolution kind can be augmented with optional settings: 'baseUrl', 'paths' and 'rootDirs' - they are used to * mitigate differences between design time structure of the project and its runtime counterpart so the same import name * can be resolved successfully by TypeScript compiler and runtime module loader. * If these settings are set then loading procedure will try to use them to resolve module name and it can of failure it will * fallback to standard resolution routine. * * - baseUrl - this setting controls how non-relative module names are resolved. If this setting is specified then non-relative * names will be resolved relative to baseUrl: i.e. if baseUrl is '/a/b' then candidate location to resolve module name 'c/d' will * be '/a/b/c/d' * - paths - this setting can only be used when baseUrl is specified. allows to tune how non-relative module names * will be resolved based on the content of the module name. * Structure of 'paths' compiler options * 'paths': { * pattern-1: [...substitutions], * pattern-2: [...substitutions], * ... * pattern-n: [...substitutions] * } * Pattern here is a string that can contain zero or one '*' character. During module resolution module name will be matched against * all patterns in the list. Matching for patterns that don't contain '*' means that module name must be equal to pattern respecting the case. * If pattern contains '*' then to match pattern "<prefix>*<suffix>" module name must start with the <prefix> and end with <suffix>. * <MatchedStar> denotes part of the module name between <prefix> and <suffix>. * If module name can be matches with multiple patterns then pattern with the longest prefix will be picked. * After selecting pattern we'll use list of substitutions to get candidate locations of the module and the try to load module * from the candidate location. * Substitution is a string that can contain zero or one '*'. To get candidate location from substitution we'll pick every * substitution in the list and replace '*' with <MatchedStar> string. If candidate location is not rooted it * will be converted to absolute using baseUrl. * For example: * baseUrl: /a/b/c * "paths": { * // match all module names * "*": [ * "*", // use matched name as is, * // <matched name> will be looked as /a/b/c/<matched name> * * "folder1/*" // substitution will convert matched name to 'folder1/<matched name>', * // since it is not rooted then final candidate location will be /a/b/c/folder1/<matched name> * ], * // match module names that start with 'components/' * "components/*": [ "/root/components/*" ] // substitution will convert /components/folder1/<matched name> to '/root/components/folder1/<matched name>', * // it is rooted so it will be final candidate location * } * * 'rootDirs' allows the project to be spreaded across multiple locations and resolve modules with relative names as if * they were in the same location. For example lets say there are two files * '/local/src/content/file1.ts' * '/shared/components/contracts/src/content/protocols/file2.ts' * After bundling content of '/shared/components/contracts/src' will be merged with '/local/src' so * if file1 has the following import 'import {x} from "./protocols/file2"' it will be resolved successfully in runtime. * 'rootDirs' provides the way to tell compiler that in order to get the whole project it should behave as if content of all * root dirs were merged together. * I.e. for the example above 'rootDirs' will have two entries: [ '/local/src', '/shared/components/contracts/src' ]. * Compiler will first convert './protocols/file2' into absolute path relative to the location of containing file: * '/local/src/content/protocols/file2' and try to load it - failure. * Then it will search 'rootDirs' looking for a longest matching prefix of this absolute path and if such prefix is found - absolute path will * be converted to a path relative to found rootDir entry './content/protocols/file2' (*). As a last step compiler will check all remaining * entries in 'rootDirs', use them to build absolute path out of (*) and try to resolve module from this location. */ function tryLoadModuleUsingOptionalResolutionSettings(moduleName: string, containingDirectory: string, loader: ResolutionKindSpecificLoader, failedLookupLocations: string[], supportedExtensions: string[], state: ModuleResolutionState): string { if (moduleHasNonRelativeName(moduleName)) { return tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state); } else { return tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state); } } function tryLoadModuleUsingRootDirs(moduleName: string, containingDirectory: string, loader: ResolutionKindSpecificLoader, failedLookupLocations: string[], supportedExtensions: string[], state: ModuleResolutionState): string { if (!state.compilerOptions.rootDirs) { return undefined; } if (state.traceEnabled) { trace(state.host, Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName); } const candidate = normalizePath(combinePaths(containingDirectory, moduleName)); let matchedRootDir: string; let matchedNormalizedPrefix: string; for (const rootDir of state.compilerOptions.rootDirs) { // rootDirs are expected to be absolute // in case of tsconfig.json this will happen automatically - compiler will expand relative names // using location of tsconfig.json as base location let normalizedRoot = normalizePath(rootDir); if (!endsWith(normalizedRoot, directorySeparator)) { normalizedRoot += directorySeparator; } const isLongestMatchingPrefix = startsWith(candidate, normalizedRoot) && (matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length); if (state.traceEnabled) { trace(state.host, Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix); } if (isLongestMatchingPrefix) { matchedNormalizedPrefix = normalizedRoot; matchedRootDir = rootDir; } } if (matchedNormalizedPrefix) { if (state.traceEnabled) { trace(state.host, Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix); } const suffix = candidate.substr(matchedNormalizedPrefix.length); // first - try to load from a initial location if (state.traceEnabled) { trace(state.host, Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); } const resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state); if (resolvedFileName) { return resolvedFileName; } if (state.traceEnabled) { trace(state.host, Diagnostics.Trying_other_entries_in_rootDirs); } // then try to resolve using remaining entries in rootDirs for (const rootDir of state.compilerOptions.rootDirs) { if (rootDir === matchedRootDir) { // skip the initially matched entry continue; } const candidate = combinePaths(normalizePath(rootDir), suffix); if (state.traceEnabled) { trace(state.host, Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate); } const baseDirectory = getDirectoryPath(candidate); const resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state); if (resolvedFileName) { return resolvedFileName; } } if (state.traceEnabled) { trace(state.host, Diagnostics.Module_resolution_using_rootDirs_has_failed); } } return undefined; } function tryLoadModuleUsingBaseUrl(moduleName: string, loader: ResolutionKindSpecificLoader, failedLookupLocations: string[], supportedExtensions: string[], state: ModuleResolutionState): string { if (!state.compilerOptions.baseUrl) { return undefined; } if (state.traceEnabled) { trace(state.host, Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName); } let longestMatchPrefixLength = -1; let matchedPattern: string; let matchedStar: string; if (state.compilerOptions.paths) { if (state.traceEnabled) { trace(state.host, Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); } for (const key in state.compilerOptions.paths) { const pattern: string = key; const indexOfStar = pattern.indexOf("*"); if (indexOfStar !== -1) { const prefix = pattern.substr(0, indexOfStar); const suffix = pattern.substr(indexOfStar + 1); if (moduleName.length >= prefix.length + suffix.length && startsWith(moduleName, prefix) && endsWith(moduleName, suffix)) { // use length of prefix as betterness criteria if (prefix.length > longestMatchPrefixLength) { longestMatchPrefixLength = prefix.length; matchedPattern = pattern; matchedStar = moduleName.substr(prefix.length, moduleName.length - suffix.length); } } } else if (pattern === moduleName) { // pattern was matched as is - no need to search further matchedPattern = pattern; matchedStar = undefined; break; } } } if (matchedPattern) { if (state.traceEnabled) { trace(state.host, Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPattern); } for (const subst of state.compilerOptions.paths[matchedPattern]) { const path = matchedStar ? subst.replace("\*", matchedStar) : subst; const candidate = normalizePath(combinePaths(state.compilerOptions.baseUrl, path)); if (state.traceEnabled) { trace(state.host, Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); } const resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(getDirectoryPath(candidate), state.host), state); if (resolvedFileName) { return resolvedFileName; } } return undefined; } else { const candidate = normalizePath(combinePaths(state.compilerOptions.baseUrl, moduleName)); if (state.traceEnabled) { trace(state.host, Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate); } return loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(getDirectoryPath(candidate), state.host), state); } } export function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations { const containingDirectory = getDirectoryPath(containingFile); const supportedExtensions = getSupportedExtensions(compilerOptions); const traceEnabled = isTraceEnabled(compilerOptions, host); const failedLookupLocations: string[] = []; const state = {compilerOptions, host, traceEnabled, skipTsx: false}; let resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, nodeLoadModuleByRelativeName, failedLookupLocations, supportedExtensions, state); if (resolvedFileName) { return createResolvedModule(resolvedFileName, /*isExternalLibraryImport*/false, failedLookupLocations); } let isExternalLibraryImport = false; if (moduleHasNonRelativeName(moduleName)) { if (traceEnabled) { trace(host, Diagnostics.Loading_module_0_from_node_modules_folder, moduleName); } resolvedFileName = loadModuleFromNodeModules(moduleName, containingDirectory, failedLookupLocations, state); isExternalLibraryImport = resolvedFileName !== undefined; } else { const candidate = normalizePath(combinePaths(containingDirectory, moduleName)); resolvedFileName = nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, /*onlyRecordFailures*/ false, state); } return createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations); } function nodeLoadModuleByRelativeName(candidate: string, supportedExtensions: string[], failedLookupLocations: string[], onlyRecordFailures: boolean, state: ModuleResolutionState): string { if (state.traceEnabled) { trace(state.host, Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0, candidate); } const resolvedFileName = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state); return resolvedFileName || loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, onlyRecordFailures, state); } /* @internal */ export function directoryProbablyExists(directoryName: string, host: { directoryExists?: (directoryName: string) => boolean } ): boolean { // if host does not support 'directoryExists' assume that directory will exist return !host.directoryExists || host.directoryExists(directoryName); } /** * @param {boolean} onlyRecordFailures - if true then function won't try to actually load files but instead record all attempts as failures. This flag is necessary * in cases when we know upfront that all load attempts will fail (because containing folder does not exists) however we still need to record all failed lookup locations. */ function loadModuleFromFile(candidate: string, extensions: string[], failedLookupLocation: string[], onlyRecordFailures: boolean, state: ModuleResolutionState): string { return forEach(extensions, tryLoad); function tryLoad(ext: string): string { if (ext === ".tsx" && state.skipTsx) { return undefined; } const fileName = fileExtensionIs(candidate, ext) ? candidate : candidate + ext; if (!onlyRecordFailures && state.host.fileExists(fileName)) { if (state.traceEnabled) { trace(state.host, Diagnostics.File_0_exist_use_it_as_a_module_resolution_result, fileName); } return fileName; } else { if (state.traceEnabled) { trace(state.host, Diagnostics.File_0_does_not_exist, fileName); } failedLookupLocation.push(fileName); return undefined; } } } function loadNodeModuleFromDirectory(extensions: string[], candidate: string, failedLookupLocation: string[], onlyRecordFailures: boolean, state: ModuleResolutionState): string { const packageJsonPath = combinePaths(candidate, "package.json"); const directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); if (directoryExists && state.host.fileExists(packageJsonPath)) { if (state.traceEnabled) { trace(state.host, Diagnostics.Found_package_json_at_0, packageJsonPath); } let jsonContent: { typings?: string }; try { const jsonText = state.host.readFile(packageJsonPath); jsonContent = jsonText ? <{ typings?: string }>JSON.parse(jsonText) : { typings: undefined }; } catch (e) { // gracefully handle if readFile fails or returns not JSON jsonContent = { typings: undefined }; } if (jsonContent.typings) { if (typeof jsonContent.typings === "string") { const typingsFile = normalizePath(combinePaths(candidate, jsonContent.typings)); if (state.traceEnabled) { trace(state.host, Diagnostics.package_json_has_typings_field_0_that_references_1, jsonContent.typings, typingsFile); } const result = loadModuleFromFile(typingsFile, extensions, failedLookupLocation, !directoryProbablyExists(getDirectoryPath(typingsFile), state.host), state); if (result) { return result; } } else if (state.traceEnabled) { trace(state.host, Diagnostics.Expected_type_of_typings_field_in_package_json_to_be_string_got_0, typeof jsonContent.typings); } } else { if (state.traceEnabled) { trace(state.host, Diagnostics.package_json_does_not_have_typings_field); } } } else { if (state.traceEnabled) { trace(state.host, Diagnostics.File_0_does_not_exist, packageJsonPath); } // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results failedLookupLocation.push(packageJsonPath); } return loadModuleFromFile(combinePaths(candidate, "index"), extensions, failedLookupLocation, !directoryExists, state); } function loadModuleFromNodeModules(moduleName: string, directory: string, failedLookupLocations: string[], state: ModuleResolutionState): string { directory = normalizeSlashes(directory); while (true) { const baseName = getBaseFileName(directory); if (baseName !== "node_modules") { const nodeModulesFolder = combinePaths(directory, "node_modules"); const nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); const candidate = normalizePath(combinePaths(nodeModulesFolder, moduleName)); // Load only typescript files irrespective of allowJs option if loading from node modules let result = loadModuleFromFile(candidate, supportedTypeScriptExtensions, failedLookupLocations, !nodeModulesFolderExists, state); if (result) { return result; } result = loadNodeModuleFromDirectory(supportedTypeScriptExtensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state); if (result) { return result; } } const parentPath = getDirectoryPath(directory); if (parentPath === directory) { break; } directory = parentPath; } return undefined; } export function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations { const traceEnabled = isTraceEnabled(compilerOptions, host); const state = { compilerOptions, host, traceEnabled, skipTsx: !compilerOptions.jsx }; const failedLookupLocations: string[] = []; const supportedExtensions = getSupportedExtensions(compilerOptions); let containingDirectory = getDirectoryPath(containingFile); const resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loadModuleFromFile, failedLookupLocations, supportedExtensions, state); if (resolvedFileName) { return createResolvedModule(resolvedFileName, /*isExternalLibraryImport*/false, failedLookupLocations); } let referencedSourceFile: string; if (moduleHasNonRelativeName(moduleName)) { while (true) { const searchName = normalizePath(combinePaths(containingDirectory, moduleName)); referencedSourceFile = loadModuleFromFile(searchName, supportedExtensions, failedLookupLocations, /*onlyRecordFailures*/ false, state); if (referencedSourceFile) { break; } const parentPath = getDirectoryPath(containingDirectory); if (parentPath === containingDirectory) { break; } containingDirectory = parentPath; } } else { const candidate = normalizePath(combinePaths(containingDirectory, moduleName)); referencedSourceFile = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, /*onlyRecordFailures*/ false, state); } return referencedSourceFile ? { resolvedModule: { resolvedFileName: referencedSourceFile }, failedLookupLocations } : { resolvedModule: undefined, failedLookupLocations }; } /* @internal */ export const defaultInitCompilerOptions: CompilerOptions = { module: ModuleKind.CommonJS, target: ScriptTarget.ES5, noImplicitAny: false, sourceMap: false, }; export function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost { const existingDirectories: Map<boolean> = {}; function getCanonicalFileName(fileName: string): string { // if underlying system can distinguish between two files whose names differs only in cases then file name already in canonical form. // otherwise use toLowerCase as a canonical form. return sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); } // returned by CScript sys environment const unsupportedFileEncodingErrorCode = -2147024809; function getSourceFile(fileName: string, languageVersion: ScriptTarget, onError?: (message: string) => void): SourceFile { let text: string; try { const start = new Date().getTime(); text = sys.readFile(fileName, options.charset); ioReadTime += new Date().getTime() - start; } catch (e) { if (onError) { onError(e.number === unsupportedFileEncodingErrorCode ? createCompilerDiagnostic(Diagnostics.Unsupported_file_encoding).messageText : e.message); } text = ""; } return text !== undefined ? createSourceFile(fileName, text, languageVersion, setParentNodes) : undefined; } function directoryExists(directoryPath: string): boolean { if (hasProperty(existingDirectories, directoryPath)) { return true; } if (sys.directoryExists(directoryPath)) { existingDirectories[directoryPath] = true; return true; } return false; } function ensureDirectoriesExist(directoryPath: string) { if (directoryPath.length > getRootLength(directoryPath) && !directoryExists(directoryPath)) { const parentDirectory = getDirectoryPath(directoryPath); ensureDirectoriesExist(parentDirectory); sys.createDirectory(directoryPath); } } function writeFile(fileName: string, data: string, writeByteOrderMark: boolean, onError?: (message: string) => void) { try { const start = new Date().getTime(); ensureDirectoriesExist(getDirectoryPath(normalizePath(fileName))); sys.writeFile(fileName, data, writeByteOrderMark); ioWriteTime += new Date().getTime() - start; } catch (e) { if (onError) { onError(e.message); } } } const newLine = getNewLineCharacter(options); return { getSourceFile, getDefaultLibFileName: options => combinePaths(getDirectoryPath(normalizePath(sys.getExecutingFilePath())), getDefaultLibFileName(options)), writeFile, getCurrentDirectory: memoize(() => sys.getCurrentDirectory()), useCaseSensitiveFileNames: () => sys.useCaseSensitiveFileNames, getCanonicalFileName, getNewLine: () => newLine, fileExists: fileName => sys.fileExists(fileName), readFile: fileName => sys.readFile(fileName), trace: (s: string) => sys.write(s + newLine), directoryExists: directoryName => sys.directoryExists(directoryName) }; } export function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[] { let diagnostics = program.getOptionsDiagnostics(cancellationToken).concat( program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); if (program.getCompilerOptions().declaration) { diagnostics = diagnostics.concat(program.getDeclarationDiagnostics(sourceFile, cancellationToken)); } return sortAndDeduplicateDiagnostics(diagnostics); } export function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string { if (typeof messageText === "string") { return messageText; } else { let diagnosticChain = messageText; let result = ""; let indent = 0; while (diagnosticChain) { if (indent) { result += newLine; for (let i = 0; i < indent; i++) { result += " "; } } result += diagnosticChain.messageText; indent++; diagnosticChain = diagnosticChain.next; } return result; } } export function createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost, oldProgram?: Program): Program { let program: Program; let files: SourceFile[] = []; let fileProcessingDiagnostics = createDiagnosticCollection(); const programDiagnostics = createDiagnosticCollection(); let commonSourceDirectory: string; let diagnosticsProducingTypeChecker: TypeChecker; let noDiagnosticsTypeChecker: TypeChecker; let classifiableNames: Map<string>; let skipDefaultLib = options.noLib; const supportedExtensions = getSupportedExtensions(options); const start = new Date().getTime(); host = host || createCompilerHost(options); // Map storing if there is emit blocking diagnostics for given input const hasEmitBlockingDiagnostics = createFileMap<boolean>(getCanonicalFileName); const currentDirectory = host.getCurrentDirectory(); const resolveModuleNamesWorker = host.resolveModuleNames ? ((moduleNames: string[], containingFile: string) => host.resolveModuleNames(moduleNames, containingFile)) : ((moduleNames: string[], containingFile: string) => { const resolvedModuleNames: ResolvedModule[] = []; // resolveModuleName does not store any results between calls. // lookup is a local cache to avoid resolving the same module name several times const lookup: Map<ResolvedModule> = {}; for (const moduleName of moduleNames) { let resolvedName: ResolvedModule; if (hasProperty(lookup, moduleName)) { resolvedName = lookup[moduleName]; } else { resolvedName = resolveModuleName(moduleName, containingFile, options, host).resolvedModule; lookup[moduleName] = resolvedName; } resolvedModuleNames.push(resolvedName); } return resolvedModuleNames; }); const filesByName = createFileMap<SourceFile>(); // stores 'filename -> file association' ignoring case // used to track cases when two file names differ only in casing const filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? createFileMap<SourceFile>(fileName => fileName.toLowerCase()) : undefined; if (oldProgram) { // check properties that can affect structure of the program or module resolution strategy // if any of these properties has changed - structure cannot be reused const oldOptions = oldProgram.getCompilerOptions(); if ((oldOptions.module !== options.module) || (oldOptions.noResolve !== options.noResolve) || (oldOptions.target !== options.target) || (oldOptions.noLib !== options.noLib) || (oldOptions.jsx !== options.jsx) || (oldOptions.allowJs !== options.allowJs)) { oldProgram = undefined; } } if (!tryReuseStructureFromOldProgram()) { forEach(rootNames, name => processRootFile(name, /*isDefaultLib*/ false)); // Do not process the default library if: // - The '--noLib' flag is used. // - A 'no-default-lib' reference comment is encountered in // processing the root files. if (!skipDefaultLib) { processRootFile(host.getDefaultLibFileName(options), /*isDefaultLib*/ true); } } // unconditionally set oldProgram to undefined to prevent it from being captured in closure oldProgram = undefined; program = { getRootFileNames: () => rootNames, getSourceFile, getSourceFiles: () => files, getCompilerOptions: () => options, getSyntacticDiagnostics, getOptionsDiagnostics, getGlobalDiagnostics, getSemanticDiagnostics, getDeclarationDiagnostics, getTypeChecker, getClassifiableNames, getDiagnosticsProducingTypeChecker, getCommonSourceDirectory, emit, getCurrentDirectory: () => currentDirectory, getNodeCount: () => getDiagnosticsProducingTypeChecker().getNodeCount(), getIdentifierCount: () => getDiagnosticsProducingTypeChecker().getIdentifierCount(), getSymbolCount: () => getDiagnosticsProducingTypeChecker().getSymbolCount(), getTypeCount: () => getDiagnosticsProducingTypeChecker().getTypeCount(), getFileProcessingDiagnostics: () => fileProcessingDiagnostics }; verifyCompilerOptions(); programTime += new Date().getTime() - start; return program; function getCommonSourceDirectory() { if (typeof commonSourceDirectory === "undefined") { if (options.rootDir && checkSourceFilesBelongToPath(files, options.rootDir)) { // If a rootDir is specified and is valid use it as the commonSourceDirectory commonSourceDirectory = getNormalizedAbsolutePath(options.rootDir, currentDirectory); } else { commonSourceDirectory = computeCommonSourceDirectory(files); } if (commonSourceDirectory && commonSourceDirectory[commonSourceDirectory.length - 1] !== directorySeparator) { // Make sure directory path ends with directory separator so this string can directly // used to replace with "" to get the relative path of the source file and the relative path doesn't // start with / making it rooted path commonSourceDirectory += directorySeparator; } } return commonSourceDirectory; } function getClassifiableNames() { if (!classifiableNames) { // Initialize a checker so that all our files are bound. getTypeChecker(); classifiableNames = {}; for (const sourceFile of files) { copyMap(sourceFile.classifiableNames, classifiableNames); } } return classifiableNames; } function tryReuseStructureFromOldProgram(): boolean { if (!oldProgram) { return false; } Debug.assert(!oldProgram.structureIsReused); // there is an old program, check if we can reuse its structure const oldRootNames = oldProgram.getRootFileNames(); if (!arrayIsEqualTo(oldRootNames, rootNames)) { return false; } // check if program source files has changed in the way that can affect structure of the program const newSourceFiles: SourceFile[] = []; const filePaths: Path[] = []; const modifiedSourceFiles: SourceFile[] = []; for (const oldSourceFile of oldProgram.getSourceFiles()) { let newSourceFile = host.getSourceFile(oldSourceFile.fileName, options.target); if (!newSourceFile) { return false; } newSourceFile.path = oldSourceFile.path; filePaths.push(newSourceFile.path); if (oldSourceFile !== newSourceFile) { if (oldSourceFile.hasNoDefaultLib !== newSourceFile.hasNoDefaultLib) { // value of no-default-lib has changed // this will affect if default library is injected into the list of files return false; } // check tripleslash references if (!arrayIsEqualTo(oldSourceFile.referencedFiles, newSourceFile.referencedFiles, fileReferenceIsEqualTo)) { // tripleslash references has changed return false; } // check imports and module augmentations collectExternalModuleReferences(newSourceFile); if (!arrayIsEqualTo(oldSourceFile.imports, newSourceFile.imports, moduleNameIsEqualTo)) { // imports has changed return false; } if (!arrayIsEqualTo(oldSourceFile.moduleAugmentations, newSourceFile.moduleAugmentations, moduleNameIsEqualTo)) { // moduleAugmentations has changed return false; } if (resolveModuleNamesWorker) { const moduleNames = map(concatenate(newSourceFile.imports, newSourceFile.moduleAugmentations), getTextOfLiteral); const resolutions = resolveModuleNamesWorker(moduleNames, getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory)); // ensure that module resolution results are still correct for (let i = 0; i < moduleNames.length; i++) { const newResolution = resolutions[i]; const oldResolution = getResolvedModule(oldSourceFile, moduleNames[i]); const resolutionChanged = oldResolution ? !newResolution || oldResolution.resolvedFileName !== newResolution.resolvedFileName || !!oldResolution.isExternalLibraryImport !== !!newResolution.isExternalLibraryImport : newResolution; if (resolutionChanged) { return false; } } } // pass the cache of module resolutions from the old source file newSourceFile.resolvedModules = oldSourceFile.resolvedModules; modifiedSourceFiles.push(newSourceFile); } else { // file has no changes - use it as is newSourceFile = oldSourceFile; } // if file has passed all checks it should be safe to reuse it newSourceFiles.push(newSourceFile); } // update fileName -> file mapping for (let i = 0, len = newSourceFiles.length; i < len; i++) { filesByName.set(filePaths[i], newSourceFiles[i]); } files = newSourceFiles; fileProcessingDiagnostics = oldProgram.getFileProcessingDiagnostics(); for (const modifiedFile of modifiedSourceFiles) { fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile); } oldProgram.structureIsReused = true; return true; } function getEmitHost(writeFileCallback?: WriteFileCallback): EmitHost { return { getCanonicalFileName, getCommonSourceDirectory: program.getCommonSourceDirectory, getCompilerOptions: program.getCompilerOptions, getCurrentDirectory: () => currentDirectory, getNewLine: () => host.getNewLine(), getSourceFile: program.getSourceFile, getSourceFiles: program.getSourceFiles, writeFile: writeFileCallback || ( (fileName, data, writeByteOrderMark, onError) => host.writeFile(fileName, data, writeByteOrderMark, onError)), isEmitBlocked, }; } function getDiagnosticsProducingTypeChecker() { return diagnosticsProducingTypeChecker || (diagnosticsProducingTypeChecker = createTypeChecker(program, /*produceDiagnostics:*/ true)); } function getTypeChecker() { return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = createTypeChecker(program, /*produceDiagnostics:*/ false)); } function emit(sourceFile?: SourceFile, writeFileCallback?: WriteFileCallback, cancellationToken?: CancellationToken): EmitResult { return runWithCancellationToken(() => emitWorker(this, sourceFile, writeFileCallback, cancellationToken)); } function isEmitBlocked(emitFileName: string): boolean { return hasEmitBlockingDiagnostics.contains(toPath(emitFileName, currentDirectory, getCanonicalFileName)); } function emitWorker(program: Program, sourceFile: SourceFile, writeFileCallback: WriteFileCallback, cancellationToken: CancellationToken): EmitResult { let declarationDiagnostics: Diagnostic[] = []; if (options.noEmit) { return { diagnostics: declarationDiagnostics, sourceMaps: undefined, emitSkipped: true }; } // If the noEmitOnError flag is set, then check if we have any errors so far. If so, // immediately bail out. Note that we pass 'undefined' for 'sourceFile' so that we // get any preEmit diagnostics, not just the ones if (options.noEmitOnError) { const diagnostics = program.getOptionsDiagnostics(cancellationToken).concat( program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); if (diagnostics.length === 0 && program.getCompilerOptions().declaration) { declarationDiagnostics = program.getDeclarationDiagnostics(/*sourceFile*/ undefined, cancellationToken); } if (diagnostics.length > 0 || declarationDiagnostics.length > 0) { return { diagnostics, sourceMaps: undefined, emitSkipped: true }; } } // Create the emit resolver outside of the "emitTime" tracking code below. That way // any cost associated with it (like type checking) are appropriate associated with // the type-checking counter. // // If the -out option is specified, we should not pass the source file to getEmitResolver. // This is because in the -out scenario all files need to be emitted, and therefore all // files need to be type checked. And the way to specify that all files need to be type // checked is to not pass the file to getEmitResolver. const emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile); const start = new Date().getTime(); const emitResult = emitFiles( emitResolver, getEmitHost(writeFileCallback), sourceFile); emitTime += new Date().getTime() - start; return emitResult; } function getSourceFile(fileName: string): SourceFile { return filesByName.get(toPath(fileName, currentDirectory, getCanonicalFileName)); } function getDiagnosticsHelper( sourceFile: SourceFile, getDiagnostics: (sourceFile: SourceFile, cancellationToken: CancellationToken) => Diagnostic[], cancellationToken: CancellationToken): Diagnostic[] { if (sourceFile) { return getDiagnostics(sourceFile, cancellationToken); } const allDiagnostics: Diagnostic[] = []; forEach(program.getSourceFiles(), sourceFile => { if (cancellationToken) { cancellationToken.throwIfCancellationRequested(); } addRange(allDiagnostics, getDiagnostics(sourceFile, cancellationToken)); }); return sortAndDeduplicateDiagnostics(allDiagnostics); } function getSyntacticDiagnostics(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] { return getDiagnosticsHelper(sourceFile, getSyntacticDiagnosticsForFile, cancellationToken); } function getSemanticDiagnostics(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] { return getDiagnosticsHelper(sourceFile, getSemanticDiagnosticsForFile, cancellationToken); } function getDeclarationDiagnostics(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] { return getDiagnosticsHelper(sourceFile, getDeclarationDiagnosticsForFile, cancellationToken); } function getSyntacticDiagnosticsForFile(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] { return sourceFile.parseDiagnostics; } function runWithCancellationToken<T>(func: () => T): T { try { return func(); } catch (e) { if (e instanceof OperationCanceledException) { // We were canceled while performing the operation. Because our type checker // might be a bad state, we need to throw it away. // // Note: we are overly aggressive here. We do not actually *have* to throw away // the "noDiagnosticsTypeChecker". However, for simplicity, i'd like to keep // the lifetimes of these two TypeCheckers the same. Also, we generally only // cancel when the user has made a change anyways. And, in that case, we (the // program instance) will get thrown away anyways. So trying to keep one of // these type checkers alive doesn't serve much purpose. noDiagnosticsTypeChecker = undefined; diagnosticsProducingTypeChecker = undefined; } throw e; } } function getSemanticDiagnosticsForFile(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] { return runWithCancellationToken(() => { const typeChecker = getDiagnosticsProducingTypeChecker(); Debug.assert(!!sourceFile.bindDiagnostics); const bindDiagnostics = sourceFile.bindDiagnostics; // For JavaScript files, we don't want to report the normal typescript semantic errors. // Instead, we just report errors for using TypeScript-only constructs from within a // JavaScript file. const checkDiagnostics = isSourceFileJavaScript(sourceFile) ? getJavaScriptSemanticDiagnosticsForFile(sourceFile, cancellationToken) : typeChecker.getDiagnostics(sourceFile, cancellationToken); const fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName); const programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName); return bindDiagnostics.concat(checkDiagnostics).concat(fileProcessingDiagnosticsInFile).concat(programDiagnosticsInFile); }); } function getJavaScriptSemanticDiagnosticsForFile(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] { return runWithCancellationToken(() => { const diagnostics: Diagnostic[] = []; walk(sourceFile); return diagnostics; function walk(node: Node): boolean { if (!node) { return false; } switch (node.kind) { case SyntaxKind.ImportEqualsDeclaration: diagnostics.push(createDiagnosticForNode(node, Diagnostics.import_can_only_be_used_in_a_ts_file)); return true; case SyntaxKind.ExportAssignment: if ((<ExportAssignment>node).isExportEquals) { diagnostics.push(createDiagnosticForNode(node, Diagnostics.export_can_only_be_used_in_a_ts_file)); return true; } break; case SyntaxKind.ClassDeclaration: let classDeclaration = <ClassDeclaration>node; if (checkModifiers(classDeclaration.modifiers) || checkTypeParameters(classDeclaration.typeParameters)) { return true; } break; case SyntaxKind.HeritageClause: let heritageClause = <HeritageClause>node; if (heritageClause.token === SyntaxKind.ImplementsKeyword) { diagnostics.push(createDiagnosticForNode(node, Diagnostics.implements_clauses_can_only_be_used_in_a_ts_file)); return true; } break; case SyntaxKind.InterfaceDeclaration: diagnostics.push(createDiagnosticForNode(node, Diagnostics.interface_declarations_can_only_be_used_in_a_ts_file)); return true; case SyntaxKind.ModuleDeclaration: diagnostics.push(createDiagnosticForNode(node, Diagnostics.module_declarations_can_only_be_used_in_a_ts_file)); return true; case SyntaxKind.TypeAliasDeclaration: diagnostics.push(createDiagnosticForNode(node, Diagnostics.type_aliases_can_only_be_used_in_a_ts_file)); return true; case SyntaxKind.MethodDeclaration: case SyntaxKind.MethodSignature: case SyntaxKind.Constructor: case SyntaxKind.GetAccessor: case SyntaxKind.SetAccessor: case SyntaxKind.FunctionExpression: case SyntaxKind.FunctionDeclaration: case SyntaxKind.ArrowFunction: case SyntaxKind.FunctionDeclaration: const functionDeclaration = <FunctionLikeDeclaration>node; if (checkModifiers(functionDeclaration.modifiers) || checkTypeParameters(functionDeclaration.typeParameters) || checkTypeAnnotation(functionDeclaration.type)) { return true; } break; case SyntaxKind.VariableStatement: const variableStatement = <VariableStatement>node; if (checkModifiers(variableStatement.modifiers)) { return true; } break; case SyntaxKind.VariableDeclaration: const variableDeclaration = <VariableDeclaration>node; if (checkTypeAnnotation(variableDeclaration.type)) { return true; } break; case SyntaxKind.CallExpression: case SyntaxKind.NewExpression: const expression = <CallExpression>node; if (expression.typeArguments && expression.typeArguments.length > 0) { const start = expression.typeArguments.pos; diagnostics.push(createFileDiagnostic(sourceFile, start, expression.typeArguments.end - start, Diagnostics.type_arguments_can_only_be_used_in_a_ts_file)); return true; } break; case SyntaxKind.Parameter: const parameter = <ParameterDeclaration>node; if (parameter.modifiers) { const start = parameter.modifiers.pos; diagnostics.push(createFileDiagnostic(sourceFile, start, parameter.modifiers.end - start, Diagnostics.parameter_modifiers_can_only_be_used_in_a_ts_file)); return true; } if (parameter.questionToken) { diagnostics.push(createDiagnosticForNode(parameter.questionToken, Diagnostics._0_can_only_be_used_in_a_ts_file, "?")); return true; } if (parameter.type) { diagnostics.push(createDiagnosticForNode(parameter.type, Diagnostics.types_can_only_be_used_in_a_ts_file)); return true; } break; case SyntaxKind.PropertyDeclaration: diagnostics.push(createDiagnosticForNode(node, Diagnostics.property_declarations_can_only_be_used_in_a_ts_file)); return true; case SyntaxKind.EnumDeclaration: diagnostics.push(createDiagnosticForNode(node, Diagnostics.enum_declarations_can_only_be_used_in_a_ts_file)); return true; case SyntaxKind.TypeAssertionExpression: let typeAssertionExpression = <TypeAssertion>node; diagnostics.push(createDiagnosticForNode(typeAssertionExpression.type, Diagnostics.type_assertion_expressions_can_only_be_used_in_a_ts_file)); return true; case SyntaxKind.Decorator: if (!options.experimentalDecorators) { diagnostics.push(createDiagnosticForNode(node, Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning)); } return true; } return forEachChild(node, walk); } function checkTypeParameters(typeParameters: NodeArray<TypeParameterDeclaration>): boolean { if (typeParameters) { const start = typeParameters.pos; diagnostics.push(createFileDiagnostic(sourceFile, start, typeParameters.end - start, Diagnostics.type_parameter_declarations_can_only_be_used_in_a_ts_file)); return true; } return false; } function checkTypeAnnotation(type: TypeNode): boolean { if (type) { diagnostics.push(createDiagnosticForNode(type, Diagnostics.types_can_only_be_used_in_a_ts_file)); return true; } return false; } function checkModifiers(modifiers: ModifiersArray): boolean { if (modifiers) { for (const modifier of modifiers) { switch (modifier.kind) { case SyntaxKind.PublicKeyword: case SyntaxKind.PrivateKeyword: case SyntaxKind.ProtectedKeyword: case SyntaxKind.ReadonlyKeyword: case SyntaxKind.DeclareKeyword: diagnostics.push(createDiagnosticForNode(modifier, Diagnostics._0_can_only_be_used_in_a_ts_file, tokenToString(modifier.kind))); return true; // These are all legal modifiers. case SyntaxKind.StaticKeyword: case SyntaxKind.ExportKeyword: case SyntaxKind.ConstKeyword: case SyntaxKind.DefaultKeyword: case SyntaxKind.AbstractKeyword: } } } return false; } }); } function getDeclarationDiagnosticsForFile(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] { return runWithCancellationToken(() => { if (!isDeclarationFile(sourceFile)) { const resolver = getDiagnosticsProducingTypeChecker().getEmitResolver(sourceFile, cancellationToken); // Don't actually write any files since we're just getting diagnostics. const writeFile: WriteFileCallback = () => { }; return ts.getDeclarationDiagnostics(getEmitHost(writeFile), resolver, sourceFile); } }); } function getOptionsDiagnostics(): Diagnostic[] { const allDiagnostics: Diagnostic[] = []; addRange(allDiagnostics, fileProcessingDiagnostics.getGlobalDiagnostics()); addRange(allDiagnostics, programDiagnostics.getGlobalDiagnostics()); return sortAndDeduplicateDiagnostics(allDiagnostics); } function getGlobalDiagnostics(): Diagnostic[] { const allDiagnostics: Diagnostic[] = []; addRange(allDiagnostics, getDiagnosticsProducingTypeChecker().getGlobalDiagnostics()); return sortAndDeduplicateDiagnostics(allDiagnostics); } function hasExtension(fileName: string): boolean { return getBaseFileName(fileName).indexOf(".") >= 0; } function processRootFile(fileName: string, isDefaultLib: boolean) { processSourceFile(normalizePath(fileName), isDefaultLib); } function fileReferenceIsEqualTo(a: FileReference, b: FileReference): boolean { return a.fileName === b.fileName; } function moduleNameIsEqualTo(a: LiteralExpression, b: LiteralExpression): boolean { return a.text === b.text; } function getTextOfLiteral(literal: LiteralExpression): string { return literal.text; } function collectExternalModuleReferences(file: SourceFile): void { if (file.imports) { return; } const isJavaScriptFile = isSourceFileJavaScript(file); const isExternalModuleFile = isExternalModule(file); let imports: LiteralExpression[]; let moduleAugmentations: LiteralExpression[]; for (const node of file.statements) { collectModuleReferences(node, /*inAmbientModule*/ false); if (isJavaScriptFile) { collectRequireCalls(node); } } file.imports = imports || emptyArray; file.moduleAugmentations = moduleAugmentations || emptyArray; return; function collectModuleReferences(node: Node, inAmbientModule: boolean): void { switch (node.kind) { case SyntaxKind.ImportDeclaration: case SyntaxKind.ImportEqualsDeclaration: case SyntaxKind.ExportDeclaration: let moduleNameExpr = getExternalModuleName(node); if (!moduleNameExpr || moduleNameExpr.kind !== SyntaxKind.StringLiteral) { break; } if (!(<LiteralExpression>moduleNameExpr).text) { break; } // TypeScript 1.0 spec (April 2014): 12.1.6 // An ExternalImportDeclaration in an AmbientExternalModuleDeclaration may reference other external modules // only through top - level external module names. Relative external module names are not permitted. if (!inAmbientModule || !isExternalModuleNameRelative((<LiteralExpression>moduleNameExpr).text)) { (imports || (imports = [])).push(<LiteralExpression>moduleNameExpr); } break; case SyntaxKind.ModuleDeclaration: if (isAmbientModule(<ModuleDeclaration>node) && (inAmbientModule || node.flags & NodeFlags.Ambient || isDeclarationFile(file))) { const moduleName = <LiteralExpression>(<ModuleDeclaration>node).name; // Ambient module declarations can be interpreted as augmentations for some existing external modules. // This will happen in two cases: // - if current file is external module then module augmentation is a ambient module declaration defined in the top level scope // - if current file is not external module then module augmentation is an ambient module declaration with non-relative module name // immediately nested in top level ambient module declaration . if (isExternalModuleFile || (inAmbientModule && !isExternalModuleNameRelative(moduleName.text))) { (moduleAugmentations || (moduleAugmentations = [])).push(moduleName); } else if (!inAmbientModule) { // An AmbientExternalModuleDeclaration declares an external module. // This type of declaration is permitted only in the global module. // The StringLiteral must specify a top - level external module name. // Relative external module names are not permitted // NOTE: body of ambient module is always a module block for (const statement of (<ModuleBlock>(<ModuleDeclaration>node).body).statements) { collectModuleReferences(statement, /*inAmbientModule*/ true); } } } } } function collectRequireCalls(node: Node): void { if (isRequireCall(node, /*checkArgumentIsStringLiteral*/true)) { (imports || (imports = [])).push(<StringLiteral>(<CallExpression>node).arguments[0]); } else { forEachChild(node, collectRequireCalls); } } } function processSourceFile(fileName: string, isDefaultLib: boolean, refFile?: SourceFile, refPos?: number, refEnd?: number) { let diagnosticArgument: string[]; let diagnostic: DiagnosticMessage; if (hasExtension(fileName)) { if (!options.allowNonTsExtensions && !forEach(supportedExtensions, extension => fileExtensionIs(host.getCanonicalFileName(fileName), extension))) { diagnostic = Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1; diagnosticArgument = [fileName, "'" + supportedExtensions.join("', '") + "'"]; } else if (!findSourceFile(fileName, toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd)) { diagnostic = Diagnostics.File_0_not_found; diagnosticArgument = [fileName]; } else if (refFile && host.getCanonicalFileName(fileName) === host.getCanonicalFileName(refFile.fileName)) { diagnostic = Diagnostics.A_file_cannot_have_a_reference_to_itself; diagnosticArgument = [fileName]; } } else { const nonTsFile: SourceFile = options.allowNonTsExtensions && findSourceFile(fileName, toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); if (!nonTsFile) { if (options.allowNonTsExtensions) { diagnostic = Diagnostics.File_0_not_found; diagnosticArgument = [fileName]; } else if (!forEach(supportedExtensions, extension => findSourceFile(fileName + extension, toPath(fileName + extension, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd))) { diagnostic = Diagnostics.File_0_not_found; fileName += ".ts"; diagnosticArgument = [fileName]; } } } if (diagnostic) { if (refFile !== undefined && refEnd !== undefined && refPos !== undefined) { fileProcessingDiagnostics.add(createFileDiagnostic(refFile, refPos, refEnd - refPos, diagnostic, ...diagnosticArgument)); } else { fileProcessingDiagnostics.add(createCompilerDiagnostic(diagnostic, ...diagnosticArgument)); } } } function reportFileNamesDifferOnlyInCasingError(fileName: string, existingFileName: string, refFile: SourceFile, refPos: number, refEnd: number): void { if (refFile !== undefined && refPos !== undefined && refEnd !== undefined) { fileProcessingDiagnostics.add(createFileDiagnostic(refFile, refPos, refEnd - refPos, Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, existingFileName)); } else { fileProcessingDiagnostics.add(createCompilerDiagnostic(Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, existingFileName)); } } // Get source file from normalized fileName function findSourceFile(fileName: string, path: Path, isDefaultLib: boolean, refFile?: SourceFile, refPos?: number, refEnd?: number): SourceFile { if (filesByName.contains(path)) { const file = filesByName.get(path); // try to check if we've already seen this file but with a different casing in path // NOTE: this only makes sense for case-insensitive file systems if (file && options.forceConsistentCasingInFileNames && getNormalizedAbsolutePath(file.fileName, currentDirectory) !== getNormalizedAbsolutePath(fileName, currentDirectory)) { reportFileNamesDifferOnlyInCasingError(fileName, file.fileName, refFile, refPos, refEnd); } return file; } // We haven't looked for this file, do so now and cache result const file = host.getSourceFile(fileName, options.target, hostErrorMessage => { if (refFile !== undefined && refPos !== undefined && refEnd !== undefined) { fileProcessingDiagnostics.add(createFileDiagnostic(refFile, refPos, refEnd - refPos, Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage)); } else { fileProcessingDiagnostics.add(createCompilerDiagnostic(Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage)); } }); filesByName.set(path, file); if (file) { file.path = path; if (host.useCaseSensitiveFileNames()) { // for case-sensitive file systems check if we've already seen some file with similar filename ignoring case const existingFile = filesByNameIgnoreCase.get(path); if (existingFile) { reportFileNamesDifferOnlyInCasingError(fileName, existingFile.fileName, refFile, refPos, refEnd); } else { filesByNameIgnoreCase.set(path, file); } } skipDefaultLib = skipDefaultLib || file.hasNoDefaultLib; const basePath = getDirectoryPath(fileName); if (!options.noResolve) { processReferencedFiles(file, basePath); } // always process imported modules to record module name resolutions processImportedModules(file, basePath); if (isDefaultLib) { files.unshift(file); } else { files.push(file); } } return file; } function processReferencedFiles(file: SourceFile, basePath: string) { forEach(file.referencedFiles, ref => { const referencedFileName = resolveTripleslashReference(ref.fileName, file.fileName); processSourceFile(referencedFileName, /*isDefaultLib*/ false, file, ref.pos, ref.end); }); } function getCanonicalFileName(fileName: string): string { return host.getCanonicalFileName(fileName); } function processImportedModules(file: SourceFile, basePath: string) { collectExternalModuleReferences(file); if (file.imports.length || file.moduleAugmentations.length) { file.resolvedModules = {}; const moduleNames = map(concatenate(file.imports, file.moduleAugmentations), getTextOfLiteral); const resolutions = resolveModuleNamesWorker(moduleNames, getNormalizedAbsolutePath(file.fileName, currentDirectory)); for (let i = 0; i < moduleNames.length; i++) { const resolution = resolutions[i]; setResolvedModule(file, moduleNames[i], resolution); // add file to program only if: // - resolution was successful // - noResolve is falsy // - module name come from the list fo imports const shouldAddFile = resolution && !options.noResolve && i < file.imports.length; if (shouldAddFile) { const importedFile = findSourceFile(resolution.resolvedFileName, toPath(resolution.resolvedFileName, currentDirectory, getCanonicalFileName), /*isDefaultLib*/ false, file, skipTrivia(file.text, file.imports[i].pos), file.imports[i].end); if (importedFile && resolution.isExternalLibraryImport) { // Since currently irrespective of allowJs, we only look for supportedTypeScript extension external module files, // this check is ok. Otherwise this would be never true for javascript file if (!isExternalModule(importedFile) && importedFile.statements.length) { const start = getTokenPosOfNode(file.imports[i], file); fileProcessingDiagnostics.add(createFileDiagnostic(file, start, file.imports[i].end - start, Diagnostics.Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_the_package_definition, importedFile.fileName)); } else if (importedFile.referencedFiles.length) { const firstRef = importedFile.referencedFiles[0]; fileProcessingDiagnostics.add(createFileDiagnostic(importedFile, firstRef.pos, firstRef.end - firstRef.pos, Diagnostics.Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_package_author_to_update_the_package_definition)); } } } } } else { // no imports - drop cached module resolutions file.resolvedModules = undefined; } return; } function computeCommonSourceDirectory(sourceFiles: SourceFile[]): string { let commonPathComponents: string[]; const failed = forEach(files, sourceFile => { // Each file contributes into common source file path if (isDeclarationFile(sourceFile)) { return; } const sourcePathComponents = getNormalizedPathComponents(sourceFile.fileName, currentDirectory); sourcePathComponents.pop(); // The base file name is not part of the common directory path if (!commonPathComponents) { // first file commonPathComponents = sourcePathComponents; return; } for (let i = 0, n = Math.min(commonPathComponents.length, sourcePathComponents.length); i < n; i++) { if (getCanonicalFileName(commonPathComponents[i]) !== getCanonicalFileName(sourcePathComponents[i])) { if (i === 0) { // Failed to find any common path component return true; } // New common path found that is 0 -> i-1 commonPathComponents.length = i; break; } } // If the sourcePathComponents was shorter than the commonPathComponents, truncate to the sourcePathComponents if (sourcePathComponents.length < commonPathComponents.length) { commonPathComponents.length = sourcePathComponents.length; } }); // A common path can not be found when paths span multiple drives on windows, for example if (failed) { return ""; } if (!commonPathComponents) { // Can happen when all input files are .d.ts files return currentDirectory; } return getNormalizedPathFromPathComponents(commonPathComponents); } function checkSourceFilesBelongToPath(sourceFiles: SourceFile[], rootDirectory: string): boolean { let allFilesBelongToPath = true; if (sourceFiles) { const absoluteRootDirectoryPath = host.getCanonicalFileName(getNormalizedAbsolutePath(rootDirectory, currentDirectory)); for (const sourceFile of sourceFiles) { if (!isDeclarationFile(sourceFile)) { const absoluteSourceFilePath = host.getCanonicalFileName(getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, options.rootDir)); allFilesBelongToPath = false; } } } } return allFilesBelongToPath; } function verifyCompilerOptions() { if (options.isolatedModules) { if (options.declaration) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "declaration", "isolatedModules")); } if (options.noEmitOnError) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmitOnError", "isolatedModules")); } if (options.out) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "isolatedModules")); } if (options.outFile) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "outFile", "isolatedModules")); } } if (options.inlineSourceMap) { if (options.sourceMap) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "sourceMap", "inlineSourceMap")); } if (options.mapRoot) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "mapRoot", "inlineSourceMap")); } } if (options.paths && options.baseUrl === undefined) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_paths_cannot_be_used_without_specifying_baseUrl_option)); } if (options.paths) { for (const key in options.paths) { if (!hasProperty(options.paths, key)) { continue; } if (!hasZeroOrOneAsteriskCharacter(key)) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, key)); } for (const subst of options.paths[key]) { if (!hasZeroOrOneAsteriskCharacter(subst)) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character, subst, key)); } } } } if (options.inlineSources) { if (!options.sourceMap && !options.inlineSourceMap) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_inlineSources_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided)); } if (options.sourceRoot) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "sourceRoot", "inlineSources")); } } if (options.out && options.outFile) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "outFile")); } if (!options.sourceMap && (options.mapRoot || options.sourceRoot)) { // Error to specify --mapRoot or --sourceRoot without mapSourceFiles if (options.mapRoot) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "mapRoot", "sourceMap")); } if (options.sourceRoot && !options.inlineSourceMap) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "sourceRoot", "sourceMap")); } } if (options.declarationDir) { if (!options.declaration) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "declarationDir", "declaration")); } if (options.out || options.outFile) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "declarationDir", options.out ? "out" : "outFile")); } } const languageVersion = options.target || ScriptTarget.ES3; const outFile = options.outFile || options.out; const firstExternalModuleSourceFile = forEach(files, f => isExternalModule(f) ? f : undefined); if (options.isolatedModules) { if (options.module === ModuleKind.None && languageVersion < ScriptTarget.ES6) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher)); } const firstNonExternalModuleSourceFile = forEach(files, f => !isExternalModule(f) && !isDeclarationFile(f) ? f : undefined); if (firstNonExternalModuleSourceFile) { const span = getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile); programDiagnostics.add(createFileDiagnostic(firstNonExternalModuleSourceFile, span.start, span.length, Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided)); } } else if (firstExternalModuleSourceFile && languageVersion < ScriptTarget.ES6 && options.module === ModuleKind.None) { // We cannot use createDiagnosticFromNode because nodes do not have parents yet const span = getErrorSpanForNode(firstExternalModuleSourceFile, firstExternalModuleSourceFile.externalModuleIndicator); programDiagnostics.add(createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, Diagnostics.Cannot_compile_modules_unless_the_module_flag_is_provided_with_a_valid_module_type_Consider_setting_the_module_compiler_option_in_a_tsconfig_json_file)); } // Cannot specify module gen target of es6 when below es6 if (options.module === ModuleKind.ES6 && languageVersion < ScriptTarget.ES6) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Cannot_compile_modules_into_es2015_when_targeting_ES5_or_lower)); } // Cannot specify module gen that isn't amd or system with --out if (outFile && options.module && !(options.module === ModuleKind.AMD || options.module === ModuleKind.System)) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile")); } // there has to be common source directory if user specified --outdir || --sourceRoot // if user specified --mapRoot, there needs to be common source directory if there would be multiple files being emitted if (options.outDir || // there is --outDir specified options.sourceRoot || // there is --sourceRoot specified options.mapRoot) { // there is --mapRoot specified // Precalculate and cache the common source directory const dir = getCommonSourceDirectory(); // If we failed to find a good common directory, but outDir is specified and at least one of our files is on a windows drive/URL/other resource, add a failure if (options.outDir && dir === "" && forEach(files, file => getRootLength(file.fileName) > 1)) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files)); } } if (options.noEmit) { if (options.out) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmit", "out")); } if (options.outFile) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmit", "outFile")); } if (options.outDir) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmit", "outDir")); } if (options.declaration) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmit", "declaration")); } } else if (options.allowJs && options.declaration) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", "declaration")); } if (options.emitDecoratorMetadata && !options.experimentalDecorators) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDecoratorMetadata", "experimentalDecorators")); } if (options.reactNamespace && !isIdentifier(options.reactNamespace, languageVersion)) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier, options.reactNamespace)); } // If the emit is enabled make sure that every output file is unique and not overwriting any of the input files if (!options.noEmit && !options.suppressOutputPathCheck) { const emitHost = getEmitHost(); const emitFilesSeen = createFileMap<boolean>(!host.useCaseSensitiveFileNames() ? key => key.toLocaleLowerCase() : undefined); forEachExpectedEmitFile(emitHost, (emitFileNames, sourceFiles, isBundledEmit) => { verifyEmitFilePath(emitFileNames.jsFilePath, emitFilesSeen); verifyEmitFilePath(emitFileNames.declarationFilePath, emitFilesSeen); }); } // Verify that all the emit files are unique and don't overwrite input files function verifyEmitFilePath(emitFileName: string, emitFilesSeen: FileMap<boolean>) { if (emitFileName) { const emitFilePath = toPath(emitFileName, currentDirectory, getCanonicalFileName); // Report error if the output overwrites input file if (filesByName.contains(emitFilePath)) { createEmitBlockingDiagnostics(emitFileName, emitFilePath, Diagnostics.Cannot_write_file_0_because_it_would_overwrite_input_file); } // Report error if multiple files write into same file if (emitFilesSeen.contains(emitFilePath)) { // Already seen the same emit file - report error createEmitBlockingDiagnostics(emitFileName, emitFilePath, Diagnostics.Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files); } else { emitFilesSeen.set(emitFilePath, true); } } } } function createEmitBlockingDiagnostics(emitFileName: string, emitFilePath: Path, message: DiagnosticMessage) { hasEmitBlockingDiagnostics.set(toPath(emitFileName, currentDirectory, getCanonicalFileName), true); programDiagnostics.add(createCompilerDiagnostic(message, emitFileName)); } } }
src/compiler/program.ts
1
https://github.com/microsoft/TypeScript/commit/8e77f40ace2155b16bb0ac5a417467edbec86843
[ 0.9987697005271912, 0.08144194632768631, 0.00016451235569547862, 0.0002895535435527563, 0.2448028028011322 ]
{ "id": 2, "code_window": [ " });\n", " }\n", "\n", " function getDeclarationDiagnosticsForFile(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] {\n", " return runWithCancellationToken(() => {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ " function getDeclarationDiagnosticsWorker(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] {\n" ], "file_path": "src/compiler/program.ts", "type": "replace", "edit_start_line_idx": 1214 }
tests/cases/conformance/types/namedTypes/interfaceWithPrivateMember.ts(5,5): error TS1070: 'private' modifier cannot appear on a type member. tests/cases/conformance/types/namedTypes/interfaceWithPrivateMember.ts(9,5): error TS1070: 'private' modifier cannot appear on a type member. tests/cases/conformance/types/namedTypes/interfaceWithPrivateMember.ts(13,5): error TS1070: 'private' modifier cannot appear on a type member. ==== tests/cases/conformance/types/namedTypes/interfaceWithPrivateMember.ts (3 errors) ==== // interfaces do not permit private members, these are errors interface I { private x: string; ~~~~~~~ !!! error TS1070: 'private' modifier cannot appear on a type member. } interface I2<T> { private y: T; ~~~~~~~ !!! error TS1070: 'private' modifier cannot appear on a type member. } var x: { private y: string; ~~~~~~~ !!! error TS1070: 'private' modifier cannot appear on a type member. }
tests/baselines/reference/interfaceWithPrivateMember.errors.txt
0
https://github.com/microsoft/TypeScript/commit/8e77f40ace2155b16bb0ac5a417467edbec86843
[ 0.0001707374321995303, 0.00016830896493047476, 0.00016668647003825754, 0.00016750300710555166, 0.000001749238890624838 ]
{ "id": 2, "code_window": [ " });\n", " }\n", "\n", " function getDeclarationDiagnosticsForFile(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] {\n", " return runWithCancellationToken(() => {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ " function getDeclarationDiagnosticsWorker(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] {\n" ], "file_path": "src/compiler/program.ts", "type": "replace", "edit_start_line_idx": 1214 }
var x = 1; var y = 1; var z = x + + + y var a = 1; var b = 1; var c = x - - - y
tests/cases/compiler/asiArith.ts
0
https://github.com/microsoft/TypeScript/commit/8e77f40ace2155b16bb0ac5a417467edbec86843
[ 0.00017348954861517996, 0.0001691557845333591, 0.00016487071115989238, 0.00016913143917918205, 0.0000037874735880905064 ]
{ "id": 2, "code_window": [ " });\n", " }\n", "\n", " function getDeclarationDiagnosticsForFile(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] {\n", " return runWithCancellationToken(() => {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ " function getDeclarationDiagnosticsWorker(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] {\n" ], "file_path": "src/compiler/program.ts", "type": "replace", "edit_start_line_idx": 1214 }
//@module: amd //@target: ES5 // @filename: m1.ts export default function f1() { } // @filename: m2.ts import f1 from "./m1"; export default function f2() { f1(); }
tests/cases/conformance/es6/modules/exportAndImport-es5-amd.ts
0
https://github.com/microsoft/TypeScript/commit/8e77f40ace2155b16bb0ac5a417467edbec86843
[ 0.0001747128408169374, 0.00017400736396666616, 0.00017330188711639494, 0.00017400736396666616, 7.05476850271225e-7 ]
{ "id": 3, "code_window": [ " return runWithCancellationToken(() => {\n", " if (!isDeclarationFile(sourceFile)) {\n", " const resolver = getDiagnosticsProducingTypeChecker().getEmitResolver(sourceFile, cancellationToken);\n", " // Don't actually write any files since we're just getting diagnostics.\n", " const writeFile: WriteFileCallback = () => { };\n", " return ts.getDeclarationDiagnostics(getEmitHost(writeFile), resolver, sourceFile);\n", " }\n", " });\n", " }\n", "\n" ], "labels": [ "keep", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " const resolver = getDiagnosticsProducingTypeChecker().getEmitResolver(sourceFile, cancellationToken);\n", " // Don't actually write any files since we're just getting diagnostics.\n", " const writeFile: WriteFileCallback = () => { };\n", " return ts.getDeclarationDiagnostics(getEmitHost(writeFile), resolver, sourceFile);\n" ], "file_path": "src/compiler/program.ts", "type": "replace", "edit_start_line_idx": 1216 }
/// <reference path="sys.ts" /> /// <reference path="emitter.ts" /> /// <reference path="core.ts" /> namespace ts { /* @internal */ export let programTime = 0; /* @internal */ export let emitTime = 0; /* @internal */ export let ioReadTime = 0; /* @internal */ export let ioWriteTime = 0; /** The version of the TypeScript compiler release */ const emptyArray: any[] = []; export const version = "1.9.0"; export function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean): string { let fileName = "tsconfig.json"; while (true) { if (fileExists(fileName)) { return fileName; } const parentPath = getDirectoryPath(searchPath); if (parentPath === searchPath) { break; } searchPath = parentPath; fileName = "../" + fileName; } return undefined; } export function resolveTripleslashReference(moduleName: string, containingFile: string): string { const basePath = getDirectoryPath(containingFile); const referencedFileName = isRootedDiskPath(moduleName) ? moduleName : combinePaths(basePath, moduleName); return normalizePath(referencedFileName); } function trace(host: ModuleResolutionHost, message: DiagnosticMessage, ...args: any[]): void; function trace(host: ModuleResolutionHost, message: DiagnosticMessage): void { host.trace(formatMessage.apply(undefined, arguments)); } function isTraceEnabled(compilerOptions: CompilerOptions, host: ModuleResolutionHost): boolean { return compilerOptions.traceModuleResolution && host.trace !== undefined; } function startsWith(str: string, prefix: string): boolean { return str.lastIndexOf(prefix, 0) === 0; } function endsWith(str: string, suffix: string): boolean { const expectedPos = str.length - suffix.length; return str.indexOf(suffix, expectedPos) === expectedPos; } function hasZeroOrOneAsteriskCharacter(str: string): boolean { let seenAsterisk = false; for (let i = 0; i < str.length; i++) { if (str.charCodeAt(i) === CharacterCodes.asterisk) { if (!seenAsterisk) { seenAsterisk = true; } else { // have already seen asterisk return false; } } } return true; } function createResolvedModule(resolvedFileName: string, isExternalLibraryImport: boolean, failedLookupLocations: string[]): ResolvedModuleWithFailedLookupLocations { return { resolvedModule: resolvedFileName ? { resolvedFileName, isExternalLibraryImport } : undefined, failedLookupLocations }; } function moduleHasNonRelativeName(moduleName: string): boolean { if (isRootedDiskPath(moduleName)) { return false; } const i = moduleName.lastIndexOf("./", 1); const startsWithDotSlashOrDotDotSlash = i === 0 || (i === 1 && moduleName.charCodeAt(0) === CharacterCodes.dot); return !startsWithDotSlashOrDotDotSlash; } interface ModuleResolutionState { host: ModuleResolutionHost; compilerOptions: CompilerOptions; traceEnabled: boolean; // skip .tsx files if jsx is not enabled skipTsx: boolean; } export function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations { const traceEnabled = isTraceEnabled(compilerOptions, host); if (traceEnabled) { trace(host, Diagnostics.Resolving_module_0_from_1, moduleName, containingFile); } let moduleResolution = compilerOptions.moduleResolution; if (moduleResolution === undefined) { moduleResolution = getEmitModuleKind(compilerOptions) === ModuleKind.CommonJS ? ModuleResolutionKind.NodeJs : ModuleResolutionKind.Classic; if (traceEnabled) { trace(host, Diagnostics.Module_resolution_kind_is_not_specified_using_0, ModuleResolutionKind[moduleResolution]); } } else { if (traceEnabled) { trace(host, Diagnostics.Explicitly_specified_module_resolution_kind_Colon_0, ModuleResolutionKind[moduleResolution]); } } let result: ResolvedModuleWithFailedLookupLocations; switch (moduleResolution) { case ModuleResolutionKind.NodeJs: result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host); break; case ModuleResolutionKind.Classic: result = classicNameResolver(moduleName, containingFile, compilerOptions, host); break; } if (traceEnabled) { if (result.resolvedModule) { trace(host, Diagnostics.Module_name_0_was_successfully_resolved_to_1, moduleName, result.resolvedModule.resolvedFileName); } else { trace(host, Diagnostics.Module_name_0_was_not_resolved, moduleName); } } return result; } /* * Every module resolution kind can has its specific understanding how to load module from a specific path on disk * I.e. for path '/a/b/c': * - Node loader will first to try to check if '/a/b/c' points to a file with some supported extension and if this fails * it will try to load module from directory: directory '/a/b/c' should exist and it should have either 'package.json' with * 'typings' entry or file 'index' with some supported extension * - Classic loader will only try to interpret '/a/b/c' as file. */ type ResolutionKindSpecificLoader = (candidate: string, extensions: string[], failedLookupLocations: string[], onlyRecordFailures: boolean, state: ModuleResolutionState) => string; /** * Any module resolution kind can be augmented with optional settings: 'baseUrl', 'paths' and 'rootDirs' - they are used to * mitigate differences between design time structure of the project and its runtime counterpart so the same import name * can be resolved successfully by TypeScript compiler and runtime module loader. * If these settings are set then loading procedure will try to use them to resolve module name and it can of failure it will * fallback to standard resolution routine. * * - baseUrl - this setting controls how non-relative module names are resolved. If this setting is specified then non-relative * names will be resolved relative to baseUrl: i.e. if baseUrl is '/a/b' then candidate location to resolve module name 'c/d' will * be '/a/b/c/d' * - paths - this setting can only be used when baseUrl is specified. allows to tune how non-relative module names * will be resolved based on the content of the module name. * Structure of 'paths' compiler options * 'paths': { * pattern-1: [...substitutions], * pattern-2: [...substitutions], * ... * pattern-n: [...substitutions] * } * Pattern here is a string that can contain zero or one '*' character. During module resolution module name will be matched against * all patterns in the list. Matching for patterns that don't contain '*' means that module name must be equal to pattern respecting the case. * If pattern contains '*' then to match pattern "<prefix>*<suffix>" module name must start with the <prefix> and end with <suffix>. * <MatchedStar> denotes part of the module name between <prefix> and <suffix>. * If module name can be matches with multiple patterns then pattern with the longest prefix will be picked. * After selecting pattern we'll use list of substitutions to get candidate locations of the module and the try to load module * from the candidate location. * Substitution is a string that can contain zero or one '*'. To get candidate location from substitution we'll pick every * substitution in the list and replace '*' with <MatchedStar> string. If candidate location is not rooted it * will be converted to absolute using baseUrl. * For example: * baseUrl: /a/b/c * "paths": { * // match all module names * "*": [ * "*", // use matched name as is, * // <matched name> will be looked as /a/b/c/<matched name> * * "folder1/*" // substitution will convert matched name to 'folder1/<matched name>', * // since it is not rooted then final candidate location will be /a/b/c/folder1/<matched name> * ], * // match module names that start with 'components/' * "components/*": [ "/root/components/*" ] // substitution will convert /components/folder1/<matched name> to '/root/components/folder1/<matched name>', * // it is rooted so it will be final candidate location * } * * 'rootDirs' allows the project to be spreaded across multiple locations and resolve modules with relative names as if * they were in the same location. For example lets say there are two files * '/local/src/content/file1.ts' * '/shared/components/contracts/src/content/protocols/file2.ts' * After bundling content of '/shared/components/contracts/src' will be merged with '/local/src' so * if file1 has the following import 'import {x} from "./protocols/file2"' it will be resolved successfully in runtime. * 'rootDirs' provides the way to tell compiler that in order to get the whole project it should behave as if content of all * root dirs were merged together. * I.e. for the example above 'rootDirs' will have two entries: [ '/local/src', '/shared/components/contracts/src' ]. * Compiler will first convert './protocols/file2' into absolute path relative to the location of containing file: * '/local/src/content/protocols/file2' and try to load it - failure. * Then it will search 'rootDirs' looking for a longest matching prefix of this absolute path and if such prefix is found - absolute path will * be converted to a path relative to found rootDir entry './content/protocols/file2' (*). As a last step compiler will check all remaining * entries in 'rootDirs', use them to build absolute path out of (*) and try to resolve module from this location. */ function tryLoadModuleUsingOptionalResolutionSettings(moduleName: string, containingDirectory: string, loader: ResolutionKindSpecificLoader, failedLookupLocations: string[], supportedExtensions: string[], state: ModuleResolutionState): string { if (moduleHasNonRelativeName(moduleName)) { return tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state); } else { return tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state); } } function tryLoadModuleUsingRootDirs(moduleName: string, containingDirectory: string, loader: ResolutionKindSpecificLoader, failedLookupLocations: string[], supportedExtensions: string[], state: ModuleResolutionState): string { if (!state.compilerOptions.rootDirs) { return undefined; } if (state.traceEnabled) { trace(state.host, Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName); } const candidate = normalizePath(combinePaths(containingDirectory, moduleName)); let matchedRootDir: string; let matchedNormalizedPrefix: string; for (const rootDir of state.compilerOptions.rootDirs) { // rootDirs are expected to be absolute // in case of tsconfig.json this will happen automatically - compiler will expand relative names // using location of tsconfig.json as base location let normalizedRoot = normalizePath(rootDir); if (!endsWith(normalizedRoot, directorySeparator)) { normalizedRoot += directorySeparator; } const isLongestMatchingPrefix = startsWith(candidate, normalizedRoot) && (matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length); if (state.traceEnabled) { trace(state.host, Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix); } if (isLongestMatchingPrefix) { matchedNormalizedPrefix = normalizedRoot; matchedRootDir = rootDir; } } if (matchedNormalizedPrefix) { if (state.traceEnabled) { trace(state.host, Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix); } const suffix = candidate.substr(matchedNormalizedPrefix.length); // first - try to load from a initial location if (state.traceEnabled) { trace(state.host, Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); } const resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state); if (resolvedFileName) { return resolvedFileName; } if (state.traceEnabled) { trace(state.host, Diagnostics.Trying_other_entries_in_rootDirs); } // then try to resolve using remaining entries in rootDirs for (const rootDir of state.compilerOptions.rootDirs) { if (rootDir === matchedRootDir) { // skip the initially matched entry continue; } const candidate = combinePaths(normalizePath(rootDir), suffix); if (state.traceEnabled) { trace(state.host, Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate); } const baseDirectory = getDirectoryPath(candidate); const resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state); if (resolvedFileName) { return resolvedFileName; } } if (state.traceEnabled) { trace(state.host, Diagnostics.Module_resolution_using_rootDirs_has_failed); } } return undefined; } function tryLoadModuleUsingBaseUrl(moduleName: string, loader: ResolutionKindSpecificLoader, failedLookupLocations: string[], supportedExtensions: string[], state: ModuleResolutionState): string { if (!state.compilerOptions.baseUrl) { return undefined; } if (state.traceEnabled) { trace(state.host, Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName); } let longestMatchPrefixLength = -1; let matchedPattern: string; let matchedStar: string; if (state.compilerOptions.paths) { if (state.traceEnabled) { trace(state.host, Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); } for (const key in state.compilerOptions.paths) { const pattern: string = key; const indexOfStar = pattern.indexOf("*"); if (indexOfStar !== -1) { const prefix = pattern.substr(0, indexOfStar); const suffix = pattern.substr(indexOfStar + 1); if (moduleName.length >= prefix.length + suffix.length && startsWith(moduleName, prefix) && endsWith(moduleName, suffix)) { // use length of prefix as betterness criteria if (prefix.length > longestMatchPrefixLength) { longestMatchPrefixLength = prefix.length; matchedPattern = pattern; matchedStar = moduleName.substr(prefix.length, moduleName.length - suffix.length); } } } else if (pattern === moduleName) { // pattern was matched as is - no need to search further matchedPattern = pattern; matchedStar = undefined; break; } } } if (matchedPattern) { if (state.traceEnabled) { trace(state.host, Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPattern); } for (const subst of state.compilerOptions.paths[matchedPattern]) { const path = matchedStar ? subst.replace("\*", matchedStar) : subst; const candidate = normalizePath(combinePaths(state.compilerOptions.baseUrl, path)); if (state.traceEnabled) { trace(state.host, Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); } const resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(getDirectoryPath(candidate), state.host), state); if (resolvedFileName) { return resolvedFileName; } } return undefined; } else { const candidate = normalizePath(combinePaths(state.compilerOptions.baseUrl, moduleName)); if (state.traceEnabled) { trace(state.host, Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate); } return loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(getDirectoryPath(candidate), state.host), state); } } export function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations { const containingDirectory = getDirectoryPath(containingFile); const supportedExtensions = getSupportedExtensions(compilerOptions); const traceEnabled = isTraceEnabled(compilerOptions, host); const failedLookupLocations: string[] = []; const state = {compilerOptions, host, traceEnabled, skipTsx: false}; let resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, nodeLoadModuleByRelativeName, failedLookupLocations, supportedExtensions, state); if (resolvedFileName) { return createResolvedModule(resolvedFileName, /*isExternalLibraryImport*/false, failedLookupLocations); } let isExternalLibraryImport = false; if (moduleHasNonRelativeName(moduleName)) { if (traceEnabled) { trace(host, Diagnostics.Loading_module_0_from_node_modules_folder, moduleName); } resolvedFileName = loadModuleFromNodeModules(moduleName, containingDirectory, failedLookupLocations, state); isExternalLibraryImport = resolvedFileName !== undefined; } else { const candidate = normalizePath(combinePaths(containingDirectory, moduleName)); resolvedFileName = nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, /*onlyRecordFailures*/ false, state); } return createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations); } function nodeLoadModuleByRelativeName(candidate: string, supportedExtensions: string[], failedLookupLocations: string[], onlyRecordFailures: boolean, state: ModuleResolutionState): string { if (state.traceEnabled) { trace(state.host, Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0, candidate); } const resolvedFileName = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state); return resolvedFileName || loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, onlyRecordFailures, state); } /* @internal */ export function directoryProbablyExists(directoryName: string, host: { directoryExists?: (directoryName: string) => boolean } ): boolean { // if host does not support 'directoryExists' assume that directory will exist return !host.directoryExists || host.directoryExists(directoryName); } /** * @param {boolean} onlyRecordFailures - if true then function won't try to actually load files but instead record all attempts as failures. This flag is necessary * in cases when we know upfront that all load attempts will fail (because containing folder does not exists) however we still need to record all failed lookup locations. */ function loadModuleFromFile(candidate: string, extensions: string[], failedLookupLocation: string[], onlyRecordFailures: boolean, state: ModuleResolutionState): string { return forEach(extensions, tryLoad); function tryLoad(ext: string): string { if (ext === ".tsx" && state.skipTsx) { return undefined; } const fileName = fileExtensionIs(candidate, ext) ? candidate : candidate + ext; if (!onlyRecordFailures && state.host.fileExists(fileName)) { if (state.traceEnabled) { trace(state.host, Diagnostics.File_0_exist_use_it_as_a_module_resolution_result, fileName); } return fileName; } else { if (state.traceEnabled) { trace(state.host, Diagnostics.File_0_does_not_exist, fileName); } failedLookupLocation.push(fileName); return undefined; } } } function loadNodeModuleFromDirectory(extensions: string[], candidate: string, failedLookupLocation: string[], onlyRecordFailures: boolean, state: ModuleResolutionState): string { const packageJsonPath = combinePaths(candidate, "package.json"); const directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); if (directoryExists && state.host.fileExists(packageJsonPath)) { if (state.traceEnabled) { trace(state.host, Diagnostics.Found_package_json_at_0, packageJsonPath); } let jsonContent: { typings?: string }; try { const jsonText = state.host.readFile(packageJsonPath); jsonContent = jsonText ? <{ typings?: string }>JSON.parse(jsonText) : { typings: undefined }; } catch (e) { // gracefully handle if readFile fails or returns not JSON jsonContent = { typings: undefined }; } if (jsonContent.typings) { if (typeof jsonContent.typings === "string") { const typingsFile = normalizePath(combinePaths(candidate, jsonContent.typings)); if (state.traceEnabled) { trace(state.host, Diagnostics.package_json_has_typings_field_0_that_references_1, jsonContent.typings, typingsFile); } const result = loadModuleFromFile(typingsFile, extensions, failedLookupLocation, !directoryProbablyExists(getDirectoryPath(typingsFile), state.host), state); if (result) { return result; } } else if (state.traceEnabled) { trace(state.host, Diagnostics.Expected_type_of_typings_field_in_package_json_to_be_string_got_0, typeof jsonContent.typings); } } else { if (state.traceEnabled) { trace(state.host, Diagnostics.package_json_does_not_have_typings_field); } } } else { if (state.traceEnabled) { trace(state.host, Diagnostics.File_0_does_not_exist, packageJsonPath); } // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results failedLookupLocation.push(packageJsonPath); } return loadModuleFromFile(combinePaths(candidate, "index"), extensions, failedLookupLocation, !directoryExists, state); } function loadModuleFromNodeModules(moduleName: string, directory: string, failedLookupLocations: string[], state: ModuleResolutionState): string { directory = normalizeSlashes(directory); while (true) { const baseName = getBaseFileName(directory); if (baseName !== "node_modules") { const nodeModulesFolder = combinePaths(directory, "node_modules"); const nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); const candidate = normalizePath(combinePaths(nodeModulesFolder, moduleName)); // Load only typescript files irrespective of allowJs option if loading from node modules let result = loadModuleFromFile(candidate, supportedTypeScriptExtensions, failedLookupLocations, !nodeModulesFolderExists, state); if (result) { return result; } result = loadNodeModuleFromDirectory(supportedTypeScriptExtensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state); if (result) { return result; } } const parentPath = getDirectoryPath(directory); if (parentPath === directory) { break; } directory = parentPath; } return undefined; } export function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations { const traceEnabled = isTraceEnabled(compilerOptions, host); const state = { compilerOptions, host, traceEnabled, skipTsx: !compilerOptions.jsx }; const failedLookupLocations: string[] = []; const supportedExtensions = getSupportedExtensions(compilerOptions); let containingDirectory = getDirectoryPath(containingFile); const resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loadModuleFromFile, failedLookupLocations, supportedExtensions, state); if (resolvedFileName) { return createResolvedModule(resolvedFileName, /*isExternalLibraryImport*/false, failedLookupLocations); } let referencedSourceFile: string; if (moduleHasNonRelativeName(moduleName)) { while (true) { const searchName = normalizePath(combinePaths(containingDirectory, moduleName)); referencedSourceFile = loadModuleFromFile(searchName, supportedExtensions, failedLookupLocations, /*onlyRecordFailures*/ false, state); if (referencedSourceFile) { break; } const parentPath = getDirectoryPath(containingDirectory); if (parentPath === containingDirectory) { break; } containingDirectory = parentPath; } } else { const candidate = normalizePath(combinePaths(containingDirectory, moduleName)); referencedSourceFile = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, /*onlyRecordFailures*/ false, state); } return referencedSourceFile ? { resolvedModule: { resolvedFileName: referencedSourceFile }, failedLookupLocations } : { resolvedModule: undefined, failedLookupLocations }; } /* @internal */ export const defaultInitCompilerOptions: CompilerOptions = { module: ModuleKind.CommonJS, target: ScriptTarget.ES5, noImplicitAny: false, sourceMap: false, }; export function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost { const existingDirectories: Map<boolean> = {}; function getCanonicalFileName(fileName: string): string { // if underlying system can distinguish between two files whose names differs only in cases then file name already in canonical form. // otherwise use toLowerCase as a canonical form. return sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); } // returned by CScript sys environment const unsupportedFileEncodingErrorCode = -2147024809; function getSourceFile(fileName: string, languageVersion: ScriptTarget, onError?: (message: string) => void): SourceFile { let text: string; try { const start = new Date().getTime(); text = sys.readFile(fileName, options.charset); ioReadTime += new Date().getTime() - start; } catch (e) { if (onError) { onError(e.number === unsupportedFileEncodingErrorCode ? createCompilerDiagnostic(Diagnostics.Unsupported_file_encoding).messageText : e.message); } text = ""; } return text !== undefined ? createSourceFile(fileName, text, languageVersion, setParentNodes) : undefined; } function directoryExists(directoryPath: string): boolean { if (hasProperty(existingDirectories, directoryPath)) { return true; } if (sys.directoryExists(directoryPath)) { existingDirectories[directoryPath] = true; return true; } return false; } function ensureDirectoriesExist(directoryPath: string) { if (directoryPath.length > getRootLength(directoryPath) && !directoryExists(directoryPath)) { const parentDirectory = getDirectoryPath(directoryPath); ensureDirectoriesExist(parentDirectory); sys.createDirectory(directoryPath); } } function writeFile(fileName: string, data: string, writeByteOrderMark: boolean, onError?: (message: string) => void) { try { const start = new Date().getTime(); ensureDirectoriesExist(getDirectoryPath(normalizePath(fileName))); sys.writeFile(fileName, data, writeByteOrderMark); ioWriteTime += new Date().getTime() - start; } catch (e) { if (onError) { onError(e.message); } } } const newLine = getNewLineCharacter(options); return { getSourceFile, getDefaultLibFileName: options => combinePaths(getDirectoryPath(normalizePath(sys.getExecutingFilePath())), getDefaultLibFileName(options)), writeFile, getCurrentDirectory: memoize(() => sys.getCurrentDirectory()), useCaseSensitiveFileNames: () => sys.useCaseSensitiveFileNames, getCanonicalFileName, getNewLine: () => newLine, fileExists: fileName => sys.fileExists(fileName), readFile: fileName => sys.readFile(fileName), trace: (s: string) => sys.write(s + newLine), directoryExists: directoryName => sys.directoryExists(directoryName) }; } export function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[] { let diagnostics = program.getOptionsDiagnostics(cancellationToken).concat( program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); if (program.getCompilerOptions().declaration) { diagnostics = diagnostics.concat(program.getDeclarationDiagnostics(sourceFile, cancellationToken)); } return sortAndDeduplicateDiagnostics(diagnostics); } export function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string { if (typeof messageText === "string") { return messageText; } else { let diagnosticChain = messageText; let result = ""; let indent = 0; while (diagnosticChain) { if (indent) { result += newLine; for (let i = 0; i < indent; i++) { result += " "; } } result += diagnosticChain.messageText; indent++; diagnosticChain = diagnosticChain.next; } return result; } } export function createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost, oldProgram?: Program): Program { let program: Program; let files: SourceFile[] = []; let fileProcessingDiagnostics = createDiagnosticCollection(); const programDiagnostics = createDiagnosticCollection(); let commonSourceDirectory: string; let diagnosticsProducingTypeChecker: TypeChecker; let noDiagnosticsTypeChecker: TypeChecker; let classifiableNames: Map<string>; let skipDefaultLib = options.noLib; const supportedExtensions = getSupportedExtensions(options); const start = new Date().getTime(); host = host || createCompilerHost(options); // Map storing if there is emit blocking diagnostics for given input const hasEmitBlockingDiagnostics = createFileMap<boolean>(getCanonicalFileName); const currentDirectory = host.getCurrentDirectory(); const resolveModuleNamesWorker = host.resolveModuleNames ? ((moduleNames: string[], containingFile: string) => host.resolveModuleNames(moduleNames, containingFile)) : ((moduleNames: string[], containingFile: string) => { const resolvedModuleNames: ResolvedModule[] = []; // resolveModuleName does not store any results between calls. // lookup is a local cache to avoid resolving the same module name several times const lookup: Map<ResolvedModule> = {}; for (const moduleName of moduleNames) { let resolvedName: ResolvedModule; if (hasProperty(lookup, moduleName)) { resolvedName = lookup[moduleName]; } else { resolvedName = resolveModuleName(moduleName, containingFile, options, host).resolvedModule; lookup[moduleName] = resolvedName; } resolvedModuleNames.push(resolvedName); } return resolvedModuleNames; }); const filesByName = createFileMap<SourceFile>(); // stores 'filename -> file association' ignoring case // used to track cases when two file names differ only in casing const filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? createFileMap<SourceFile>(fileName => fileName.toLowerCase()) : undefined; if (oldProgram) { // check properties that can affect structure of the program or module resolution strategy // if any of these properties has changed - structure cannot be reused const oldOptions = oldProgram.getCompilerOptions(); if ((oldOptions.module !== options.module) || (oldOptions.noResolve !== options.noResolve) || (oldOptions.target !== options.target) || (oldOptions.noLib !== options.noLib) || (oldOptions.jsx !== options.jsx) || (oldOptions.allowJs !== options.allowJs)) { oldProgram = undefined; } } if (!tryReuseStructureFromOldProgram()) { forEach(rootNames, name => processRootFile(name, /*isDefaultLib*/ false)); // Do not process the default library if: // - The '--noLib' flag is used. // - A 'no-default-lib' reference comment is encountered in // processing the root files. if (!skipDefaultLib) { processRootFile(host.getDefaultLibFileName(options), /*isDefaultLib*/ true); } } // unconditionally set oldProgram to undefined to prevent it from being captured in closure oldProgram = undefined; program = { getRootFileNames: () => rootNames, getSourceFile, getSourceFiles: () => files, getCompilerOptions: () => options, getSyntacticDiagnostics, getOptionsDiagnostics, getGlobalDiagnostics, getSemanticDiagnostics, getDeclarationDiagnostics, getTypeChecker, getClassifiableNames, getDiagnosticsProducingTypeChecker, getCommonSourceDirectory, emit, getCurrentDirectory: () => currentDirectory, getNodeCount: () => getDiagnosticsProducingTypeChecker().getNodeCount(), getIdentifierCount: () => getDiagnosticsProducingTypeChecker().getIdentifierCount(), getSymbolCount: () => getDiagnosticsProducingTypeChecker().getSymbolCount(), getTypeCount: () => getDiagnosticsProducingTypeChecker().getTypeCount(), getFileProcessingDiagnostics: () => fileProcessingDiagnostics }; verifyCompilerOptions(); programTime += new Date().getTime() - start; return program; function getCommonSourceDirectory() { if (typeof commonSourceDirectory === "undefined") { if (options.rootDir && checkSourceFilesBelongToPath(files, options.rootDir)) { // If a rootDir is specified and is valid use it as the commonSourceDirectory commonSourceDirectory = getNormalizedAbsolutePath(options.rootDir, currentDirectory); } else { commonSourceDirectory = computeCommonSourceDirectory(files); } if (commonSourceDirectory && commonSourceDirectory[commonSourceDirectory.length - 1] !== directorySeparator) { // Make sure directory path ends with directory separator so this string can directly // used to replace with "" to get the relative path of the source file and the relative path doesn't // start with / making it rooted path commonSourceDirectory += directorySeparator; } } return commonSourceDirectory; } function getClassifiableNames() { if (!classifiableNames) { // Initialize a checker so that all our files are bound. getTypeChecker(); classifiableNames = {}; for (const sourceFile of files) { copyMap(sourceFile.classifiableNames, classifiableNames); } } return classifiableNames; } function tryReuseStructureFromOldProgram(): boolean { if (!oldProgram) { return false; } Debug.assert(!oldProgram.structureIsReused); // there is an old program, check if we can reuse its structure const oldRootNames = oldProgram.getRootFileNames(); if (!arrayIsEqualTo(oldRootNames, rootNames)) { return false; } // check if program source files has changed in the way that can affect structure of the program const newSourceFiles: SourceFile[] = []; const filePaths: Path[] = []; const modifiedSourceFiles: SourceFile[] = []; for (const oldSourceFile of oldProgram.getSourceFiles()) { let newSourceFile = host.getSourceFile(oldSourceFile.fileName, options.target); if (!newSourceFile) { return false; } newSourceFile.path = oldSourceFile.path; filePaths.push(newSourceFile.path); if (oldSourceFile !== newSourceFile) { if (oldSourceFile.hasNoDefaultLib !== newSourceFile.hasNoDefaultLib) { // value of no-default-lib has changed // this will affect if default library is injected into the list of files return false; } // check tripleslash references if (!arrayIsEqualTo(oldSourceFile.referencedFiles, newSourceFile.referencedFiles, fileReferenceIsEqualTo)) { // tripleslash references has changed return false; } // check imports and module augmentations collectExternalModuleReferences(newSourceFile); if (!arrayIsEqualTo(oldSourceFile.imports, newSourceFile.imports, moduleNameIsEqualTo)) { // imports has changed return false; } if (!arrayIsEqualTo(oldSourceFile.moduleAugmentations, newSourceFile.moduleAugmentations, moduleNameIsEqualTo)) { // moduleAugmentations has changed return false; } if (resolveModuleNamesWorker) { const moduleNames = map(concatenate(newSourceFile.imports, newSourceFile.moduleAugmentations), getTextOfLiteral); const resolutions = resolveModuleNamesWorker(moduleNames, getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory)); // ensure that module resolution results are still correct for (let i = 0; i < moduleNames.length; i++) { const newResolution = resolutions[i]; const oldResolution = getResolvedModule(oldSourceFile, moduleNames[i]); const resolutionChanged = oldResolution ? !newResolution || oldResolution.resolvedFileName !== newResolution.resolvedFileName || !!oldResolution.isExternalLibraryImport !== !!newResolution.isExternalLibraryImport : newResolution; if (resolutionChanged) { return false; } } } // pass the cache of module resolutions from the old source file newSourceFile.resolvedModules = oldSourceFile.resolvedModules; modifiedSourceFiles.push(newSourceFile); } else { // file has no changes - use it as is newSourceFile = oldSourceFile; } // if file has passed all checks it should be safe to reuse it newSourceFiles.push(newSourceFile); } // update fileName -> file mapping for (let i = 0, len = newSourceFiles.length; i < len; i++) { filesByName.set(filePaths[i], newSourceFiles[i]); } files = newSourceFiles; fileProcessingDiagnostics = oldProgram.getFileProcessingDiagnostics(); for (const modifiedFile of modifiedSourceFiles) { fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile); } oldProgram.structureIsReused = true; return true; } function getEmitHost(writeFileCallback?: WriteFileCallback): EmitHost { return { getCanonicalFileName, getCommonSourceDirectory: program.getCommonSourceDirectory, getCompilerOptions: program.getCompilerOptions, getCurrentDirectory: () => currentDirectory, getNewLine: () => host.getNewLine(), getSourceFile: program.getSourceFile, getSourceFiles: program.getSourceFiles, writeFile: writeFileCallback || ( (fileName, data, writeByteOrderMark, onError) => host.writeFile(fileName, data, writeByteOrderMark, onError)), isEmitBlocked, }; } function getDiagnosticsProducingTypeChecker() { return diagnosticsProducingTypeChecker || (diagnosticsProducingTypeChecker = createTypeChecker(program, /*produceDiagnostics:*/ true)); } function getTypeChecker() { return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = createTypeChecker(program, /*produceDiagnostics:*/ false)); } function emit(sourceFile?: SourceFile, writeFileCallback?: WriteFileCallback, cancellationToken?: CancellationToken): EmitResult { return runWithCancellationToken(() => emitWorker(this, sourceFile, writeFileCallback, cancellationToken)); } function isEmitBlocked(emitFileName: string): boolean { return hasEmitBlockingDiagnostics.contains(toPath(emitFileName, currentDirectory, getCanonicalFileName)); } function emitWorker(program: Program, sourceFile: SourceFile, writeFileCallback: WriteFileCallback, cancellationToken: CancellationToken): EmitResult { let declarationDiagnostics: Diagnostic[] = []; if (options.noEmit) { return { diagnostics: declarationDiagnostics, sourceMaps: undefined, emitSkipped: true }; } // If the noEmitOnError flag is set, then check if we have any errors so far. If so, // immediately bail out. Note that we pass 'undefined' for 'sourceFile' so that we // get any preEmit diagnostics, not just the ones if (options.noEmitOnError) { const diagnostics = program.getOptionsDiagnostics(cancellationToken).concat( program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); if (diagnostics.length === 0 && program.getCompilerOptions().declaration) { declarationDiagnostics = program.getDeclarationDiagnostics(/*sourceFile*/ undefined, cancellationToken); } if (diagnostics.length > 0 || declarationDiagnostics.length > 0) { return { diagnostics, sourceMaps: undefined, emitSkipped: true }; } } // Create the emit resolver outside of the "emitTime" tracking code below. That way // any cost associated with it (like type checking) are appropriate associated with // the type-checking counter. // // If the -out option is specified, we should not pass the source file to getEmitResolver. // This is because in the -out scenario all files need to be emitted, and therefore all // files need to be type checked. And the way to specify that all files need to be type // checked is to not pass the file to getEmitResolver. const emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile); const start = new Date().getTime(); const emitResult = emitFiles( emitResolver, getEmitHost(writeFileCallback), sourceFile); emitTime += new Date().getTime() - start; return emitResult; } function getSourceFile(fileName: string): SourceFile { return filesByName.get(toPath(fileName, currentDirectory, getCanonicalFileName)); } function getDiagnosticsHelper( sourceFile: SourceFile, getDiagnostics: (sourceFile: SourceFile, cancellationToken: CancellationToken) => Diagnostic[], cancellationToken: CancellationToken): Diagnostic[] { if (sourceFile) { return getDiagnostics(sourceFile, cancellationToken); } const allDiagnostics: Diagnostic[] = []; forEach(program.getSourceFiles(), sourceFile => { if (cancellationToken) { cancellationToken.throwIfCancellationRequested(); } addRange(allDiagnostics, getDiagnostics(sourceFile, cancellationToken)); }); return sortAndDeduplicateDiagnostics(allDiagnostics); } function getSyntacticDiagnostics(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] { return getDiagnosticsHelper(sourceFile, getSyntacticDiagnosticsForFile, cancellationToken); } function getSemanticDiagnostics(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] { return getDiagnosticsHelper(sourceFile, getSemanticDiagnosticsForFile, cancellationToken); } function getDeclarationDiagnostics(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] { return getDiagnosticsHelper(sourceFile, getDeclarationDiagnosticsForFile, cancellationToken); } function getSyntacticDiagnosticsForFile(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] { return sourceFile.parseDiagnostics; } function runWithCancellationToken<T>(func: () => T): T { try { return func(); } catch (e) { if (e instanceof OperationCanceledException) { // We were canceled while performing the operation. Because our type checker // might be a bad state, we need to throw it away. // // Note: we are overly aggressive here. We do not actually *have* to throw away // the "noDiagnosticsTypeChecker". However, for simplicity, i'd like to keep // the lifetimes of these two TypeCheckers the same. Also, we generally only // cancel when the user has made a change anyways. And, in that case, we (the // program instance) will get thrown away anyways. So trying to keep one of // these type checkers alive doesn't serve much purpose. noDiagnosticsTypeChecker = undefined; diagnosticsProducingTypeChecker = undefined; } throw e; } } function getSemanticDiagnosticsForFile(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] { return runWithCancellationToken(() => { const typeChecker = getDiagnosticsProducingTypeChecker(); Debug.assert(!!sourceFile.bindDiagnostics); const bindDiagnostics = sourceFile.bindDiagnostics; // For JavaScript files, we don't want to report the normal typescript semantic errors. // Instead, we just report errors for using TypeScript-only constructs from within a // JavaScript file. const checkDiagnostics = isSourceFileJavaScript(sourceFile) ? getJavaScriptSemanticDiagnosticsForFile(sourceFile, cancellationToken) : typeChecker.getDiagnostics(sourceFile, cancellationToken); const fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName); const programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName); return bindDiagnostics.concat(checkDiagnostics).concat(fileProcessingDiagnosticsInFile).concat(programDiagnosticsInFile); }); } function getJavaScriptSemanticDiagnosticsForFile(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] { return runWithCancellationToken(() => { const diagnostics: Diagnostic[] = []; walk(sourceFile); return diagnostics; function walk(node: Node): boolean { if (!node) { return false; } switch (node.kind) { case SyntaxKind.ImportEqualsDeclaration: diagnostics.push(createDiagnosticForNode(node, Diagnostics.import_can_only_be_used_in_a_ts_file)); return true; case SyntaxKind.ExportAssignment: if ((<ExportAssignment>node).isExportEquals) { diagnostics.push(createDiagnosticForNode(node, Diagnostics.export_can_only_be_used_in_a_ts_file)); return true; } break; case SyntaxKind.ClassDeclaration: let classDeclaration = <ClassDeclaration>node; if (checkModifiers(classDeclaration.modifiers) || checkTypeParameters(classDeclaration.typeParameters)) { return true; } break; case SyntaxKind.HeritageClause: let heritageClause = <HeritageClause>node; if (heritageClause.token === SyntaxKind.ImplementsKeyword) { diagnostics.push(createDiagnosticForNode(node, Diagnostics.implements_clauses_can_only_be_used_in_a_ts_file)); return true; } break; case SyntaxKind.InterfaceDeclaration: diagnostics.push(createDiagnosticForNode(node, Diagnostics.interface_declarations_can_only_be_used_in_a_ts_file)); return true; case SyntaxKind.ModuleDeclaration: diagnostics.push(createDiagnosticForNode(node, Diagnostics.module_declarations_can_only_be_used_in_a_ts_file)); return true; case SyntaxKind.TypeAliasDeclaration: diagnostics.push(createDiagnosticForNode(node, Diagnostics.type_aliases_can_only_be_used_in_a_ts_file)); return true; case SyntaxKind.MethodDeclaration: case SyntaxKind.MethodSignature: case SyntaxKind.Constructor: case SyntaxKind.GetAccessor: case SyntaxKind.SetAccessor: case SyntaxKind.FunctionExpression: case SyntaxKind.FunctionDeclaration: case SyntaxKind.ArrowFunction: case SyntaxKind.FunctionDeclaration: const functionDeclaration = <FunctionLikeDeclaration>node; if (checkModifiers(functionDeclaration.modifiers) || checkTypeParameters(functionDeclaration.typeParameters) || checkTypeAnnotation(functionDeclaration.type)) { return true; } break; case SyntaxKind.VariableStatement: const variableStatement = <VariableStatement>node; if (checkModifiers(variableStatement.modifiers)) { return true; } break; case SyntaxKind.VariableDeclaration: const variableDeclaration = <VariableDeclaration>node; if (checkTypeAnnotation(variableDeclaration.type)) { return true; } break; case SyntaxKind.CallExpression: case SyntaxKind.NewExpression: const expression = <CallExpression>node; if (expression.typeArguments && expression.typeArguments.length > 0) { const start = expression.typeArguments.pos; diagnostics.push(createFileDiagnostic(sourceFile, start, expression.typeArguments.end - start, Diagnostics.type_arguments_can_only_be_used_in_a_ts_file)); return true; } break; case SyntaxKind.Parameter: const parameter = <ParameterDeclaration>node; if (parameter.modifiers) { const start = parameter.modifiers.pos; diagnostics.push(createFileDiagnostic(sourceFile, start, parameter.modifiers.end - start, Diagnostics.parameter_modifiers_can_only_be_used_in_a_ts_file)); return true; } if (parameter.questionToken) { diagnostics.push(createDiagnosticForNode(parameter.questionToken, Diagnostics._0_can_only_be_used_in_a_ts_file, "?")); return true; } if (parameter.type) { diagnostics.push(createDiagnosticForNode(parameter.type, Diagnostics.types_can_only_be_used_in_a_ts_file)); return true; } break; case SyntaxKind.PropertyDeclaration: diagnostics.push(createDiagnosticForNode(node, Diagnostics.property_declarations_can_only_be_used_in_a_ts_file)); return true; case SyntaxKind.EnumDeclaration: diagnostics.push(createDiagnosticForNode(node, Diagnostics.enum_declarations_can_only_be_used_in_a_ts_file)); return true; case SyntaxKind.TypeAssertionExpression: let typeAssertionExpression = <TypeAssertion>node; diagnostics.push(createDiagnosticForNode(typeAssertionExpression.type, Diagnostics.type_assertion_expressions_can_only_be_used_in_a_ts_file)); return true; case SyntaxKind.Decorator: if (!options.experimentalDecorators) { diagnostics.push(createDiagnosticForNode(node, Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning)); } return true; } return forEachChild(node, walk); } function checkTypeParameters(typeParameters: NodeArray<TypeParameterDeclaration>): boolean { if (typeParameters) { const start = typeParameters.pos; diagnostics.push(createFileDiagnostic(sourceFile, start, typeParameters.end - start, Diagnostics.type_parameter_declarations_can_only_be_used_in_a_ts_file)); return true; } return false; } function checkTypeAnnotation(type: TypeNode): boolean { if (type) { diagnostics.push(createDiagnosticForNode(type, Diagnostics.types_can_only_be_used_in_a_ts_file)); return true; } return false; } function checkModifiers(modifiers: ModifiersArray): boolean { if (modifiers) { for (const modifier of modifiers) { switch (modifier.kind) { case SyntaxKind.PublicKeyword: case SyntaxKind.PrivateKeyword: case SyntaxKind.ProtectedKeyword: case SyntaxKind.ReadonlyKeyword: case SyntaxKind.DeclareKeyword: diagnostics.push(createDiagnosticForNode(modifier, Diagnostics._0_can_only_be_used_in_a_ts_file, tokenToString(modifier.kind))); return true; // These are all legal modifiers. case SyntaxKind.StaticKeyword: case SyntaxKind.ExportKeyword: case SyntaxKind.ConstKeyword: case SyntaxKind.DefaultKeyword: case SyntaxKind.AbstractKeyword: } } } return false; } }); } function getDeclarationDiagnosticsForFile(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] { return runWithCancellationToken(() => { if (!isDeclarationFile(sourceFile)) { const resolver = getDiagnosticsProducingTypeChecker().getEmitResolver(sourceFile, cancellationToken); // Don't actually write any files since we're just getting diagnostics. const writeFile: WriteFileCallback = () => { }; return ts.getDeclarationDiagnostics(getEmitHost(writeFile), resolver, sourceFile); } }); } function getOptionsDiagnostics(): Diagnostic[] { const allDiagnostics: Diagnostic[] = []; addRange(allDiagnostics, fileProcessingDiagnostics.getGlobalDiagnostics()); addRange(allDiagnostics, programDiagnostics.getGlobalDiagnostics()); return sortAndDeduplicateDiagnostics(allDiagnostics); } function getGlobalDiagnostics(): Diagnostic[] { const allDiagnostics: Diagnostic[] = []; addRange(allDiagnostics, getDiagnosticsProducingTypeChecker().getGlobalDiagnostics()); return sortAndDeduplicateDiagnostics(allDiagnostics); } function hasExtension(fileName: string): boolean { return getBaseFileName(fileName).indexOf(".") >= 0; } function processRootFile(fileName: string, isDefaultLib: boolean) { processSourceFile(normalizePath(fileName), isDefaultLib); } function fileReferenceIsEqualTo(a: FileReference, b: FileReference): boolean { return a.fileName === b.fileName; } function moduleNameIsEqualTo(a: LiteralExpression, b: LiteralExpression): boolean { return a.text === b.text; } function getTextOfLiteral(literal: LiteralExpression): string { return literal.text; } function collectExternalModuleReferences(file: SourceFile): void { if (file.imports) { return; } const isJavaScriptFile = isSourceFileJavaScript(file); const isExternalModuleFile = isExternalModule(file); let imports: LiteralExpression[]; let moduleAugmentations: LiteralExpression[]; for (const node of file.statements) { collectModuleReferences(node, /*inAmbientModule*/ false); if (isJavaScriptFile) { collectRequireCalls(node); } } file.imports = imports || emptyArray; file.moduleAugmentations = moduleAugmentations || emptyArray; return; function collectModuleReferences(node: Node, inAmbientModule: boolean): void { switch (node.kind) { case SyntaxKind.ImportDeclaration: case SyntaxKind.ImportEqualsDeclaration: case SyntaxKind.ExportDeclaration: let moduleNameExpr = getExternalModuleName(node); if (!moduleNameExpr || moduleNameExpr.kind !== SyntaxKind.StringLiteral) { break; } if (!(<LiteralExpression>moduleNameExpr).text) { break; } // TypeScript 1.0 spec (April 2014): 12.1.6 // An ExternalImportDeclaration in an AmbientExternalModuleDeclaration may reference other external modules // only through top - level external module names. Relative external module names are not permitted. if (!inAmbientModule || !isExternalModuleNameRelative((<LiteralExpression>moduleNameExpr).text)) { (imports || (imports = [])).push(<LiteralExpression>moduleNameExpr); } break; case SyntaxKind.ModuleDeclaration: if (isAmbientModule(<ModuleDeclaration>node) && (inAmbientModule || node.flags & NodeFlags.Ambient || isDeclarationFile(file))) { const moduleName = <LiteralExpression>(<ModuleDeclaration>node).name; // Ambient module declarations can be interpreted as augmentations for some existing external modules. // This will happen in two cases: // - if current file is external module then module augmentation is a ambient module declaration defined in the top level scope // - if current file is not external module then module augmentation is an ambient module declaration with non-relative module name // immediately nested in top level ambient module declaration . if (isExternalModuleFile || (inAmbientModule && !isExternalModuleNameRelative(moduleName.text))) { (moduleAugmentations || (moduleAugmentations = [])).push(moduleName); } else if (!inAmbientModule) { // An AmbientExternalModuleDeclaration declares an external module. // This type of declaration is permitted only in the global module. // The StringLiteral must specify a top - level external module name. // Relative external module names are not permitted // NOTE: body of ambient module is always a module block for (const statement of (<ModuleBlock>(<ModuleDeclaration>node).body).statements) { collectModuleReferences(statement, /*inAmbientModule*/ true); } } } } } function collectRequireCalls(node: Node): void { if (isRequireCall(node, /*checkArgumentIsStringLiteral*/true)) { (imports || (imports = [])).push(<StringLiteral>(<CallExpression>node).arguments[0]); } else { forEachChild(node, collectRequireCalls); } } } function processSourceFile(fileName: string, isDefaultLib: boolean, refFile?: SourceFile, refPos?: number, refEnd?: number) { let diagnosticArgument: string[]; let diagnostic: DiagnosticMessage; if (hasExtension(fileName)) { if (!options.allowNonTsExtensions && !forEach(supportedExtensions, extension => fileExtensionIs(host.getCanonicalFileName(fileName), extension))) { diagnostic = Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1; diagnosticArgument = [fileName, "'" + supportedExtensions.join("', '") + "'"]; } else if (!findSourceFile(fileName, toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd)) { diagnostic = Diagnostics.File_0_not_found; diagnosticArgument = [fileName]; } else if (refFile && host.getCanonicalFileName(fileName) === host.getCanonicalFileName(refFile.fileName)) { diagnostic = Diagnostics.A_file_cannot_have_a_reference_to_itself; diagnosticArgument = [fileName]; } } else { const nonTsFile: SourceFile = options.allowNonTsExtensions && findSourceFile(fileName, toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); if (!nonTsFile) { if (options.allowNonTsExtensions) { diagnostic = Diagnostics.File_0_not_found; diagnosticArgument = [fileName]; } else if (!forEach(supportedExtensions, extension => findSourceFile(fileName + extension, toPath(fileName + extension, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd))) { diagnostic = Diagnostics.File_0_not_found; fileName += ".ts"; diagnosticArgument = [fileName]; } } } if (diagnostic) { if (refFile !== undefined && refEnd !== undefined && refPos !== undefined) { fileProcessingDiagnostics.add(createFileDiagnostic(refFile, refPos, refEnd - refPos, diagnostic, ...diagnosticArgument)); } else { fileProcessingDiagnostics.add(createCompilerDiagnostic(diagnostic, ...diagnosticArgument)); } } } function reportFileNamesDifferOnlyInCasingError(fileName: string, existingFileName: string, refFile: SourceFile, refPos: number, refEnd: number): void { if (refFile !== undefined && refPos !== undefined && refEnd !== undefined) { fileProcessingDiagnostics.add(createFileDiagnostic(refFile, refPos, refEnd - refPos, Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, existingFileName)); } else { fileProcessingDiagnostics.add(createCompilerDiagnostic(Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, existingFileName)); } } // Get source file from normalized fileName function findSourceFile(fileName: string, path: Path, isDefaultLib: boolean, refFile?: SourceFile, refPos?: number, refEnd?: number): SourceFile { if (filesByName.contains(path)) { const file = filesByName.get(path); // try to check if we've already seen this file but with a different casing in path // NOTE: this only makes sense for case-insensitive file systems if (file && options.forceConsistentCasingInFileNames && getNormalizedAbsolutePath(file.fileName, currentDirectory) !== getNormalizedAbsolutePath(fileName, currentDirectory)) { reportFileNamesDifferOnlyInCasingError(fileName, file.fileName, refFile, refPos, refEnd); } return file; } // We haven't looked for this file, do so now and cache result const file = host.getSourceFile(fileName, options.target, hostErrorMessage => { if (refFile !== undefined && refPos !== undefined && refEnd !== undefined) { fileProcessingDiagnostics.add(createFileDiagnostic(refFile, refPos, refEnd - refPos, Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage)); } else { fileProcessingDiagnostics.add(createCompilerDiagnostic(Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage)); } }); filesByName.set(path, file); if (file) { file.path = path; if (host.useCaseSensitiveFileNames()) { // for case-sensitive file systems check if we've already seen some file with similar filename ignoring case const existingFile = filesByNameIgnoreCase.get(path); if (existingFile) { reportFileNamesDifferOnlyInCasingError(fileName, existingFile.fileName, refFile, refPos, refEnd); } else { filesByNameIgnoreCase.set(path, file); } } skipDefaultLib = skipDefaultLib || file.hasNoDefaultLib; const basePath = getDirectoryPath(fileName); if (!options.noResolve) { processReferencedFiles(file, basePath); } // always process imported modules to record module name resolutions processImportedModules(file, basePath); if (isDefaultLib) { files.unshift(file); } else { files.push(file); } } return file; } function processReferencedFiles(file: SourceFile, basePath: string) { forEach(file.referencedFiles, ref => { const referencedFileName = resolveTripleslashReference(ref.fileName, file.fileName); processSourceFile(referencedFileName, /*isDefaultLib*/ false, file, ref.pos, ref.end); }); } function getCanonicalFileName(fileName: string): string { return host.getCanonicalFileName(fileName); } function processImportedModules(file: SourceFile, basePath: string) { collectExternalModuleReferences(file); if (file.imports.length || file.moduleAugmentations.length) { file.resolvedModules = {}; const moduleNames = map(concatenate(file.imports, file.moduleAugmentations), getTextOfLiteral); const resolutions = resolveModuleNamesWorker(moduleNames, getNormalizedAbsolutePath(file.fileName, currentDirectory)); for (let i = 0; i < moduleNames.length; i++) { const resolution = resolutions[i]; setResolvedModule(file, moduleNames[i], resolution); // add file to program only if: // - resolution was successful // - noResolve is falsy // - module name come from the list fo imports const shouldAddFile = resolution && !options.noResolve && i < file.imports.length; if (shouldAddFile) { const importedFile = findSourceFile(resolution.resolvedFileName, toPath(resolution.resolvedFileName, currentDirectory, getCanonicalFileName), /*isDefaultLib*/ false, file, skipTrivia(file.text, file.imports[i].pos), file.imports[i].end); if (importedFile && resolution.isExternalLibraryImport) { // Since currently irrespective of allowJs, we only look for supportedTypeScript extension external module files, // this check is ok. Otherwise this would be never true for javascript file if (!isExternalModule(importedFile) && importedFile.statements.length) { const start = getTokenPosOfNode(file.imports[i], file); fileProcessingDiagnostics.add(createFileDiagnostic(file, start, file.imports[i].end - start, Diagnostics.Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_the_package_definition, importedFile.fileName)); } else if (importedFile.referencedFiles.length) { const firstRef = importedFile.referencedFiles[0]; fileProcessingDiagnostics.add(createFileDiagnostic(importedFile, firstRef.pos, firstRef.end - firstRef.pos, Diagnostics.Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_package_author_to_update_the_package_definition)); } } } } } else { // no imports - drop cached module resolutions file.resolvedModules = undefined; } return; } function computeCommonSourceDirectory(sourceFiles: SourceFile[]): string { let commonPathComponents: string[]; const failed = forEach(files, sourceFile => { // Each file contributes into common source file path if (isDeclarationFile(sourceFile)) { return; } const sourcePathComponents = getNormalizedPathComponents(sourceFile.fileName, currentDirectory); sourcePathComponents.pop(); // The base file name is not part of the common directory path if (!commonPathComponents) { // first file commonPathComponents = sourcePathComponents; return; } for (let i = 0, n = Math.min(commonPathComponents.length, sourcePathComponents.length); i < n; i++) { if (getCanonicalFileName(commonPathComponents[i]) !== getCanonicalFileName(sourcePathComponents[i])) { if (i === 0) { // Failed to find any common path component return true; } // New common path found that is 0 -> i-1 commonPathComponents.length = i; break; } } // If the sourcePathComponents was shorter than the commonPathComponents, truncate to the sourcePathComponents if (sourcePathComponents.length < commonPathComponents.length) { commonPathComponents.length = sourcePathComponents.length; } }); // A common path can not be found when paths span multiple drives on windows, for example if (failed) { return ""; } if (!commonPathComponents) { // Can happen when all input files are .d.ts files return currentDirectory; } return getNormalizedPathFromPathComponents(commonPathComponents); } function checkSourceFilesBelongToPath(sourceFiles: SourceFile[], rootDirectory: string): boolean { let allFilesBelongToPath = true; if (sourceFiles) { const absoluteRootDirectoryPath = host.getCanonicalFileName(getNormalizedAbsolutePath(rootDirectory, currentDirectory)); for (const sourceFile of sourceFiles) { if (!isDeclarationFile(sourceFile)) { const absoluteSourceFilePath = host.getCanonicalFileName(getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, options.rootDir)); allFilesBelongToPath = false; } } } } return allFilesBelongToPath; } function verifyCompilerOptions() { if (options.isolatedModules) { if (options.declaration) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "declaration", "isolatedModules")); } if (options.noEmitOnError) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmitOnError", "isolatedModules")); } if (options.out) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "isolatedModules")); } if (options.outFile) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "outFile", "isolatedModules")); } } if (options.inlineSourceMap) { if (options.sourceMap) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "sourceMap", "inlineSourceMap")); } if (options.mapRoot) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "mapRoot", "inlineSourceMap")); } } if (options.paths && options.baseUrl === undefined) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_paths_cannot_be_used_without_specifying_baseUrl_option)); } if (options.paths) { for (const key in options.paths) { if (!hasProperty(options.paths, key)) { continue; } if (!hasZeroOrOneAsteriskCharacter(key)) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, key)); } for (const subst of options.paths[key]) { if (!hasZeroOrOneAsteriskCharacter(subst)) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character, subst, key)); } } } } if (options.inlineSources) { if (!options.sourceMap && !options.inlineSourceMap) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_inlineSources_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided)); } if (options.sourceRoot) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "sourceRoot", "inlineSources")); } } if (options.out && options.outFile) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "outFile")); } if (!options.sourceMap && (options.mapRoot || options.sourceRoot)) { // Error to specify --mapRoot or --sourceRoot without mapSourceFiles if (options.mapRoot) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "mapRoot", "sourceMap")); } if (options.sourceRoot && !options.inlineSourceMap) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "sourceRoot", "sourceMap")); } } if (options.declarationDir) { if (!options.declaration) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "declarationDir", "declaration")); } if (options.out || options.outFile) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "declarationDir", options.out ? "out" : "outFile")); } } const languageVersion = options.target || ScriptTarget.ES3; const outFile = options.outFile || options.out; const firstExternalModuleSourceFile = forEach(files, f => isExternalModule(f) ? f : undefined); if (options.isolatedModules) { if (options.module === ModuleKind.None && languageVersion < ScriptTarget.ES6) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher)); } const firstNonExternalModuleSourceFile = forEach(files, f => !isExternalModule(f) && !isDeclarationFile(f) ? f : undefined); if (firstNonExternalModuleSourceFile) { const span = getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile); programDiagnostics.add(createFileDiagnostic(firstNonExternalModuleSourceFile, span.start, span.length, Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided)); } } else if (firstExternalModuleSourceFile && languageVersion < ScriptTarget.ES6 && options.module === ModuleKind.None) { // We cannot use createDiagnosticFromNode because nodes do not have parents yet const span = getErrorSpanForNode(firstExternalModuleSourceFile, firstExternalModuleSourceFile.externalModuleIndicator); programDiagnostics.add(createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, Diagnostics.Cannot_compile_modules_unless_the_module_flag_is_provided_with_a_valid_module_type_Consider_setting_the_module_compiler_option_in_a_tsconfig_json_file)); } // Cannot specify module gen target of es6 when below es6 if (options.module === ModuleKind.ES6 && languageVersion < ScriptTarget.ES6) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Cannot_compile_modules_into_es2015_when_targeting_ES5_or_lower)); } // Cannot specify module gen that isn't amd or system with --out if (outFile && options.module && !(options.module === ModuleKind.AMD || options.module === ModuleKind.System)) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile")); } // there has to be common source directory if user specified --outdir || --sourceRoot // if user specified --mapRoot, there needs to be common source directory if there would be multiple files being emitted if (options.outDir || // there is --outDir specified options.sourceRoot || // there is --sourceRoot specified options.mapRoot) { // there is --mapRoot specified // Precalculate and cache the common source directory const dir = getCommonSourceDirectory(); // If we failed to find a good common directory, but outDir is specified and at least one of our files is on a windows drive/URL/other resource, add a failure if (options.outDir && dir === "" && forEach(files, file => getRootLength(file.fileName) > 1)) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files)); } } if (options.noEmit) { if (options.out) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmit", "out")); } if (options.outFile) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmit", "outFile")); } if (options.outDir) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmit", "outDir")); } if (options.declaration) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmit", "declaration")); } } else if (options.allowJs && options.declaration) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", "declaration")); } if (options.emitDecoratorMetadata && !options.experimentalDecorators) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDecoratorMetadata", "experimentalDecorators")); } if (options.reactNamespace && !isIdentifier(options.reactNamespace, languageVersion)) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier, options.reactNamespace)); } // If the emit is enabled make sure that every output file is unique and not overwriting any of the input files if (!options.noEmit && !options.suppressOutputPathCheck) { const emitHost = getEmitHost(); const emitFilesSeen = createFileMap<boolean>(!host.useCaseSensitiveFileNames() ? key => key.toLocaleLowerCase() : undefined); forEachExpectedEmitFile(emitHost, (emitFileNames, sourceFiles, isBundledEmit) => { verifyEmitFilePath(emitFileNames.jsFilePath, emitFilesSeen); verifyEmitFilePath(emitFileNames.declarationFilePath, emitFilesSeen); }); } // Verify that all the emit files are unique and don't overwrite input files function verifyEmitFilePath(emitFileName: string, emitFilesSeen: FileMap<boolean>) { if (emitFileName) { const emitFilePath = toPath(emitFileName, currentDirectory, getCanonicalFileName); // Report error if the output overwrites input file if (filesByName.contains(emitFilePath)) { createEmitBlockingDiagnostics(emitFileName, emitFilePath, Diagnostics.Cannot_write_file_0_because_it_would_overwrite_input_file); } // Report error if multiple files write into same file if (emitFilesSeen.contains(emitFilePath)) { // Already seen the same emit file - report error createEmitBlockingDiagnostics(emitFileName, emitFilePath, Diagnostics.Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files); } else { emitFilesSeen.set(emitFilePath, true); } } } } function createEmitBlockingDiagnostics(emitFileName: string, emitFilePath: Path, message: DiagnosticMessage) { hasEmitBlockingDiagnostics.set(toPath(emitFileName, currentDirectory, getCanonicalFileName), true); programDiagnostics.add(createCompilerDiagnostic(message, emitFileName)); } } }
src/compiler/program.ts
1
https://github.com/microsoft/TypeScript/commit/8e77f40ace2155b16bb0ac5a417467edbec86843
[ 0.9977836012840271, 0.019622942432761192, 0.0001609042810741812, 0.0001748317008605227, 0.12751823663711548 ]
{ "id": 3, "code_window": [ " return runWithCancellationToken(() => {\n", " if (!isDeclarationFile(sourceFile)) {\n", " const resolver = getDiagnosticsProducingTypeChecker().getEmitResolver(sourceFile, cancellationToken);\n", " // Don't actually write any files since we're just getting diagnostics.\n", " const writeFile: WriteFileCallback = () => { };\n", " return ts.getDeclarationDiagnostics(getEmitHost(writeFile), resolver, sourceFile);\n", " }\n", " });\n", " }\n", "\n" ], "labels": [ "keep", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " const resolver = getDiagnosticsProducingTypeChecker().getEmitResolver(sourceFile, cancellationToken);\n", " // Don't actually write any files since we're just getting diagnostics.\n", " const writeFile: WriteFileCallback = () => { };\n", " return ts.getDeclarationDiagnostics(getEmitHost(writeFile), resolver, sourceFile);\n" ], "file_path": "src/compiler/program.ts", "type": "replace", "edit_start_line_idx": 1216 }
//// [parserModifierOnPropertySignature2.ts] interface Foo{ public biz; } //// [parserModifierOnPropertySignature2.js]
tests/baselines/reference/parserModifierOnPropertySignature2.js
0
https://github.com/microsoft/TypeScript/commit/8e77f40ace2155b16bb0ac5a417467edbec86843
[ 0.0001671304926276207, 0.0001671304926276207, 0.0001671304926276207, 0.0001671304926276207, 0 ]
{ "id": 3, "code_window": [ " return runWithCancellationToken(() => {\n", " if (!isDeclarationFile(sourceFile)) {\n", " const resolver = getDiagnosticsProducingTypeChecker().getEmitResolver(sourceFile, cancellationToken);\n", " // Don't actually write any files since we're just getting diagnostics.\n", " const writeFile: WriteFileCallback = () => { };\n", " return ts.getDeclarationDiagnostics(getEmitHost(writeFile), resolver, sourceFile);\n", " }\n", " });\n", " }\n", "\n" ], "labels": [ "keep", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " const resolver = getDiagnosticsProducingTypeChecker().getEmitResolver(sourceFile, cancellationToken);\n", " // Don't actually write any files since we're just getting diagnostics.\n", " const writeFile: WriteFileCallback = () => { };\n", " return ts.getDeclarationDiagnostics(getEmitHost(writeFile), resolver, sourceFile);\n" ], "file_path": "src/compiler/program.ts", "type": "replace", "edit_start_line_idx": 1216 }
// @declaration: true function f() { class C { public baz = 1; static foo() { } public bar() { } } }
tests/cases/conformance/classes/classDeclarations/modifierOnClassDeclarationMemberInFunction.ts
0
https://github.com/microsoft/TypeScript/commit/8e77f40ace2155b16bb0ac5a417467edbec86843
[ 0.0001754278055159375, 0.0001754278055159375, 0.0001754278055159375, 0.0001754278055159375, 0 ]
{ "id": 3, "code_window": [ " return runWithCancellationToken(() => {\n", " if (!isDeclarationFile(sourceFile)) {\n", " const resolver = getDiagnosticsProducingTypeChecker().getEmitResolver(sourceFile, cancellationToken);\n", " // Don't actually write any files since we're just getting diagnostics.\n", " const writeFile: WriteFileCallback = () => { };\n", " return ts.getDeclarationDiagnostics(getEmitHost(writeFile), resolver, sourceFile);\n", " }\n", " });\n", " }\n", "\n" ], "labels": [ "keep", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " const resolver = getDiagnosticsProducingTypeChecker().getEmitResolver(sourceFile, cancellationToken);\n", " // Don't actually write any files since we're just getting diagnostics.\n", " const writeFile: WriteFileCallback = () => { };\n", " return ts.getDeclarationDiagnostics(getEmitHost(writeFile), resolver, sourceFile);\n" ], "file_path": "src/compiler/program.ts", "type": "replace", "edit_start_line_idx": 1216 }
interface I<S> { f: <T extends S>(x: T) => void } var x: I<{s: string}> x.f({s: 1})
tests/cases/compiler/genericConstraintSatisfaction1.ts
0
https://github.com/microsoft/TypeScript/commit/8e77f40ace2155b16bb0ac5a417467edbec86843
[ 0.00017257238505408168, 0.00017257238505408168, 0.00017257238505408168, 0.00017257238505408168, 0 ]
{ "id": 4, "code_window": [ " });\n", " }\n", "\n", " function getOptionsDiagnostics(): Diagnostic[] {\n", " const allDiagnostics: Diagnostic[] = [];\n", " addRange(allDiagnostics, fileProcessingDiagnostics.getGlobalDiagnostics());\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " function getDeclarationDiagnosticsForFile(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] {\n", " return isDeclarationFile(sourceFile) ? [] : getDeclarationDiagnosticsWorker(sourceFile, cancellationToken);\n", " }\n", "\n" ], "file_path": "src/compiler/program.ts", "type": "add", "edit_start_line_idx": 1225 }
/// <reference path="sys.ts" /> /// <reference path="emitter.ts" /> /// <reference path="core.ts" /> namespace ts { /* @internal */ export let programTime = 0; /* @internal */ export let emitTime = 0; /* @internal */ export let ioReadTime = 0; /* @internal */ export let ioWriteTime = 0; /** The version of the TypeScript compiler release */ const emptyArray: any[] = []; export const version = "1.9.0"; export function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean): string { let fileName = "tsconfig.json"; while (true) { if (fileExists(fileName)) { return fileName; } const parentPath = getDirectoryPath(searchPath); if (parentPath === searchPath) { break; } searchPath = parentPath; fileName = "../" + fileName; } return undefined; } export function resolveTripleslashReference(moduleName: string, containingFile: string): string { const basePath = getDirectoryPath(containingFile); const referencedFileName = isRootedDiskPath(moduleName) ? moduleName : combinePaths(basePath, moduleName); return normalizePath(referencedFileName); } function trace(host: ModuleResolutionHost, message: DiagnosticMessage, ...args: any[]): void; function trace(host: ModuleResolutionHost, message: DiagnosticMessage): void { host.trace(formatMessage.apply(undefined, arguments)); } function isTraceEnabled(compilerOptions: CompilerOptions, host: ModuleResolutionHost): boolean { return compilerOptions.traceModuleResolution && host.trace !== undefined; } function startsWith(str: string, prefix: string): boolean { return str.lastIndexOf(prefix, 0) === 0; } function endsWith(str: string, suffix: string): boolean { const expectedPos = str.length - suffix.length; return str.indexOf(suffix, expectedPos) === expectedPos; } function hasZeroOrOneAsteriskCharacter(str: string): boolean { let seenAsterisk = false; for (let i = 0; i < str.length; i++) { if (str.charCodeAt(i) === CharacterCodes.asterisk) { if (!seenAsterisk) { seenAsterisk = true; } else { // have already seen asterisk return false; } } } return true; } function createResolvedModule(resolvedFileName: string, isExternalLibraryImport: boolean, failedLookupLocations: string[]): ResolvedModuleWithFailedLookupLocations { return { resolvedModule: resolvedFileName ? { resolvedFileName, isExternalLibraryImport } : undefined, failedLookupLocations }; } function moduleHasNonRelativeName(moduleName: string): boolean { if (isRootedDiskPath(moduleName)) { return false; } const i = moduleName.lastIndexOf("./", 1); const startsWithDotSlashOrDotDotSlash = i === 0 || (i === 1 && moduleName.charCodeAt(0) === CharacterCodes.dot); return !startsWithDotSlashOrDotDotSlash; } interface ModuleResolutionState { host: ModuleResolutionHost; compilerOptions: CompilerOptions; traceEnabled: boolean; // skip .tsx files if jsx is not enabled skipTsx: boolean; } export function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations { const traceEnabled = isTraceEnabled(compilerOptions, host); if (traceEnabled) { trace(host, Diagnostics.Resolving_module_0_from_1, moduleName, containingFile); } let moduleResolution = compilerOptions.moduleResolution; if (moduleResolution === undefined) { moduleResolution = getEmitModuleKind(compilerOptions) === ModuleKind.CommonJS ? ModuleResolutionKind.NodeJs : ModuleResolutionKind.Classic; if (traceEnabled) { trace(host, Diagnostics.Module_resolution_kind_is_not_specified_using_0, ModuleResolutionKind[moduleResolution]); } } else { if (traceEnabled) { trace(host, Diagnostics.Explicitly_specified_module_resolution_kind_Colon_0, ModuleResolutionKind[moduleResolution]); } } let result: ResolvedModuleWithFailedLookupLocations; switch (moduleResolution) { case ModuleResolutionKind.NodeJs: result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host); break; case ModuleResolutionKind.Classic: result = classicNameResolver(moduleName, containingFile, compilerOptions, host); break; } if (traceEnabled) { if (result.resolvedModule) { trace(host, Diagnostics.Module_name_0_was_successfully_resolved_to_1, moduleName, result.resolvedModule.resolvedFileName); } else { trace(host, Diagnostics.Module_name_0_was_not_resolved, moduleName); } } return result; } /* * Every module resolution kind can has its specific understanding how to load module from a specific path on disk * I.e. for path '/a/b/c': * - Node loader will first to try to check if '/a/b/c' points to a file with some supported extension and if this fails * it will try to load module from directory: directory '/a/b/c' should exist and it should have either 'package.json' with * 'typings' entry or file 'index' with some supported extension * - Classic loader will only try to interpret '/a/b/c' as file. */ type ResolutionKindSpecificLoader = (candidate: string, extensions: string[], failedLookupLocations: string[], onlyRecordFailures: boolean, state: ModuleResolutionState) => string; /** * Any module resolution kind can be augmented with optional settings: 'baseUrl', 'paths' and 'rootDirs' - they are used to * mitigate differences between design time structure of the project and its runtime counterpart so the same import name * can be resolved successfully by TypeScript compiler and runtime module loader. * If these settings are set then loading procedure will try to use them to resolve module name and it can of failure it will * fallback to standard resolution routine. * * - baseUrl - this setting controls how non-relative module names are resolved. If this setting is specified then non-relative * names will be resolved relative to baseUrl: i.e. if baseUrl is '/a/b' then candidate location to resolve module name 'c/d' will * be '/a/b/c/d' * - paths - this setting can only be used when baseUrl is specified. allows to tune how non-relative module names * will be resolved based on the content of the module name. * Structure of 'paths' compiler options * 'paths': { * pattern-1: [...substitutions], * pattern-2: [...substitutions], * ... * pattern-n: [...substitutions] * } * Pattern here is a string that can contain zero or one '*' character. During module resolution module name will be matched against * all patterns in the list. Matching for patterns that don't contain '*' means that module name must be equal to pattern respecting the case. * If pattern contains '*' then to match pattern "<prefix>*<suffix>" module name must start with the <prefix> and end with <suffix>. * <MatchedStar> denotes part of the module name between <prefix> and <suffix>. * If module name can be matches with multiple patterns then pattern with the longest prefix will be picked. * After selecting pattern we'll use list of substitutions to get candidate locations of the module and the try to load module * from the candidate location. * Substitution is a string that can contain zero or one '*'. To get candidate location from substitution we'll pick every * substitution in the list and replace '*' with <MatchedStar> string. If candidate location is not rooted it * will be converted to absolute using baseUrl. * For example: * baseUrl: /a/b/c * "paths": { * // match all module names * "*": [ * "*", // use matched name as is, * // <matched name> will be looked as /a/b/c/<matched name> * * "folder1/*" // substitution will convert matched name to 'folder1/<matched name>', * // since it is not rooted then final candidate location will be /a/b/c/folder1/<matched name> * ], * // match module names that start with 'components/' * "components/*": [ "/root/components/*" ] // substitution will convert /components/folder1/<matched name> to '/root/components/folder1/<matched name>', * // it is rooted so it will be final candidate location * } * * 'rootDirs' allows the project to be spreaded across multiple locations and resolve modules with relative names as if * they were in the same location. For example lets say there are two files * '/local/src/content/file1.ts' * '/shared/components/contracts/src/content/protocols/file2.ts' * After bundling content of '/shared/components/contracts/src' will be merged with '/local/src' so * if file1 has the following import 'import {x} from "./protocols/file2"' it will be resolved successfully in runtime. * 'rootDirs' provides the way to tell compiler that in order to get the whole project it should behave as if content of all * root dirs were merged together. * I.e. for the example above 'rootDirs' will have two entries: [ '/local/src', '/shared/components/contracts/src' ]. * Compiler will first convert './protocols/file2' into absolute path relative to the location of containing file: * '/local/src/content/protocols/file2' and try to load it - failure. * Then it will search 'rootDirs' looking for a longest matching prefix of this absolute path and if such prefix is found - absolute path will * be converted to a path relative to found rootDir entry './content/protocols/file2' (*). As a last step compiler will check all remaining * entries in 'rootDirs', use them to build absolute path out of (*) and try to resolve module from this location. */ function tryLoadModuleUsingOptionalResolutionSettings(moduleName: string, containingDirectory: string, loader: ResolutionKindSpecificLoader, failedLookupLocations: string[], supportedExtensions: string[], state: ModuleResolutionState): string { if (moduleHasNonRelativeName(moduleName)) { return tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state); } else { return tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state); } } function tryLoadModuleUsingRootDirs(moduleName: string, containingDirectory: string, loader: ResolutionKindSpecificLoader, failedLookupLocations: string[], supportedExtensions: string[], state: ModuleResolutionState): string { if (!state.compilerOptions.rootDirs) { return undefined; } if (state.traceEnabled) { trace(state.host, Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName); } const candidate = normalizePath(combinePaths(containingDirectory, moduleName)); let matchedRootDir: string; let matchedNormalizedPrefix: string; for (const rootDir of state.compilerOptions.rootDirs) { // rootDirs are expected to be absolute // in case of tsconfig.json this will happen automatically - compiler will expand relative names // using location of tsconfig.json as base location let normalizedRoot = normalizePath(rootDir); if (!endsWith(normalizedRoot, directorySeparator)) { normalizedRoot += directorySeparator; } const isLongestMatchingPrefix = startsWith(candidate, normalizedRoot) && (matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length); if (state.traceEnabled) { trace(state.host, Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix); } if (isLongestMatchingPrefix) { matchedNormalizedPrefix = normalizedRoot; matchedRootDir = rootDir; } } if (matchedNormalizedPrefix) { if (state.traceEnabled) { trace(state.host, Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix); } const suffix = candidate.substr(matchedNormalizedPrefix.length); // first - try to load from a initial location if (state.traceEnabled) { trace(state.host, Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); } const resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state); if (resolvedFileName) { return resolvedFileName; } if (state.traceEnabled) { trace(state.host, Diagnostics.Trying_other_entries_in_rootDirs); } // then try to resolve using remaining entries in rootDirs for (const rootDir of state.compilerOptions.rootDirs) { if (rootDir === matchedRootDir) { // skip the initially matched entry continue; } const candidate = combinePaths(normalizePath(rootDir), suffix); if (state.traceEnabled) { trace(state.host, Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate); } const baseDirectory = getDirectoryPath(candidate); const resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state); if (resolvedFileName) { return resolvedFileName; } } if (state.traceEnabled) { trace(state.host, Diagnostics.Module_resolution_using_rootDirs_has_failed); } } return undefined; } function tryLoadModuleUsingBaseUrl(moduleName: string, loader: ResolutionKindSpecificLoader, failedLookupLocations: string[], supportedExtensions: string[], state: ModuleResolutionState): string { if (!state.compilerOptions.baseUrl) { return undefined; } if (state.traceEnabled) { trace(state.host, Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName); } let longestMatchPrefixLength = -1; let matchedPattern: string; let matchedStar: string; if (state.compilerOptions.paths) { if (state.traceEnabled) { trace(state.host, Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); } for (const key in state.compilerOptions.paths) { const pattern: string = key; const indexOfStar = pattern.indexOf("*"); if (indexOfStar !== -1) { const prefix = pattern.substr(0, indexOfStar); const suffix = pattern.substr(indexOfStar + 1); if (moduleName.length >= prefix.length + suffix.length && startsWith(moduleName, prefix) && endsWith(moduleName, suffix)) { // use length of prefix as betterness criteria if (prefix.length > longestMatchPrefixLength) { longestMatchPrefixLength = prefix.length; matchedPattern = pattern; matchedStar = moduleName.substr(prefix.length, moduleName.length - suffix.length); } } } else if (pattern === moduleName) { // pattern was matched as is - no need to search further matchedPattern = pattern; matchedStar = undefined; break; } } } if (matchedPattern) { if (state.traceEnabled) { trace(state.host, Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPattern); } for (const subst of state.compilerOptions.paths[matchedPattern]) { const path = matchedStar ? subst.replace("\*", matchedStar) : subst; const candidate = normalizePath(combinePaths(state.compilerOptions.baseUrl, path)); if (state.traceEnabled) { trace(state.host, Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); } const resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(getDirectoryPath(candidate), state.host), state); if (resolvedFileName) { return resolvedFileName; } } return undefined; } else { const candidate = normalizePath(combinePaths(state.compilerOptions.baseUrl, moduleName)); if (state.traceEnabled) { trace(state.host, Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate); } return loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(getDirectoryPath(candidate), state.host), state); } } export function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations { const containingDirectory = getDirectoryPath(containingFile); const supportedExtensions = getSupportedExtensions(compilerOptions); const traceEnabled = isTraceEnabled(compilerOptions, host); const failedLookupLocations: string[] = []; const state = {compilerOptions, host, traceEnabled, skipTsx: false}; let resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, nodeLoadModuleByRelativeName, failedLookupLocations, supportedExtensions, state); if (resolvedFileName) { return createResolvedModule(resolvedFileName, /*isExternalLibraryImport*/false, failedLookupLocations); } let isExternalLibraryImport = false; if (moduleHasNonRelativeName(moduleName)) { if (traceEnabled) { trace(host, Diagnostics.Loading_module_0_from_node_modules_folder, moduleName); } resolvedFileName = loadModuleFromNodeModules(moduleName, containingDirectory, failedLookupLocations, state); isExternalLibraryImport = resolvedFileName !== undefined; } else { const candidate = normalizePath(combinePaths(containingDirectory, moduleName)); resolvedFileName = nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, /*onlyRecordFailures*/ false, state); } return createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations); } function nodeLoadModuleByRelativeName(candidate: string, supportedExtensions: string[], failedLookupLocations: string[], onlyRecordFailures: boolean, state: ModuleResolutionState): string { if (state.traceEnabled) { trace(state.host, Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0, candidate); } const resolvedFileName = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state); return resolvedFileName || loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, onlyRecordFailures, state); } /* @internal */ export function directoryProbablyExists(directoryName: string, host: { directoryExists?: (directoryName: string) => boolean } ): boolean { // if host does not support 'directoryExists' assume that directory will exist return !host.directoryExists || host.directoryExists(directoryName); } /** * @param {boolean} onlyRecordFailures - if true then function won't try to actually load files but instead record all attempts as failures. This flag is necessary * in cases when we know upfront that all load attempts will fail (because containing folder does not exists) however we still need to record all failed lookup locations. */ function loadModuleFromFile(candidate: string, extensions: string[], failedLookupLocation: string[], onlyRecordFailures: boolean, state: ModuleResolutionState): string { return forEach(extensions, tryLoad); function tryLoad(ext: string): string { if (ext === ".tsx" && state.skipTsx) { return undefined; } const fileName = fileExtensionIs(candidate, ext) ? candidate : candidate + ext; if (!onlyRecordFailures && state.host.fileExists(fileName)) { if (state.traceEnabled) { trace(state.host, Diagnostics.File_0_exist_use_it_as_a_module_resolution_result, fileName); } return fileName; } else { if (state.traceEnabled) { trace(state.host, Diagnostics.File_0_does_not_exist, fileName); } failedLookupLocation.push(fileName); return undefined; } } } function loadNodeModuleFromDirectory(extensions: string[], candidate: string, failedLookupLocation: string[], onlyRecordFailures: boolean, state: ModuleResolutionState): string { const packageJsonPath = combinePaths(candidate, "package.json"); const directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); if (directoryExists && state.host.fileExists(packageJsonPath)) { if (state.traceEnabled) { trace(state.host, Diagnostics.Found_package_json_at_0, packageJsonPath); } let jsonContent: { typings?: string }; try { const jsonText = state.host.readFile(packageJsonPath); jsonContent = jsonText ? <{ typings?: string }>JSON.parse(jsonText) : { typings: undefined }; } catch (e) { // gracefully handle if readFile fails or returns not JSON jsonContent = { typings: undefined }; } if (jsonContent.typings) { if (typeof jsonContent.typings === "string") { const typingsFile = normalizePath(combinePaths(candidate, jsonContent.typings)); if (state.traceEnabled) { trace(state.host, Diagnostics.package_json_has_typings_field_0_that_references_1, jsonContent.typings, typingsFile); } const result = loadModuleFromFile(typingsFile, extensions, failedLookupLocation, !directoryProbablyExists(getDirectoryPath(typingsFile), state.host), state); if (result) { return result; } } else if (state.traceEnabled) { trace(state.host, Diagnostics.Expected_type_of_typings_field_in_package_json_to_be_string_got_0, typeof jsonContent.typings); } } else { if (state.traceEnabled) { trace(state.host, Diagnostics.package_json_does_not_have_typings_field); } } } else { if (state.traceEnabled) { trace(state.host, Diagnostics.File_0_does_not_exist, packageJsonPath); } // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results failedLookupLocation.push(packageJsonPath); } return loadModuleFromFile(combinePaths(candidate, "index"), extensions, failedLookupLocation, !directoryExists, state); } function loadModuleFromNodeModules(moduleName: string, directory: string, failedLookupLocations: string[], state: ModuleResolutionState): string { directory = normalizeSlashes(directory); while (true) { const baseName = getBaseFileName(directory); if (baseName !== "node_modules") { const nodeModulesFolder = combinePaths(directory, "node_modules"); const nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); const candidate = normalizePath(combinePaths(nodeModulesFolder, moduleName)); // Load only typescript files irrespective of allowJs option if loading from node modules let result = loadModuleFromFile(candidate, supportedTypeScriptExtensions, failedLookupLocations, !nodeModulesFolderExists, state); if (result) { return result; } result = loadNodeModuleFromDirectory(supportedTypeScriptExtensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state); if (result) { return result; } } const parentPath = getDirectoryPath(directory); if (parentPath === directory) { break; } directory = parentPath; } return undefined; } export function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations { const traceEnabled = isTraceEnabled(compilerOptions, host); const state = { compilerOptions, host, traceEnabled, skipTsx: !compilerOptions.jsx }; const failedLookupLocations: string[] = []; const supportedExtensions = getSupportedExtensions(compilerOptions); let containingDirectory = getDirectoryPath(containingFile); const resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loadModuleFromFile, failedLookupLocations, supportedExtensions, state); if (resolvedFileName) { return createResolvedModule(resolvedFileName, /*isExternalLibraryImport*/false, failedLookupLocations); } let referencedSourceFile: string; if (moduleHasNonRelativeName(moduleName)) { while (true) { const searchName = normalizePath(combinePaths(containingDirectory, moduleName)); referencedSourceFile = loadModuleFromFile(searchName, supportedExtensions, failedLookupLocations, /*onlyRecordFailures*/ false, state); if (referencedSourceFile) { break; } const parentPath = getDirectoryPath(containingDirectory); if (parentPath === containingDirectory) { break; } containingDirectory = parentPath; } } else { const candidate = normalizePath(combinePaths(containingDirectory, moduleName)); referencedSourceFile = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, /*onlyRecordFailures*/ false, state); } return referencedSourceFile ? { resolvedModule: { resolvedFileName: referencedSourceFile }, failedLookupLocations } : { resolvedModule: undefined, failedLookupLocations }; } /* @internal */ export const defaultInitCompilerOptions: CompilerOptions = { module: ModuleKind.CommonJS, target: ScriptTarget.ES5, noImplicitAny: false, sourceMap: false, }; export function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost { const existingDirectories: Map<boolean> = {}; function getCanonicalFileName(fileName: string): string { // if underlying system can distinguish between two files whose names differs only in cases then file name already in canonical form. // otherwise use toLowerCase as a canonical form. return sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); } // returned by CScript sys environment const unsupportedFileEncodingErrorCode = -2147024809; function getSourceFile(fileName: string, languageVersion: ScriptTarget, onError?: (message: string) => void): SourceFile { let text: string; try { const start = new Date().getTime(); text = sys.readFile(fileName, options.charset); ioReadTime += new Date().getTime() - start; } catch (e) { if (onError) { onError(e.number === unsupportedFileEncodingErrorCode ? createCompilerDiagnostic(Diagnostics.Unsupported_file_encoding).messageText : e.message); } text = ""; } return text !== undefined ? createSourceFile(fileName, text, languageVersion, setParentNodes) : undefined; } function directoryExists(directoryPath: string): boolean { if (hasProperty(existingDirectories, directoryPath)) { return true; } if (sys.directoryExists(directoryPath)) { existingDirectories[directoryPath] = true; return true; } return false; } function ensureDirectoriesExist(directoryPath: string) { if (directoryPath.length > getRootLength(directoryPath) && !directoryExists(directoryPath)) { const parentDirectory = getDirectoryPath(directoryPath); ensureDirectoriesExist(parentDirectory); sys.createDirectory(directoryPath); } } function writeFile(fileName: string, data: string, writeByteOrderMark: boolean, onError?: (message: string) => void) { try { const start = new Date().getTime(); ensureDirectoriesExist(getDirectoryPath(normalizePath(fileName))); sys.writeFile(fileName, data, writeByteOrderMark); ioWriteTime += new Date().getTime() - start; } catch (e) { if (onError) { onError(e.message); } } } const newLine = getNewLineCharacter(options); return { getSourceFile, getDefaultLibFileName: options => combinePaths(getDirectoryPath(normalizePath(sys.getExecutingFilePath())), getDefaultLibFileName(options)), writeFile, getCurrentDirectory: memoize(() => sys.getCurrentDirectory()), useCaseSensitiveFileNames: () => sys.useCaseSensitiveFileNames, getCanonicalFileName, getNewLine: () => newLine, fileExists: fileName => sys.fileExists(fileName), readFile: fileName => sys.readFile(fileName), trace: (s: string) => sys.write(s + newLine), directoryExists: directoryName => sys.directoryExists(directoryName) }; } export function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[] { let diagnostics = program.getOptionsDiagnostics(cancellationToken).concat( program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); if (program.getCompilerOptions().declaration) { diagnostics = diagnostics.concat(program.getDeclarationDiagnostics(sourceFile, cancellationToken)); } return sortAndDeduplicateDiagnostics(diagnostics); } export function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string { if (typeof messageText === "string") { return messageText; } else { let diagnosticChain = messageText; let result = ""; let indent = 0; while (diagnosticChain) { if (indent) { result += newLine; for (let i = 0; i < indent; i++) { result += " "; } } result += diagnosticChain.messageText; indent++; diagnosticChain = diagnosticChain.next; } return result; } } export function createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost, oldProgram?: Program): Program { let program: Program; let files: SourceFile[] = []; let fileProcessingDiagnostics = createDiagnosticCollection(); const programDiagnostics = createDiagnosticCollection(); let commonSourceDirectory: string; let diagnosticsProducingTypeChecker: TypeChecker; let noDiagnosticsTypeChecker: TypeChecker; let classifiableNames: Map<string>; let skipDefaultLib = options.noLib; const supportedExtensions = getSupportedExtensions(options); const start = new Date().getTime(); host = host || createCompilerHost(options); // Map storing if there is emit blocking diagnostics for given input const hasEmitBlockingDiagnostics = createFileMap<boolean>(getCanonicalFileName); const currentDirectory = host.getCurrentDirectory(); const resolveModuleNamesWorker = host.resolveModuleNames ? ((moduleNames: string[], containingFile: string) => host.resolveModuleNames(moduleNames, containingFile)) : ((moduleNames: string[], containingFile: string) => { const resolvedModuleNames: ResolvedModule[] = []; // resolveModuleName does not store any results between calls. // lookup is a local cache to avoid resolving the same module name several times const lookup: Map<ResolvedModule> = {}; for (const moduleName of moduleNames) { let resolvedName: ResolvedModule; if (hasProperty(lookup, moduleName)) { resolvedName = lookup[moduleName]; } else { resolvedName = resolveModuleName(moduleName, containingFile, options, host).resolvedModule; lookup[moduleName] = resolvedName; } resolvedModuleNames.push(resolvedName); } return resolvedModuleNames; }); const filesByName = createFileMap<SourceFile>(); // stores 'filename -> file association' ignoring case // used to track cases when two file names differ only in casing const filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? createFileMap<SourceFile>(fileName => fileName.toLowerCase()) : undefined; if (oldProgram) { // check properties that can affect structure of the program or module resolution strategy // if any of these properties has changed - structure cannot be reused const oldOptions = oldProgram.getCompilerOptions(); if ((oldOptions.module !== options.module) || (oldOptions.noResolve !== options.noResolve) || (oldOptions.target !== options.target) || (oldOptions.noLib !== options.noLib) || (oldOptions.jsx !== options.jsx) || (oldOptions.allowJs !== options.allowJs)) { oldProgram = undefined; } } if (!tryReuseStructureFromOldProgram()) { forEach(rootNames, name => processRootFile(name, /*isDefaultLib*/ false)); // Do not process the default library if: // - The '--noLib' flag is used. // - A 'no-default-lib' reference comment is encountered in // processing the root files. if (!skipDefaultLib) { processRootFile(host.getDefaultLibFileName(options), /*isDefaultLib*/ true); } } // unconditionally set oldProgram to undefined to prevent it from being captured in closure oldProgram = undefined; program = { getRootFileNames: () => rootNames, getSourceFile, getSourceFiles: () => files, getCompilerOptions: () => options, getSyntacticDiagnostics, getOptionsDiagnostics, getGlobalDiagnostics, getSemanticDiagnostics, getDeclarationDiagnostics, getTypeChecker, getClassifiableNames, getDiagnosticsProducingTypeChecker, getCommonSourceDirectory, emit, getCurrentDirectory: () => currentDirectory, getNodeCount: () => getDiagnosticsProducingTypeChecker().getNodeCount(), getIdentifierCount: () => getDiagnosticsProducingTypeChecker().getIdentifierCount(), getSymbolCount: () => getDiagnosticsProducingTypeChecker().getSymbolCount(), getTypeCount: () => getDiagnosticsProducingTypeChecker().getTypeCount(), getFileProcessingDiagnostics: () => fileProcessingDiagnostics }; verifyCompilerOptions(); programTime += new Date().getTime() - start; return program; function getCommonSourceDirectory() { if (typeof commonSourceDirectory === "undefined") { if (options.rootDir && checkSourceFilesBelongToPath(files, options.rootDir)) { // If a rootDir is specified and is valid use it as the commonSourceDirectory commonSourceDirectory = getNormalizedAbsolutePath(options.rootDir, currentDirectory); } else { commonSourceDirectory = computeCommonSourceDirectory(files); } if (commonSourceDirectory && commonSourceDirectory[commonSourceDirectory.length - 1] !== directorySeparator) { // Make sure directory path ends with directory separator so this string can directly // used to replace with "" to get the relative path of the source file and the relative path doesn't // start with / making it rooted path commonSourceDirectory += directorySeparator; } } return commonSourceDirectory; } function getClassifiableNames() { if (!classifiableNames) { // Initialize a checker so that all our files are bound. getTypeChecker(); classifiableNames = {}; for (const sourceFile of files) { copyMap(sourceFile.classifiableNames, classifiableNames); } } return classifiableNames; } function tryReuseStructureFromOldProgram(): boolean { if (!oldProgram) { return false; } Debug.assert(!oldProgram.structureIsReused); // there is an old program, check if we can reuse its structure const oldRootNames = oldProgram.getRootFileNames(); if (!arrayIsEqualTo(oldRootNames, rootNames)) { return false; } // check if program source files has changed in the way that can affect structure of the program const newSourceFiles: SourceFile[] = []; const filePaths: Path[] = []; const modifiedSourceFiles: SourceFile[] = []; for (const oldSourceFile of oldProgram.getSourceFiles()) { let newSourceFile = host.getSourceFile(oldSourceFile.fileName, options.target); if (!newSourceFile) { return false; } newSourceFile.path = oldSourceFile.path; filePaths.push(newSourceFile.path); if (oldSourceFile !== newSourceFile) { if (oldSourceFile.hasNoDefaultLib !== newSourceFile.hasNoDefaultLib) { // value of no-default-lib has changed // this will affect if default library is injected into the list of files return false; } // check tripleslash references if (!arrayIsEqualTo(oldSourceFile.referencedFiles, newSourceFile.referencedFiles, fileReferenceIsEqualTo)) { // tripleslash references has changed return false; } // check imports and module augmentations collectExternalModuleReferences(newSourceFile); if (!arrayIsEqualTo(oldSourceFile.imports, newSourceFile.imports, moduleNameIsEqualTo)) { // imports has changed return false; } if (!arrayIsEqualTo(oldSourceFile.moduleAugmentations, newSourceFile.moduleAugmentations, moduleNameIsEqualTo)) { // moduleAugmentations has changed return false; } if (resolveModuleNamesWorker) { const moduleNames = map(concatenate(newSourceFile.imports, newSourceFile.moduleAugmentations), getTextOfLiteral); const resolutions = resolveModuleNamesWorker(moduleNames, getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory)); // ensure that module resolution results are still correct for (let i = 0; i < moduleNames.length; i++) { const newResolution = resolutions[i]; const oldResolution = getResolvedModule(oldSourceFile, moduleNames[i]); const resolutionChanged = oldResolution ? !newResolution || oldResolution.resolvedFileName !== newResolution.resolvedFileName || !!oldResolution.isExternalLibraryImport !== !!newResolution.isExternalLibraryImport : newResolution; if (resolutionChanged) { return false; } } } // pass the cache of module resolutions from the old source file newSourceFile.resolvedModules = oldSourceFile.resolvedModules; modifiedSourceFiles.push(newSourceFile); } else { // file has no changes - use it as is newSourceFile = oldSourceFile; } // if file has passed all checks it should be safe to reuse it newSourceFiles.push(newSourceFile); } // update fileName -> file mapping for (let i = 0, len = newSourceFiles.length; i < len; i++) { filesByName.set(filePaths[i], newSourceFiles[i]); } files = newSourceFiles; fileProcessingDiagnostics = oldProgram.getFileProcessingDiagnostics(); for (const modifiedFile of modifiedSourceFiles) { fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile); } oldProgram.structureIsReused = true; return true; } function getEmitHost(writeFileCallback?: WriteFileCallback): EmitHost { return { getCanonicalFileName, getCommonSourceDirectory: program.getCommonSourceDirectory, getCompilerOptions: program.getCompilerOptions, getCurrentDirectory: () => currentDirectory, getNewLine: () => host.getNewLine(), getSourceFile: program.getSourceFile, getSourceFiles: program.getSourceFiles, writeFile: writeFileCallback || ( (fileName, data, writeByteOrderMark, onError) => host.writeFile(fileName, data, writeByteOrderMark, onError)), isEmitBlocked, }; } function getDiagnosticsProducingTypeChecker() { return diagnosticsProducingTypeChecker || (diagnosticsProducingTypeChecker = createTypeChecker(program, /*produceDiagnostics:*/ true)); } function getTypeChecker() { return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = createTypeChecker(program, /*produceDiagnostics:*/ false)); } function emit(sourceFile?: SourceFile, writeFileCallback?: WriteFileCallback, cancellationToken?: CancellationToken): EmitResult { return runWithCancellationToken(() => emitWorker(this, sourceFile, writeFileCallback, cancellationToken)); } function isEmitBlocked(emitFileName: string): boolean { return hasEmitBlockingDiagnostics.contains(toPath(emitFileName, currentDirectory, getCanonicalFileName)); } function emitWorker(program: Program, sourceFile: SourceFile, writeFileCallback: WriteFileCallback, cancellationToken: CancellationToken): EmitResult { let declarationDiagnostics: Diagnostic[] = []; if (options.noEmit) { return { diagnostics: declarationDiagnostics, sourceMaps: undefined, emitSkipped: true }; } // If the noEmitOnError flag is set, then check if we have any errors so far. If so, // immediately bail out. Note that we pass 'undefined' for 'sourceFile' so that we // get any preEmit diagnostics, not just the ones if (options.noEmitOnError) { const diagnostics = program.getOptionsDiagnostics(cancellationToken).concat( program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); if (diagnostics.length === 0 && program.getCompilerOptions().declaration) { declarationDiagnostics = program.getDeclarationDiagnostics(/*sourceFile*/ undefined, cancellationToken); } if (diagnostics.length > 0 || declarationDiagnostics.length > 0) { return { diagnostics, sourceMaps: undefined, emitSkipped: true }; } } // Create the emit resolver outside of the "emitTime" tracking code below. That way // any cost associated with it (like type checking) are appropriate associated with // the type-checking counter. // // If the -out option is specified, we should not pass the source file to getEmitResolver. // This is because in the -out scenario all files need to be emitted, and therefore all // files need to be type checked. And the way to specify that all files need to be type // checked is to not pass the file to getEmitResolver. const emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile); const start = new Date().getTime(); const emitResult = emitFiles( emitResolver, getEmitHost(writeFileCallback), sourceFile); emitTime += new Date().getTime() - start; return emitResult; } function getSourceFile(fileName: string): SourceFile { return filesByName.get(toPath(fileName, currentDirectory, getCanonicalFileName)); } function getDiagnosticsHelper( sourceFile: SourceFile, getDiagnostics: (sourceFile: SourceFile, cancellationToken: CancellationToken) => Diagnostic[], cancellationToken: CancellationToken): Diagnostic[] { if (sourceFile) { return getDiagnostics(sourceFile, cancellationToken); } const allDiagnostics: Diagnostic[] = []; forEach(program.getSourceFiles(), sourceFile => { if (cancellationToken) { cancellationToken.throwIfCancellationRequested(); } addRange(allDiagnostics, getDiagnostics(sourceFile, cancellationToken)); }); return sortAndDeduplicateDiagnostics(allDiagnostics); } function getSyntacticDiagnostics(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] { return getDiagnosticsHelper(sourceFile, getSyntacticDiagnosticsForFile, cancellationToken); } function getSemanticDiagnostics(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] { return getDiagnosticsHelper(sourceFile, getSemanticDiagnosticsForFile, cancellationToken); } function getDeclarationDiagnostics(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] { return getDiagnosticsHelper(sourceFile, getDeclarationDiagnosticsForFile, cancellationToken); } function getSyntacticDiagnosticsForFile(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] { return sourceFile.parseDiagnostics; } function runWithCancellationToken<T>(func: () => T): T { try { return func(); } catch (e) { if (e instanceof OperationCanceledException) { // We were canceled while performing the operation. Because our type checker // might be a bad state, we need to throw it away. // // Note: we are overly aggressive here. We do not actually *have* to throw away // the "noDiagnosticsTypeChecker". However, for simplicity, i'd like to keep // the lifetimes of these two TypeCheckers the same. Also, we generally only // cancel when the user has made a change anyways. And, in that case, we (the // program instance) will get thrown away anyways. So trying to keep one of // these type checkers alive doesn't serve much purpose. noDiagnosticsTypeChecker = undefined; diagnosticsProducingTypeChecker = undefined; } throw e; } } function getSemanticDiagnosticsForFile(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] { return runWithCancellationToken(() => { const typeChecker = getDiagnosticsProducingTypeChecker(); Debug.assert(!!sourceFile.bindDiagnostics); const bindDiagnostics = sourceFile.bindDiagnostics; // For JavaScript files, we don't want to report the normal typescript semantic errors. // Instead, we just report errors for using TypeScript-only constructs from within a // JavaScript file. const checkDiagnostics = isSourceFileJavaScript(sourceFile) ? getJavaScriptSemanticDiagnosticsForFile(sourceFile, cancellationToken) : typeChecker.getDiagnostics(sourceFile, cancellationToken); const fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName); const programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName); return bindDiagnostics.concat(checkDiagnostics).concat(fileProcessingDiagnosticsInFile).concat(programDiagnosticsInFile); }); } function getJavaScriptSemanticDiagnosticsForFile(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] { return runWithCancellationToken(() => { const diagnostics: Diagnostic[] = []; walk(sourceFile); return diagnostics; function walk(node: Node): boolean { if (!node) { return false; } switch (node.kind) { case SyntaxKind.ImportEqualsDeclaration: diagnostics.push(createDiagnosticForNode(node, Diagnostics.import_can_only_be_used_in_a_ts_file)); return true; case SyntaxKind.ExportAssignment: if ((<ExportAssignment>node).isExportEquals) { diagnostics.push(createDiagnosticForNode(node, Diagnostics.export_can_only_be_used_in_a_ts_file)); return true; } break; case SyntaxKind.ClassDeclaration: let classDeclaration = <ClassDeclaration>node; if (checkModifiers(classDeclaration.modifiers) || checkTypeParameters(classDeclaration.typeParameters)) { return true; } break; case SyntaxKind.HeritageClause: let heritageClause = <HeritageClause>node; if (heritageClause.token === SyntaxKind.ImplementsKeyword) { diagnostics.push(createDiagnosticForNode(node, Diagnostics.implements_clauses_can_only_be_used_in_a_ts_file)); return true; } break; case SyntaxKind.InterfaceDeclaration: diagnostics.push(createDiagnosticForNode(node, Diagnostics.interface_declarations_can_only_be_used_in_a_ts_file)); return true; case SyntaxKind.ModuleDeclaration: diagnostics.push(createDiagnosticForNode(node, Diagnostics.module_declarations_can_only_be_used_in_a_ts_file)); return true; case SyntaxKind.TypeAliasDeclaration: diagnostics.push(createDiagnosticForNode(node, Diagnostics.type_aliases_can_only_be_used_in_a_ts_file)); return true; case SyntaxKind.MethodDeclaration: case SyntaxKind.MethodSignature: case SyntaxKind.Constructor: case SyntaxKind.GetAccessor: case SyntaxKind.SetAccessor: case SyntaxKind.FunctionExpression: case SyntaxKind.FunctionDeclaration: case SyntaxKind.ArrowFunction: case SyntaxKind.FunctionDeclaration: const functionDeclaration = <FunctionLikeDeclaration>node; if (checkModifiers(functionDeclaration.modifiers) || checkTypeParameters(functionDeclaration.typeParameters) || checkTypeAnnotation(functionDeclaration.type)) { return true; } break; case SyntaxKind.VariableStatement: const variableStatement = <VariableStatement>node; if (checkModifiers(variableStatement.modifiers)) { return true; } break; case SyntaxKind.VariableDeclaration: const variableDeclaration = <VariableDeclaration>node; if (checkTypeAnnotation(variableDeclaration.type)) { return true; } break; case SyntaxKind.CallExpression: case SyntaxKind.NewExpression: const expression = <CallExpression>node; if (expression.typeArguments && expression.typeArguments.length > 0) { const start = expression.typeArguments.pos; diagnostics.push(createFileDiagnostic(sourceFile, start, expression.typeArguments.end - start, Diagnostics.type_arguments_can_only_be_used_in_a_ts_file)); return true; } break; case SyntaxKind.Parameter: const parameter = <ParameterDeclaration>node; if (parameter.modifiers) { const start = parameter.modifiers.pos; diagnostics.push(createFileDiagnostic(sourceFile, start, parameter.modifiers.end - start, Diagnostics.parameter_modifiers_can_only_be_used_in_a_ts_file)); return true; } if (parameter.questionToken) { diagnostics.push(createDiagnosticForNode(parameter.questionToken, Diagnostics._0_can_only_be_used_in_a_ts_file, "?")); return true; } if (parameter.type) { diagnostics.push(createDiagnosticForNode(parameter.type, Diagnostics.types_can_only_be_used_in_a_ts_file)); return true; } break; case SyntaxKind.PropertyDeclaration: diagnostics.push(createDiagnosticForNode(node, Diagnostics.property_declarations_can_only_be_used_in_a_ts_file)); return true; case SyntaxKind.EnumDeclaration: diagnostics.push(createDiagnosticForNode(node, Diagnostics.enum_declarations_can_only_be_used_in_a_ts_file)); return true; case SyntaxKind.TypeAssertionExpression: let typeAssertionExpression = <TypeAssertion>node; diagnostics.push(createDiagnosticForNode(typeAssertionExpression.type, Diagnostics.type_assertion_expressions_can_only_be_used_in_a_ts_file)); return true; case SyntaxKind.Decorator: if (!options.experimentalDecorators) { diagnostics.push(createDiagnosticForNode(node, Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning)); } return true; } return forEachChild(node, walk); } function checkTypeParameters(typeParameters: NodeArray<TypeParameterDeclaration>): boolean { if (typeParameters) { const start = typeParameters.pos; diagnostics.push(createFileDiagnostic(sourceFile, start, typeParameters.end - start, Diagnostics.type_parameter_declarations_can_only_be_used_in_a_ts_file)); return true; } return false; } function checkTypeAnnotation(type: TypeNode): boolean { if (type) { diagnostics.push(createDiagnosticForNode(type, Diagnostics.types_can_only_be_used_in_a_ts_file)); return true; } return false; } function checkModifiers(modifiers: ModifiersArray): boolean { if (modifiers) { for (const modifier of modifiers) { switch (modifier.kind) { case SyntaxKind.PublicKeyword: case SyntaxKind.PrivateKeyword: case SyntaxKind.ProtectedKeyword: case SyntaxKind.ReadonlyKeyword: case SyntaxKind.DeclareKeyword: diagnostics.push(createDiagnosticForNode(modifier, Diagnostics._0_can_only_be_used_in_a_ts_file, tokenToString(modifier.kind))); return true; // These are all legal modifiers. case SyntaxKind.StaticKeyword: case SyntaxKind.ExportKeyword: case SyntaxKind.ConstKeyword: case SyntaxKind.DefaultKeyword: case SyntaxKind.AbstractKeyword: } } } return false; } }); } function getDeclarationDiagnosticsForFile(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] { return runWithCancellationToken(() => { if (!isDeclarationFile(sourceFile)) { const resolver = getDiagnosticsProducingTypeChecker().getEmitResolver(sourceFile, cancellationToken); // Don't actually write any files since we're just getting diagnostics. const writeFile: WriteFileCallback = () => { }; return ts.getDeclarationDiagnostics(getEmitHost(writeFile), resolver, sourceFile); } }); } function getOptionsDiagnostics(): Diagnostic[] { const allDiagnostics: Diagnostic[] = []; addRange(allDiagnostics, fileProcessingDiagnostics.getGlobalDiagnostics()); addRange(allDiagnostics, programDiagnostics.getGlobalDiagnostics()); return sortAndDeduplicateDiagnostics(allDiagnostics); } function getGlobalDiagnostics(): Diagnostic[] { const allDiagnostics: Diagnostic[] = []; addRange(allDiagnostics, getDiagnosticsProducingTypeChecker().getGlobalDiagnostics()); return sortAndDeduplicateDiagnostics(allDiagnostics); } function hasExtension(fileName: string): boolean { return getBaseFileName(fileName).indexOf(".") >= 0; } function processRootFile(fileName: string, isDefaultLib: boolean) { processSourceFile(normalizePath(fileName), isDefaultLib); } function fileReferenceIsEqualTo(a: FileReference, b: FileReference): boolean { return a.fileName === b.fileName; } function moduleNameIsEqualTo(a: LiteralExpression, b: LiteralExpression): boolean { return a.text === b.text; } function getTextOfLiteral(literal: LiteralExpression): string { return literal.text; } function collectExternalModuleReferences(file: SourceFile): void { if (file.imports) { return; } const isJavaScriptFile = isSourceFileJavaScript(file); const isExternalModuleFile = isExternalModule(file); let imports: LiteralExpression[]; let moduleAugmentations: LiteralExpression[]; for (const node of file.statements) { collectModuleReferences(node, /*inAmbientModule*/ false); if (isJavaScriptFile) { collectRequireCalls(node); } } file.imports = imports || emptyArray; file.moduleAugmentations = moduleAugmentations || emptyArray; return; function collectModuleReferences(node: Node, inAmbientModule: boolean): void { switch (node.kind) { case SyntaxKind.ImportDeclaration: case SyntaxKind.ImportEqualsDeclaration: case SyntaxKind.ExportDeclaration: let moduleNameExpr = getExternalModuleName(node); if (!moduleNameExpr || moduleNameExpr.kind !== SyntaxKind.StringLiteral) { break; } if (!(<LiteralExpression>moduleNameExpr).text) { break; } // TypeScript 1.0 spec (April 2014): 12.1.6 // An ExternalImportDeclaration in an AmbientExternalModuleDeclaration may reference other external modules // only through top - level external module names. Relative external module names are not permitted. if (!inAmbientModule || !isExternalModuleNameRelative((<LiteralExpression>moduleNameExpr).text)) { (imports || (imports = [])).push(<LiteralExpression>moduleNameExpr); } break; case SyntaxKind.ModuleDeclaration: if (isAmbientModule(<ModuleDeclaration>node) && (inAmbientModule || node.flags & NodeFlags.Ambient || isDeclarationFile(file))) { const moduleName = <LiteralExpression>(<ModuleDeclaration>node).name; // Ambient module declarations can be interpreted as augmentations for some existing external modules. // This will happen in two cases: // - if current file is external module then module augmentation is a ambient module declaration defined in the top level scope // - if current file is not external module then module augmentation is an ambient module declaration with non-relative module name // immediately nested in top level ambient module declaration . if (isExternalModuleFile || (inAmbientModule && !isExternalModuleNameRelative(moduleName.text))) { (moduleAugmentations || (moduleAugmentations = [])).push(moduleName); } else if (!inAmbientModule) { // An AmbientExternalModuleDeclaration declares an external module. // This type of declaration is permitted only in the global module. // The StringLiteral must specify a top - level external module name. // Relative external module names are not permitted // NOTE: body of ambient module is always a module block for (const statement of (<ModuleBlock>(<ModuleDeclaration>node).body).statements) { collectModuleReferences(statement, /*inAmbientModule*/ true); } } } } } function collectRequireCalls(node: Node): void { if (isRequireCall(node, /*checkArgumentIsStringLiteral*/true)) { (imports || (imports = [])).push(<StringLiteral>(<CallExpression>node).arguments[0]); } else { forEachChild(node, collectRequireCalls); } } } function processSourceFile(fileName: string, isDefaultLib: boolean, refFile?: SourceFile, refPos?: number, refEnd?: number) { let diagnosticArgument: string[]; let diagnostic: DiagnosticMessage; if (hasExtension(fileName)) { if (!options.allowNonTsExtensions && !forEach(supportedExtensions, extension => fileExtensionIs(host.getCanonicalFileName(fileName), extension))) { diagnostic = Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1; diagnosticArgument = [fileName, "'" + supportedExtensions.join("', '") + "'"]; } else if (!findSourceFile(fileName, toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd)) { diagnostic = Diagnostics.File_0_not_found; diagnosticArgument = [fileName]; } else if (refFile && host.getCanonicalFileName(fileName) === host.getCanonicalFileName(refFile.fileName)) { diagnostic = Diagnostics.A_file_cannot_have_a_reference_to_itself; diagnosticArgument = [fileName]; } } else { const nonTsFile: SourceFile = options.allowNonTsExtensions && findSourceFile(fileName, toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); if (!nonTsFile) { if (options.allowNonTsExtensions) { diagnostic = Diagnostics.File_0_not_found; diagnosticArgument = [fileName]; } else if (!forEach(supportedExtensions, extension => findSourceFile(fileName + extension, toPath(fileName + extension, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd))) { diagnostic = Diagnostics.File_0_not_found; fileName += ".ts"; diagnosticArgument = [fileName]; } } } if (diagnostic) { if (refFile !== undefined && refEnd !== undefined && refPos !== undefined) { fileProcessingDiagnostics.add(createFileDiagnostic(refFile, refPos, refEnd - refPos, diagnostic, ...diagnosticArgument)); } else { fileProcessingDiagnostics.add(createCompilerDiagnostic(diagnostic, ...diagnosticArgument)); } } } function reportFileNamesDifferOnlyInCasingError(fileName: string, existingFileName: string, refFile: SourceFile, refPos: number, refEnd: number): void { if (refFile !== undefined && refPos !== undefined && refEnd !== undefined) { fileProcessingDiagnostics.add(createFileDiagnostic(refFile, refPos, refEnd - refPos, Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, existingFileName)); } else { fileProcessingDiagnostics.add(createCompilerDiagnostic(Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, existingFileName)); } } // Get source file from normalized fileName function findSourceFile(fileName: string, path: Path, isDefaultLib: boolean, refFile?: SourceFile, refPos?: number, refEnd?: number): SourceFile { if (filesByName.contains(path)) { const file = filesByName.get(path); // try to check if we've already seen this file but with a different casing in path // NOTE: this only makes sense for case-insensitive file systems if (file && options.forceConsistentCasingInFileNames && getNormalizedAbsolutePath(file.fileName, currentDirectory) !== getNormalizedAbsolutePath(fileName, currentDirectory)) { reportFileNamesDifferOnlyInCasingError(fileName, file.fileName, refFile, refPos, refEnd); } return file; } // We haven't looked for this file, do so now and cache result const file = host.getSourceFile(fileName, options.target, hostErrorMessage => { if (refFile !== undefined && refPos !== undefined && refEnd !== undefined) { fileProcessingDiagnostics.add(createFileDiagnostic(refFile, refPos, refEnd - refPos, Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage)); } else { fileProcessingDiagnostics.add(createCompilerDiagnostic(Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage)); } }); filesByName.set(path, file); if (file) { file.path = path; if (host.useCaseSensitiveFileNames()) { // for case-sensitive file systems check if we've already seen some file with similar filename ignoring case const existingFile = filesByNameIgnoreCase.get(path); if (existingFile) { reportFileNamesDifferOnlyInCasingError(fileName, existingFile.fileName, refFile, refPos, refEnd); } else { filesByNameIgnoreCase.set(path, file); } } skipDefaultLib = skipDefaultLib || file.hasNoDefaultLib; const basePath = getDirectoryPath(fileName); if (!options.noResolve) { processReferencedFiles(file, basePath); } // always process imported modules to record module name resolutions processImportedModules(file, basePath); if (isDefaultLib) { files.unshift(file); } else { files.push(file); } } return file; } function processReferencedFiles(file: SourceFile, basePath: string) { forEach(file.referencedFiles, ref => { const referencedFileName = resolveTripleslashReference(ref.fileName, file.fileName); processSourceFile(referencedFileName, /*isDefaultLib*/ false, file, ref.pos, ref.end); }); } function getCanonicalFileName(fileName: string): string { return host.getCanonicalFileName(fileName); } function processImportedModules(file: SourceFile, basePath: string) { collectExternalModuleReferences(file); if (file.imports.length || file.moduleAugmentations.length) { file.resolvedModules = {}; const moduleNames = map(concatenate(file.imports, file.moduleAugmentations), getTextOfLiteral); const resolutions = resolveModuleNamesWorker(moduleNames, getNormalizedAbsolutePath(file.fileName, currentDirectory)); for (let i = 0; i < moduleNames.length; i++) { const resolution = resolutions[i]; setResolvedModule(file, moduleNames[i], resolution); // add file to program only if: // - resolution was successful // - noResolve is falsy // - module name come from the list fo imports const shouldAddFile = resolution && !options.noResolve && i < file.imports.length; if (shouldAddFile) { const importedFile = findSourceFile(resolution.resolvedFileName, toPath(resolution.resolvedFileName, currentDirectory, getCanonicalFileName), /*isDefaultLib*/ false, file, skipTrivia(file.text, file.imports[i].pos), file.imports[i].end); if (importedFile && resolution.isExternalLibraryImport) { // Since currently irrespective of allowJs, we only look for supportedTypeScript extension external module files, // this check is ok. Otherwise this would be never true for javascript file if (!isExternalModule(importedFile) && importedFile.statements.length) { const start = getTokenPosOfNode(file.imports[i], file); fileProcessingDiagnostics.add(createFileDiagnostic(file, start, file.imports[i].end - start, Diagnostics.Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_the_package_definition, importedFile.fileName)); } else if (importedFile.referencedFiles.length) { const firstRef = importedFile.referencedFiles[0]; fileProcessingDiagnostics.add(createFileDiagnostic(importedFile, firstRef.pos, firstRef.end - firstRef.pos, Diagnostics.Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_package_author_to_update_the_package_definition)); } } } } } else { // no imports - drop cached module resolutions file.resolvedModules = undefined; } return; } function computeCommonSourceDirectory(sourceFiles: SourceFile[]): string { let commonPathComponents: string[]; const failed = forEach(files, sourceFile => { // Each file contributes into common source file path if (isDeclarationFile(sourceFile)) { return; } const sourcePathComponents = getNormalizedPathComponents(sourceFile.fileName, currentDirectory); sourcePathComponents.pop(); // The base file name is not part of the common directory path if (!commonPathComponents) { // first file commonPathComponents = sourcePathComponents; return; } for (let i = 0, n = Math.min(commonPathComponents.length, sourcePathComponents.length); i < n; i++) { if (getCanonicalFileName(commonPathComponents[i]) !== getCanonicalFileName(sourcePathComponents[i])) { if (i === 0) { // Failed to find any common path component return true; } // New common path found that is 0 -> i-1 commonPathComponents.length = i; break; } } // If the sourcePathComponents was shorter than the commonPathComponents, truncate to the sourcePathComponents if (sourcePathComponents.length < commonPathComponents.length) { commonPathComponents.length = sourcePathComponents.length; } }); // A common path can not be found when paths span multiple drives on windows, for example if (failed) { return ""; } if (!commonPathComponents) { // Can happen when all input files are .d.ts files return currentDirectory; } return getNormalizedPathFromPathComponents(commonPathComponents); } function checkSourceFilesBelongToPath(sourceFiles: SourceFile[], rootDirectory: string): boolean { let allFilesBelongToPath = true; if (sourceFiles) { const absoluteRootDirectoryPath = host.getCanonicalFileName(getNormalizedAbsolutePath(rootDirectory, currentDirectory)); for (const sourceFile of sourceFiles) { if (!isDeclarationFile(sourceFile)) { const absoluteSourceFilePath = host.getCanonicalFileName(getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, options.rootDir)); allFilesBelongToPath = false; } } } } return allFilesBelongToPath; } function verifyCompilerOptions() { if (options.isolatedModules) { if (options.declaration) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "declaration", "isolatedModules")); } if (options.noEmitOnError) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmitOnError", "isolatedModules")); } if (options.out) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "isolatedModules")); } if (options.outFile) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "outFile", "isolatedModules")); } } if (options.inlineSourceMap) { if (options.sourceMap) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "sourceMap", "inlineSourceMap")); } if (options.mapRoot) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "mapRoot", "inlineSourceMap")); } } if (options.paths && options.baseUrl === undefined) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_paths_cannot_be_used_without_specifying_baseUrl_option)); } if (options.paths) { for (const key in options.paths) { if (!hasProperty(options.paths, key)) { continue; } if (!hasZeroOrOneAsteriskCharacter(key)) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, key)); } for (const subst of options.paths[key]) { if (!hasZeroOrOneAsteriskCharacter(subst)) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character, subst, key)); } } } } if (options.inlineSources) { if (!options.sourceMap && !options.inlineSourceMap) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_inlineSources_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided)); } if (options.sourceRoot) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "sourceRoot", "inlineSources")); } } if (options.out && options.outFile) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "outFile")); } if (!options.sourceMap && (options.mapRoot || options.sourceRoot)) { // Error to specify --mapRoot or --sourceRoot without mapSourceFiles if (options.mapRoot) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "mapRoot", "sourceMap")); } if (options.sourceRoot && !options.inlineSourceMap) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "sourceRoot", "sourceMap")); } } if (options.declarationDir) { if (!options.declaration) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "declarationDir", "declaration")); } if (options.out || options.outFile) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "declarationDir", options.out ? "out" : "outFile")); } } const languageVersion = options.target || ScriptTarget.ES3; const outFile = options.outFile || options.out; const firstExternalModuleSourceFile = forEach(files, f => isExternalModule(f) ? f : undefined); if (options.isolatedModules) { if (options.module === ModuleKind.None && languageVersion < ScriptTarget.ES6) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher)); } const firstNonExternalModuleSourceFile = forEach(files, f => !isExternalModule(f) && !isDeclarationFile(f) ? f : undefined); if (firstNonExternalModuleSourceFile) { const span = getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile); programDiagnostics.add(createFileDiagnostic(firstNonExternalModuleSourceFile, span.start, span.length, Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided)); } } else if (firstExternalModuleSourceFile && languageVersion < ScriptTarget.ES6 && options.module === ModuleKind.None) { // We cannot use createDiagnosticFromNode because nodes do not have parents yet const span = getErrorSpanForNode(firstExternalModuleSourceFile, firstExternalModuleSourceFile.externalModuleIndicator); programDiagnostics.add(createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, Diagnostics.Cannot_compile_modules_unless_the_module_flag_is_provided_with_a_valid_module_type_Consider_setting_the_module_compiler_option_in_a_tsconfig_json_file)); } // Cannot specify module gen target of es6 when below es6 if (options.module === ModuleKind.ES6 && languageVersion < ScriptTarget.ES6) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Cannot_compile_modules_into_es2015_when_targeting_ES5_or_lower)); } // Cannot specify module gen that isn't amd or system with --out if (outFile && options.module && !(options.module === ModuleKind.AMD || options.module === ModuleKind.System)) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile")); } // there has to be common source directory if user specified --outdir || --sourceRoot // if user specified --mapRoot, there needs to be common source directory if there would be multiple files being emitted if (options.outDir || // there is --outDir specified options.sourceRoot || // there is --sourceRoot specified options.mapRoot) { // there is --mapRoot specified // Precalculate and cache the common source directory const dir = getCommonSourceDirectory(); // If we failed to find a good common directory, but outDir is specified and at least one of our files is on a windows drive/URL/other resource, add a failure if (options.outDir && dir === "" && forEach(files, file => getRootLength(file.fileName) > 1)) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files)); } } if (options.noEmit) { if (options.out) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmit", "out")); } if (options.outFile) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmit", "outFile")); } if (options.outDir) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmit", "outDir")); } if (options.declaration) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmit", "declaration")); } } else if (options.allowJs && options.declaration) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", "declaration")); } if (options.emitDecoratorMetadata && !options.experimentalDecorators) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDecoratorMetadata", "experimentalDecorators")); } if (options.reactNamespace && !isIdentifier(options.reactNamespace, languageVersion)) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier, options.reactNamespace)); } // If the emit is enabled make sure that every output file is unique and not overwriting any of the input files if (!options.noEmit && !options.suppressOutputPathCheck) { const emitHost = getEmitHost(); const emitFilesSeen = createFileMap<boolean>(!host.useCaseSensitiveFileNames() ? key => key.toLocaleLowerCase() : undefined); forEachExpectedEmitFile(emitHost, (emitFileNames, sourceFiles, isBundledEmit) => { verifyEmitFilePath(emitFileNames.jsFilePath, emitFilesSeen); verifyEmitFilePath(emitFileNames.declarationFilePath, emitFilesSeen); }); } // Verify that all the emit files are unique and don't overwrite input files function verifyEmitFilePath(emitFileName: string, emitFilesSeen: FileMap<boolean>) { if (emitFileName) { const emitFilePath = toPath(emitFileName, currentDirectory, getCanonicalFileName); // Report error if the output overwrites input file if (filesByName.contains(emitFilePath)) { createEmitBlockingDiagnostics(emitFileName, emitFilePath, Diagnostics.Cannot_write_file_0_because_it_would_overwrite_input_file); } // Report error if multiple files write into same file if (emitFilesSeen.contains(emitFilePath)) { // Already seen the same emit file - report error createEmitBlockingDiagnostics(emitFileName, emitFilePath, Diagnostics.Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files); } else { emitFilesSeen.set(emitFilePath, true); } } } } function createEmitBlockingDiagnostics(emitFileName: string, emitFilePath: Path, message: DiagnosticMessage) { hasEmitBlockingDiagnostics.set(toPath(emitFileName, currentDirectory, getCanonicalFileName), true); programDiagnostics.add(createCompilerDiagnostic(message, emitFileName)); } } }
src/compiler/program.ts
1
https://github.com/microsoft/TypeScript/commit/8e77f40ace2155b16bb0ac5a417467edbec86843
[ 0.9992478489875793, 0.11430433392524719, 0.00016481129569001496, 0.00029038614593446255, 0.287712424993515 ]
{ "id": 4, "code_window": [ " });\n", " }\n", "\n", " function getOptionsDiagnostics(): Diagnostic[] {\n", " const allDiagnostics: Diagnostic[] = [];\n", " addRange(allDiagnostics, fileProcessingDiagnostics.getGlobalDiagnostics());\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " function getDeclarationDiagnosticsForFile(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] {\n", " return isDeclarationFile(sourceFile) ? [] : getDeclarationDiagnosticsWorker(sourceFile, cancellationToken);\n", " }\n", "\n" ], "file_path": "src/compiler/program.ts", "type": "add", "edit_start_line_idx": 1225 }
{"version":3,"file":"test.js","sourceRoot":"","sources":["file:///tests/cases/projects/outputdir_simple/m1.ts","file:///tests/cases/projects/outputdir_simple/test.ts"],"names":[],"mappings":"AAAA,IAAI,KAAK,GAAG,EAAE,CAAC;AACf;IAAA;IAEA,CAAC;IAAD,YAAC;AAAD,CAAC,AAFD,IAEC;AAED,IAAI,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;AAC/B;IACI,MAAM,CAAC,YAAY,CAAC;AACxB,CAAC;ACRD,6BAA6B;AAC7B,IAAI,EAAE,GAAG,EAAE,CAAC;AACZ;IAAA;IAEA,CAAC;IAAD,SAAC;AAAD,CAAC,AAFD,IAEC;AAED,IAAI,SAAS,GAAG,IAAI,EAAE,EAAE,CAAC;AACzB;IACI,MAAM,CAAC,SAAS,CAAC;AACrB,CAAC"}
tests/baselines/reference/project/maprootUrlSimpleSpecifyOutputFile/amd/bin/test.js.map
0
https://github.com/microsoft/TypeScript/commit/8e77f40ace2155b16bb0ac5a417467edbec86843
[ 0.00016439537284895778, 0.00016439537284895778, 0.00016439537284895778, 0.00016439537284895778, 0 ]
{ "id": 4, "code_window": [ " });\n", " }\n", "\n", " function getOptionsDiagnostics(): Diagnostic[] {\n", " const allDiagnostics: Diagnostic[] = [];\n", " addRange(allDiagnostics, fileProcessingDiagnostics.getGlobalDiagnostics());\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " function getDeclarationDiagnosticsForFile(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] {\n", " return isDeclarationFile(sourceFile) ? [] : getDeclarationDiagnosticsWorker(sourceFile, cancellationToken);\n", " }\n", "\n" ], "file_path": "src/compiler/program.ts", "type": "add", "edit_start_line_idx": 1225 }
tests/cases/conformance/types/objectTypeLiteral/callSignatures/specializedSignatureIsNotSubtypeOfNonSpecializedSignature.ts(2,10): error TS2394: Overload signature is not compatible with function implementation. ==== tests/cases/conformance/types/objectTypeLiteral/callSignatures/specializedSignatureIsNotSubtypeOfNonSpecializedSignature.ts (1 errors) ==== function foo(x: 'a'); ~~~ !!! error TS2394: Overload signature is not compatible with function implementation. function foo(x: number) { } class C { foo(x: 'a'); foo(x: number); foo(x: any) { } } class C2<T> { foo(x: 'a'); foo(x: T); foo(x: any) { } } class C3<T extends String> { foo(x: 'a'); foo(x: T); foo(x: any) { } } interface I { (x: 'a'); (x: number); foo(x: 'a'); foo(x: number); } interface I2<T> { (x: 'a'); (x: T); foo(x: 'a'); foo(x: T); } interface I3<T extends String> { (x: 'a'); (x: T); foo(x: 'a'); foo(x: T); } var a: { (x: 'a'); (x: number); foo(x: 'a'); foo(x: number); } var a2: { (x: 'a'); <T>(x: T); foo(x: 'a'); foo<T>(x: T); } var a3: { (x: 'a'); <T>(x: T); foo(x: 'a'); foo<T extends String>(x: T); }
tests/baselines/reference/specializedSignatureIsNotSubtypeOfNonSpecializedSignature.errors.txt
0
https://github.com/microsoft/TypeScript/commit/8e77f40ace2155b16bb0ac5a417467edbec86843
[ 0.0002866758150048554, 0.00018488429486751556, 0.00016838345618452877, 0.00017079425742849708, 0.000038493166357511654 ]
{ "id": 4, "code_window": [ " });\n", " }\n", "\n", " function getOptionsDiagnostics(): Diagnostic[] {\n", " const allDiagnostics: Diagnostic[] = [];\n", " addRange(allDiagnostics, fileProcessingDiagnostics.getGlobalDiagnostics());\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " function getDeclarationDiagnosticsForFile(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] {\n", " return isDeclarationFile(sourceFile) ? [] : getDeclarationDiagnosticsWorker(sourceFile, cancellationToken);\n", " }\n", "\n" ], "file_path": "src/compiler/program.ts", "type": "add", "edit_start_line_idx": 1225 }
//// [taggedTemplateStringsPlainCharactersThatArePartsOfEscapes02_ES6.ts] function f(...x: any[]) { } f `0${ " " }1${ " " }2${ " " }3${ " " }4${ " " }5${ " " }6${ " " }7${ " " }8${ " " }9${ " " }10${ " " }11${ " " }12${ " " }13${ " " }14${ " " }15${ " " }16${ " " }17${ " " }18${ " " }19${ " " }20${ " " }2028${ " " }2029${ " " }0085${ " " }t${ " " }v${ " " }f${ " " }b${ " " }r${ " " }n` //// [taggedTemplateStringsPlainCharactersThatArePartsOfEscapes02_ES6.js] function f(...x) { } f `0${" "}1${" "}2${" "}3${" "}4${" "}5${" "}6${" "}7${" "}8${" "}9${" "}10${" "}11${" "}12${" "}13${" "}14${" "}15${" "}16${" "}17${" "}18${" "}19${" "}20${" "}2028${" "}2029${" "}0085${" "}t${" "}v${" "}f${" "}b${" "}r${" "}n`;
tests/baselines/reference/taggedTemplateStringsPlainCharactersThatArePartsOfEscapes02_ES6.js
0
https://github.com/microsoft/TypeScript/commit/8e77f40ace2155b16bb0ac5a417467edbec86843
[ 0.0001672441721893847, 0.00016638965462334454, 0.00016553513705730438, 0.00016638965462334454, 8.545175660401583e-7 ]
{ "id": 0, "code_window": [ "\t\tlet leftBinaryContainerElement = document.createElement('div');\n", "\t\tleftBinaryContainerElement.className = 'binary-container';\n", "\t\tthis.leftBinaryContainer = $(leftBinaryContainerElement);\n", "\n", "\t\t// Left Custom Scrollbars\n", "\t\tthis.leftScrollbar = new ScrollableElement(leftBinaryContainerElement, { horizontal: 'hidden', vertical: 'hidden' });\n", "\t\tparent.getHTMLElement().appendChild(this.leftScrollbar.getDomNode());\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis.leftBinaryContainer.tabindex(0); // enable focus support from the editor part (do not remove)\n" ], "file_path": "src/vs/workbench/browser/parts/editor/binaryDiffEditor.ts", "type": "add", "edit_start_line_idx": 58 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; // import 'vs/css!./media/iframeeditor'; import {localize} from 'vs/nls'; import {TPromise} from 'vs/base/common/winjs.base'; import {IModel, EventType} from 'vs/editor/common/editorCommon'; import {Dimension, Builder} from 'vs/base/browser/builder'; import {cAll} from 'vs/base/common/lifecycle'; import {EditorOptions, EditorInput} from 'vs/workbench/common/editor'; import {BaseEditor} from 'vs/workbench/browser/parts/editor/baseEditor'; import {Position} from 'vs/platform/editor/common/editor'; import {ITelemetryService} from 'vs/platform/telemetry/common/telemetry'; import {IStorageService, StorageEventType, StorageScope} from 'vs/platform/storage/common/storage'; import {IWorkbenchEditorService} from 'vs/workbench/services/editor/common/editorService'; import {BaseTextEditorModel} from 'vs/workbench/common/editor/textEditorModel'; import {Preferences} from 'vs/workbench/common/constants'; import {HtmlInput} from 'vs/workbench/parts/html/common/htmlInput'; import {isLightTheme} from 'vs/platform/theme/common/themes'; import {DEFAULT_THEME_ID} from 'vs/workbench/services/themes/common/themeService'; /** * An implementation of editor for showing HTML content in an IFrame by leveraging the IFrameEditorInput. */ export class HtmlPreviewPart extends BaseEditor { static ID: string = 'workbench.editor.htmlPreviewPart'; private _editorService: IWorkbenchEditorService; private _storageService: IStorageService; private _iFrameElement: HTMLIFrameElement; private _model: IModel; private _modelChangeUnbind: Function; private _lastModelVersion: number; private _themeChangeUnbind: Function; constructor( @ITelemetryService telemetryService: ITelemetryService, @IWorkbenchEditorService editorService: IWorkbenchEditorService, @IStorageService storageService: IStorageService ) { super(HtmlPreviewPart.ID, telemetryService); this._editorService = editorService; this._storageService = storageService; } dispose(): void { // remove from dome const element = this._iFrameElement.parentElement; element.parentElement.removeChild(element); // unhook from model this._modelChangeUnbind = cAll(this._modelChangeUnbind); this._model = undefined; this._themeChangeUnbind = cAll(this._themeChangeUnbind); } public createEditor(parent: Builder): void { // IFrame // this.iframeBuilder.removeProperty(IFrameEditor.RESOURCE_PROPERTY); this._iFrameElement = document.createElement('iframe'); this._iFrameElement.setAttribute('frameborder', '0'); this._iFrameElement.className = 'iframe'; // Container for IFrame const iFrameContainerElement = document.createElement('div'); iFrameContainerElement.className = 'iframe-container monaco-editor-background'; // Inherit the background color from selected theme iFrameContainerElement.appendChild(this._iFrameElement); parent.getHTMLElement().appendChild(iFrameContainerElement); this._themeChangeUnbind = this._storageService.addListener(StorageEventType.STORAGE, event => { if (event.key === Preferences.THEME && this.isVisible()) { this._updateIFrameContent(true); } }); } public layout(dimension: Dimension): void { let {width, height} = dimension; this._iFrameElement.parentElement.style.width = `${width}px`; this._iFrameElement.parentElement.style.height = `${height}px`; this._iFrameElement.style.width = `${width}px`; this._iFrameElement.style.height = `${height}px`; } public focus(): void { // this.iframeContainer.domFocus(); this._iFrameElement.focus(); } // --- input public getTitle(): string { if (!this.input) { return localize('iframeEditor', 'Preview Html'); } return this.input.getName(); } public setVisible(visible: boolean, position?: Position): TPromise<void> { return super.setVisible(visible, position).then(() => { if (visible && this._model) { this._modelChangeUnbind = this._model.addListener(EventType.ModelContentChanged2, () => this._updateIFrameContent()); this._updateIFrameContent(); } else { this._modelChangeUnbind = cAll(this._modelChangeUnbind); } }) } public changePosition(position: Position): void { super.changePosition(position); // reparenting an IFRAME into another DOM element yields weird results when the contents are made // of a string and not a URL. to be on the safe side we reload the iframe when the position changes // and we do it using a timeout of 0 to reload only after the position has been changed in the DOM setTimeout(() => { this._updateIFrameContent(true); }, 0); } public setInput(input: EditorInput, options: EditorOptions): TPromise<void> { this._model = undefined; this._modelChangeUnbind = cAll(this._modelChangeUnbind); this._lastModelVersion = -1; if (!(input instanceof HtmlInput)) { return TPromise.wrapError<void>('Invalid input'); } return this._editorService.resolveEditorModel({ resource: (<HtmlInput>input).getResource() }).then(model => { if (model instanceof BaseTextEditorModel) { this._model = model.textEditorModel } if (!this._model) { return TPromise.wrapError<void>(localize('html.voidInput', "Invalid editor input.")); } this._modelChangeUnbind = this._model.addListener(EventType.ModelContentChanged2, () => this._updateIFrameContent()); this._updateIFrameContent(); return super.setInput(input, options); }); } private _updateIFrameContent(refresh: boolean = false): void { if (!this._model || (!refresh && this._lastModelVersion === this._model.getVersionId())) { // nothing to do return; } const html = this._model.getValue(); const iFrameDocument = this._iFrameElement.contentDocument; if (!iFrameDocument) { // not visible anymore return; } // the very first time we load just our script // to integrate with the outside world if ((<HTMLElement>iFrameDocument.firstChild).innerHTML === '<head></head><body></body>') { iFrameDocument.open('text/html', 'replace'); iFrameDocument.write(Integration.defaultHtml()); iFrameDocument.close(); } // diff a little against the current input and the new state const parser = new DOMParser(); const newDocument = parser.parseFromString(html, 'text/html'); const styleElement = Integration.defaultStyle(this._iFrameElement.parentElement, this._storageService.get(Preferences.THEME, StorageScope.GLOBAL, DEFAULT_THEME_ID)); if (newDocument.head.hasChildNodes()) { newDocument.head.insertBefore(styleElement, newDocument.head.firstChild); } else { newDocument.head.appendChild(styleElement) } if (newDocument.head.innerHTML !== iFrameDocument.head.innerHTML) { iFrameDocument.head.innerHTML = newDocument.head.innerHTML; } if (newDocument.body.innerHTML !== iFrameDocument.body.innerHTML) { iFrameDocument.body.innerHTML = newDocument.body.innerHTML; } this._lastModelVersion = this._model.getVersionId(); } } namespace Integration { 'use strict'; const scriptSource = [ 'var ignoredKeys = [9 /* tab */, 32 /* space */, 33 /* page up */, 34 /* page down */, 38 /* up */, 40 /* down */];', 'var ignoredCtrlCmdKeys = [65 /* a */, 67 /* c */];', 'var ignoredShiftKeys = [9 /* tab */];', 'window.document.body.addEventListener("keydown", function(event) {', // Listen to keydown events in the iframe ' try {', ' if (ignoredKeys.some(function(i) { return i === event.keyCode; })) {', ' if (!event.ctrlKey && !event.altKey && !event.shiftKey && !event.metaKey) {', ' return;', // we want some single keys to be supported (e.g. Page Down for scrolling) ' }', ' }', '', ' if (ignoredCtrlCmdKeys.some(function(i) { return i === event.keyCode; })) {', ' if (event.ctrlKey || event.metaKey) {', ' return;', // we want some ctrl/cmd keys to be supported (e.g. Ctrl+C for copy) ' }', ' }', '', ' if (ignoredShiftKeys.some(function(i) { return i === event.keyCode; })) {', ' if (event.shiftKey) {', ' return;', // we want some shift keys to be supported (e.g. Shift+Tab for copy) ' }', ' }', '', ' event.preventDefault();', // very important to not get duplicate actions when this one bubbles up! '', ' var fakeEvent = document.createEvent("KeyboardEvent");', // create a keyboard event ' Object.defineProperty(fakeEvent, "keyCode", {', // we need to set some properties that Chrome wants ' get : function() {', ' return event.keyCode;', ' }', ' });', ' Object.defineProperty(fakeEvent, "which", {', ' get : function() {', ' return event.keyCode;', ' }', ' });', ' Object.defineProperty(fakeEvent, "target", {', ' get : function() {', ' return window && window.parent.document.body;', ' }', ' });', '', ' fakeEvent.initKeyboardEvent("keydown", true, true, document.defaultView, null, null, event.ctrlKey, event.altKey, event.shiftKey, event.metaKey);', // the API shape of this method is not clear to me, but it works ;) '', ' window.parent.document.dispatchEvent(fakeEvent);', // dispatch the event onto the parent ' } catch (error) {}', '});', // disable dropping into iframe! 'window.document.addEventListener("dragover", function (e) {', ' e.preventDefault();', '});', 'window.document.addEventListener("drop", function (e) {', ' e.preventDefault();', '});', 'window.document.body.addEventListener("dragover", function (e) {', ' e.preventDefault();', '});', 'window.document.body.addEventListener("drop", function (e) {', ' e.preventDefault();', '});' ]; export function defaultHtml() { let all = [ '<html><head></head><body><script>', ...scriptSource, '</script></body></html>', ]; return all.join('\n'); } const defaultLightScrollbarStyle = [ '::-webkit-scrollbar-thumb {', ' background-color: rgba(100, 100, 100, 0.4);', '}', '::-webkit-scrollbar-thumb:hover {', ' background-color: rgba(100, 100, 100, 0.7);', '}', '::-webkit-scrollbar-thumb:active {', ' background-color: rgba(0, 0, 0, 0.6);', '}' ].join('\n'); const defaultDarkScrollbarStyle = [ '::-webkit-scrollbar-thumb {', ' background-color: rgba(121, 121, 121, 0.4);', '}', '::-webkit-scrollbar-thumb:hover {', ' background-color: rgba(100, 100, 100, 0.7);', '}', '::-webkit-scrollbar-thumb:active {', ' background-color: rgba(85, 85, 85, 0.8);', '}' ].join('\n') export function defaultStyle(element: HTMLElement, themeId: string): HTMLStyleElement { const styles = window.getComputedStyle(element); const styleElement = document.createElement('style'); styleElement.innerHTML = `* { color: ${styles.color}; background: ${styles.background}; font-family: ${styles.fontFamily}; font-size: ${styles.fontSize}; } img { max-width: 100%; max-height: 100%; } a:focus, input:focus, select:focus, textarea:focus { outline: 1px solid -webkit-focus-ring-color; outline-offset: -1px; } ::-webkit-scrollbar { width: 14px; height: 14px; } ${isLightTheme(themeId) ? defaultLightScrollbarStyle : defaultDarkScrollbarStyle}`; return styleElement; } }
src/vs/workbench/parts/html/browser/htmlPreviewPart.ts
1
https://github.com/microsoft/vscode/commit/8435ddcf464fd995936ff6f877ff4744dc3ca2b6
[ 0.0011817089980468154, 0.0002154707908630371, 0.00016507456894032657, 0.00017265189671888947, 0.00017788345576263964 ]
{ "id": 0, "code_window": [ "\t\tlet leftBinaryContainerElement = document.createElement('div');\n", "\t\tleftBinaryContainerElement.className = 'binary-container';\n", "\t\tthis.leftBinaryContainer = $(leftBinaryContainerElement);\n", "\n", "\t\t// Left Custom Scrollbars\n", "\t\tthis.leftScrollbar = new ScrollableElement(leftBinaryContainerElement, { horizontal: 'hidden', vertical: 'hidden' });\n", "\t\tparent.getHTMLElement().appendChild(this.leftScrollbar.getDomNode());\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis.leftBinaryContainer.tabindex(0); // enable focus support from the editor part (do not remove)\n" ], "file_path": "src/vs/workbench/browser/parts/editor/binaryDiffEditor.ts", "type": "add", "edit_start_line_idx": 58 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import * as assert from 'assert'; import { ProgressBar } from 'vs/base/browser/ui/progressbar/progressbar'; import { Builder } from 'vs/base/browser/builder'; import mockBrowserService = require('vs/base/test/browser/mockBrowserService'); suite("ProgressBar", () => { var fixture: HTMLElement; setup(() => { fixture = document.createElement('div'); document.body.appendChild(fixture); }); teardown(() => { document.body.removeChild(fixture); }); test("Progress Bar", function() { var b = new Builder(fixture); var bar = new ProgressBar(b); assert(bar.getContainer()); assert(bar.infinite()); assert(bar.total(100)); assert(bar.worked(50)); assert(bar.worked(50)); assert(bar.done()); bar.dispose(); }); });
src/vs/base/test/browser/progressBar.test.ts
0
https://github.com/microsoft/vscode/commit/8435ddcf464fd995936ff6f877ff4744dc3ca2b6
[ 0.0001765253400662914, 0.00017189308709930629, 0.00016750284703448415, 0.00017177205882035196, 0.000003710038981807884 ]
{ "id": 0, "code_window": [ "\t\tlet leftBinaryContainerElement = document.createElement('div');\n", "\t\tleftBinaryContainerElement.className = 'binary-container';\n", "\t\tthis.leftBinaryContainer = $(leftBinaryContainerElement);\n", "\n", "\t\t// Left Custom Scrollbars\n", "\t\tthis.leftScrollbar = new ScrollableElement(leftBinaryContainerElement, { horizontal: 'hidden', vertical: 'hidden' });\n", "\t\tparent.getHTMLElement().appendChild(this.leftScrollbar.getDomNode());\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis.leftBinaryContainer.tabindex(0); // enable focus support from the editor part (do not remove)\n" ], "file_path": "src/vs/workbench/browser/parts/editor/binaryDiffEditor.ts", "type": "add", "edit_start_line_idx": 58 }
test/**
extensions/php/.vscodeignore
0
https://github.com/microsoft/vscode/commit/8435ddcf464fd995936ff6f877ff4744dc3ca2b6
[ 0.00017611010116524994, 0.00017611010116524994, 0.00017611010116524994, 0.00017611010116524994, 0 ]
{ "id": 0, "code_window": [ "\t\tlet leftBinaryContainerElement = document.createElement('div');\n", "\t\tleftBinaryContainerElement.className = 'binary-container';\n", "\t\tthis.leftBinaryContainer = $(leftBinaryContainerElement);\n", "\n", "\t\t// Left Custom Scrollbars\n", "\t\tthis.leftScrollbar = new ScrollableElement(leftBinaryContainerElement, { horizontal: 'hidden', vertical: 'hidden' });\n", "\t\tparent.getHTMLElement().appendChild(this.leftScrollbar.getDomNode());\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis.leftBinaryContainer.tabindex(0); // enable focus support from the editor part (do not remove)\n" ], "file_path": "src/vs/workbench/browser/parts/editor/binaryDiffEditor.ts", "type": "add", "edit_start_line_idx": 58 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ .monaco-workbench > .part > .content > .composite { height: 100%; } .monaco-workbench > .part > .composite.title { display: block; } .monaco-workbench > .part > .composite.title > .title-label span { color: #6f6f6f; text-transform: uppercase; } .monaco-workbench.vs-dark > .part > .composite.title > .title-label span { color: #bbbbbb; }
src/vs/workbench/browser/parts/media/compositePart.css
0
https://github.com/microsoft/vscode/commit/8435ddcf464fd995936ff6f877ff4744dc3ca2b6
[ 0.00017644171020947397, 0.00017550565826240927, 0.00017489118908997625, 0.00017518409003969282, 6.725998673573486e-7 ]
{ "id": 1, "code_window": [ "\n", "\t\t// Right Container for Binary\n", "\t\tlet rightBinaryContainerElement = document.createElement('div');\n", "\t\trightBinaryContainerElement.className = 'binary-container';\n", "\t\tthis.rightBinaryContainer = $(rightBinaryContainerElement);\n", "\n", "\t\t// Right Custom Scrollbars\n", "\t\tthis.rightScrollbar = new ScrollableElement(rightBinaryContainerElement, { horizontal: 'hidden', vertical: 'hidden' });\n", "\t\tparent.getHTMLElement().appendChild(this.rightScrollbar.getDomNode());\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis.rightBinaryContainer.tabindex(0); // enable focus support from the editor part (do not remove)\n" ], "file_path": "src/vs/workbench/browser/parts/editor/binaryDiffEditor.ts", "type": "add", "edit_start_line_idx": 74 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ .monaco-shell { height: 100%; width: 100%; color: #6C6C6C; margin: 0; padding: 0; overflow: hidden; font-family: "Segoe WPC", "Segoe UI", "SFUIText-Light", "HelveticaNeue-Light", sans-serif, "Droid Sans Fallback"; font-size: 11px; -webkit-user-select: none; -ms-user-select: none; -khtml-user-select: none; -moz-user-select: -moz-none; -o-user-select: none; user-select: none; } @-webkit-keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } } @-moz-keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } } @-ms-keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } } @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } } .monaco-shell img { border: 0; } .monaco-shell label { cursor: pointer; } .monaco-shell a { text-decoration: none; } .monaco-shell a.plain { color: inherit; text-decoration: none; } .monaco-shell a.plain:hover, .monaco-shell a.plain.hover { color: inherit; text-decoration: none; } /* START Keyboard Focus Indication Styles */ .monaco-shell.vs [tabindex="0"]:focus, .monaco-shell.vs .synthetic-focus, .monaco-shell.vs select:focus, .monaco-shell.vs input[type="button"]:focus, .monaco-shell.vs input[type="submit"]:focus, .monaco-shell.vs input[type="text"]:focus, .monaco-shell.vs textarea:focus, .monaco-shell.vs input[type="checkbox"]:focus { outline: 1px solid rgba(0, 122, 204, 0.4); outline-offset: -1px; opacity: 1 !important; } .monaco-shell.vs-dark [tabindex="0"]:focus, .monaco-shell.vs-dark .synthetic-focus, .monaco-shell.vs-dark select:focus, .monaco-shell.vs-dark input[type="button"]:focus, .monaco-shell.vs-dark input[type="submit"]:focus, .monaco-shell.vs-dark input[type="text"]:focus, .monaco-shell.vs-dark textarea:focus, .monaco-shell.vs-dark input[type="checkbox"]:focus { outline: 1px solid rgba(14, 99, 156, 0.6); outline-offset: -1px; opacity: 1 !important; } .monaco-shell.hc-black [tabindex="0"]:focus, .monaco-shell.hc-black .synthetic-focus, .monaco-shell.hc-black select:focus, .monaco-shell.hc-black input[type="button"]:focus, .monaco-shell.hc-black input[type="submit"]:focus, .monaco-shell.hc-black input[type="text"]:focus, .monaco-shell.hc-black textarea:focus, .monaco-shell.hc-black input[type="checkbox"]:focus { outline: 2px solid #DF740C; outline-offset: -2px; } .monaco-shell.vs .monaco-tree.focused .monaco-tree-row.focused [tabindex="0"]:focus { outline: 1px solid #007ACC; /* higher contrast color for focusable elements in a row that shows focus feedback */ } .monaco-shell.vs-dark .monaco-tree.focused .monaco-tree-row.focused [tabindex="0"]:focus { outline: 1px solid #007ACC; /* higher contrast color for focusable elements in a row that shows focus feedback */ } .monaco-shell .monaco-tree.focused.no-item-focus:focus:before { position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: 5; /* make sure we are on top of the tree items */ content: ""; pointer-events: none; /* enable click through */ } .monaco-shell.vs .monaco-tree.focused.no-item-focus:focus:before { outline: 1px solid rgba(0, 122, 204, 0.4); /* we still need to handle the empty tree or no focus item case */ outline-offset: -1px; } .monaco-shell.vs-dark .monaco-tree.focused.no-item-focus:focus:before { outline: 1px solid rgba(14, 99, 156, 0.6); /* we still need to handle the empty tree or no focus item case */ outline-offset: -1px; } .monaco-shell.hc-black .monaco-tree.focused.no-item-focus:focus:before { outline: 2px solid #DF740C; /* we still need to handle the empty tree or no focus item case */ outline-offset: -2px; } .monaco-shell .synthetic-focus :focus { outline: 0 !important; /* elements within widgets that draw synthetic-focus should never show focus */ } .monaco-shell .monaco-inputbox.info.synthetic-focus, .monaco-shell .monaco-inputbox.warning.synthetic-focus, .monaco-shell .monaco-inputbox.error.synthetic-focus, .monaco-shell .monaco-inputbox.info input[type="text"]:focus, .monaco-shell .monaco-inputbox.warning input[type="text"]:focus, .monaco-shell .monaco-inputbox.error input[type="text"]:focus { outline: 0 !important; /* outline is not going well with decoration */ } .monaco-shell .monaco-tree.focused:focus { outline: 0; /* tree indicates focus not via outline but through the focussed item */ } .monaco-shell [tabindex="0"]:active, .monaco-shell select:active, .monaco-shell input[type="button"]:active, .monaco-shell input[type="submit"]:active, .monaco-shell input[type="checkbox"]:active, .monaco-shell .monaco-tree.focused.no-item-focus:active:before { outline: 0 !important; /* fixes some flashing outlines from showing up when clicking */ } .monaco-shell .activitybar [tabindex="0"]:focus { outline: 0; /* activity bar indicates focus custom */ } /* END Keyboard Focus Indication Styles */ .monaco-shell a.prominent { text-decoration: underline; } .monaco-shell a.strong { font-weight: bold; } a:active { color: inherit; background-color: inherit; } .monaco-shell input { font-family: "Segoe UI", "SFUIText-Light", "HelveticaNeue-Light", sans-serif, "Droid Sans Fallback"; color: inherit; } .monaco-shell select { font-family: "Segoe UI","SFUIText-Light", "HelveticaNeue-Light", sans-serif, "Droid Sans Fallback"; } .monaco-shell .pointer { cursor: pointer; } .monaco-shell .context-view .tooltip { background-color: white; border: 1px solid #ccc; } .monaco-shell .context-view.bottom.right .tooltip:before { border-width: 6px; border-bottom: 6px solid #ccc; } .monaco-shell .context-view.bottom.right .tooltip:after { border-width: 5px; border-bottom: 5px solid white; } .monaco-shell .context-view .monaco-menu .actions-container { min-width: 160px; } .monaco-shell .monaco-menu .action-label.check { font-weight: bold; } .monaco-shell .monaco-menu .action-label.uncheck { font-weight: normal; } /* Notifications */ .monaco-shell .monaco-notification-container { position: absolute; width: 100%; height: 400px; top: calc(50% - 200px); top: -moz-calc(50% - 200px); top: -webkit-calc(50% - 200px); top: -ms-calc(50% - 200px); top: -o-calc(50% - 200px); background-color: #0E6198; color: white; border-top: 2px solid transparent; border-bottom: 2px solid transparent; } .monaco-shell .monaco-notification-container a { color: inherit; opacity: 0.6; text-decoration: underline; } .monaco-shell .monaco-notification-container .buttons { margin-top: 2em; } .monaco-shell .monaco-notification-container button { color: inherit; text-decoration: none; display: inline-block; padding: 6px 16px; margin-right: 12px; font-family: 'Segoe UI Semibold', "Segoe UI", "SFUIText-Light", "HelveticaNeue-Light", sans-serif, "Droid Sans Fallback"; font-weight: 400; font-size: 12px; min-width: 65px; border: 2px solid #fff; background-color: transparent; -moz-box-sizing: border-box; box-sizing: border-box; cursor: pointer; } .monaco-shell .monaco-notification-container button.default { background-color: rgba(255, 255, 255, 0.2); } .monaco-shell .monaco-notification-container button:disabled { opacity: 0.4; } .monaco-shell .monaco-notification-container button:not(:disabled):hover { color: inherit; background-color: rgba(255, 255, 255, 0.1); } .monaco-shell .monaco-notification-container button.default:not(:disabled)hover { background-color: rgba(255, 255, 255, 0.3); } .monaco-shell .monaco-notification-container > .notification { max-width: 800px; height: 100%; margin: 0 auto; padding: 0 16px; overflow-y: auto; overflow-x: hidden; font-family: "Segoe WPC", "Segoe UI", "SFUIText-Light", "HelveticaNeue-Light", sans-serif, "Droid Sans Fallback"; font-size: 14px; } .monaco-shell .monaco-notification-container > .notification > .notification-title { font-family: "Segoe UI Light", "Segoe UI", "SFUIText-Light", "HelveticaNeue-Light", "Helvetica Neue", sans-serif, "Droid Sans Fallback"; font-weight: 300; font-size: 2.5em; } .monaco-shell input:disabled { background-color: #E1E1E1; } /** * Dark Theme */ .monaco-shell.vs-dark { color: #BBB; background-color: #1E1E1E; } .monaco-shell.vs-dark .monaco-action-bar.vertical .action-label.separator { border-bottom-color: #666; } .monaco-shell.vs-dark .context-view .tooltip { background-color: #1E1E1E; border-color: #707070; } .monaco-shell.vs-dark .context-view.bottom.right .tooltip:before { border-bottom: 6px solid #707070; } .monaco-shell.vs-dark .context-view.bottom.right .tooltip:after { border-bottom: 5px solid #1E1E1E; } .monaco-shell.vs-dark input:disabled { background-color: #333; } /** * High Contrast Theme */ .monaco-shell.hc-black { color: #fff; background-color: #000; } .monaco-shell.hc-black .monaco-modal-view.visible .monaco-modal-view-background { opacity: 0.6; } .monaco-shell.hc-black .monaco-notification-container { background-color: #0C141F; color: white; border-top: 2px solid #6FC3DF; border-bottom: 2px solid #6FC3DF; } .monaco-shell.hc-black .monaco-notification-container input { background-color: #000; } .monaco-shell.hc-black .context-view .tooltip { background-color: black; } .monaco-shell.hc-black .context-view .tooltip:before { border-width: 0 !important; } .monaco-shell.hc-black .context-view .tooltip:after { border-width: 0 !important; }
src/vs/workbench/electron-browser/media/shell.css
1
https://github.com/microsoft/vscode/commit/8435ddcf464fd995936ff6f877ff4744dc3ca2b6
[ 0.00017785991076380014, 0.00017365734674967825, 0.00016954148304648697, 0.00017381108773406595, 0.0000019179246919520665 ]
{ "id": 1, "code_window": [ "\n", "\t\t// Right Container for Binary\n", "\t\tlet rightBinaryContainerElement = document.createElement('div');\n", "\t\trightBinaryContainerElement.className = 'binary-container';\n", "\t\tthis.rightBinaryContainer = $(rightBinaryContainerElement);\n", "\n", "\t\t// Right Custom Scrollbars\n", "\t\tthis.rightScrollbar = new ScrollableElement(rightBinaryContainerElement, { horizontal: 'hidden', vertical: 'hidden' });\n", "\t\tparent.getHTMLElement().appendChild(this.rightScrollbar.getDomNode());\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis.rightBinaryContainer.tabindex(0); // enable focus support from the editor part (do not remove)\n" ], "file_path": "src/vs/workbench/browser/parts/editor/binaryDiffEditor.ts", "type": "add", "edit_start_line_idx": 74 }
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>fileTypes</key> <array> <string>sh</string> <string>bash</string> <string>zsh</string> <string>bashrc</string> <string>bash_profile</string> <string>bash_login</string> <string>profile</string> <string>bash_logout</string> <string>.textmate_init</string> </array> <key>firstLineMatch</key> <string>^#!.*\b(bash|zsh|sh|tcsh)|^#\s*-\*-[^*]*mode:\s*shell-script[^*]*-\*-</string> <key>keyEquivalent</key> <string>^~S</string> <key>name</key> <string>Shell Script (Bash)</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#comment</string> </dict> <dict> <key>include</key> <string>#pipeline</string> </dict> <dict> <key>include</key> <string>#list</string> </dict> <dict> <key>include</key> <string>#compound-command</string> </dict> <dict> <key>include</key> <string>#loop</string> </dict> <dict> <key>include</key> <string>#function-definition</string> </dict> <dict> <key>include</key> <string>#string</string> </dict> <dict> <key>include</key> <string>#variable</string> </dict> <dict> <key>include</key> <string>#interpolation</string> </dict> <dict> <key>include</key> <string>#heredoc</string> </dict> <dict> <key>include</key> <string>#herestring</string> </dict> <dict> <key>include</key> <string>#redirection</string> </dict> <dict> <key>include</key> <string>#pathname</string> </dict> <dict> <key>include</key> <string>#keyword</string> </dict> <dict> <key>include</key> <string>#support</string> </dict> </array> <key>repository</key> <dict> <key>case-clause</key> <dict> <key>patterns</key> <array> <dict> <key>begin</key> <string>(?=\S)</string> <key>end</key> <string>;;</string> <key>endCaptures</key> <dict> <key>0</key> <dict> <key>name</key> <string>punctuation.terminator.case-clause.shell</string> </dict> </dict> <key>name</key> <string>meta.scope.case-clause.shell</string> <key>patterns</key> <array> <dict> <key>begin</key> <string>(\(|(?=\S))</string> <key>captures</key> <dict> <key>0</key> <dict> <key>name</key> <string>punctuation.definition.case-pattern.shell</string> </dict> </dict> <key>end</key> <string>\)</string> <key>name</key> <string>meta.scope.case-pattern.shell</string> <key>patterns</key> <array> <dict> <key>match</key> <string>\|</string> <key>name</key> <string>punctuation.separator.pipe-sign.shell</string> </dict> <dict> <key>include</key> <string>#string</string> </dict> <dict> <key>include</key> <string>#variable</string> </dict> <dict> <key>include</key> <string>#interpolation</string> </dict> <dict> <key>include</key> <string>#pathname</string> </dict> </array> </dict> <dict> <key>begin</key> <string>(?&lt;=\))</string> <key>end</key> <string>(?=;;)</string> <key>name</key> <string>meta.scope.case-clause-body.shell</string> <key>patterns</key> <array> <dict> <key>include</key> <string>$self</string> </dict> </array> </dict> </array> </dict> </array> </dict> <key>comment</key> <dict> <key>begin</key> <string>(^[ \t]+)?(?&lt;!\S)(?=#)(?!#\{)</string> <key>beginCaptures</key> <dict> <key>1</key> <dict> <key>name</key> <string>punctuation.whitespace.comment.leading.shell</string> </dict> </dict> <key>end</key> <string>(?!\G)</string> <key>patterns</key> <array> <dict> <key>begin</key> <string>#</string> <key>beginCaptures</key> <dict> <key>0</key> <dict> <key>name</key> <string>punctuation.definition.comment.shell</string> </dict> </dict> <key>end</key> <string>\n</string> <key>name</key> <string>comment.line.number-sign.shell</string> </dict> </array> </dict> <key>compound-command</key> <dict> <key>patterns</key> <array> <dict> <key>begin</key> <string>(\[{2})</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>punctuation.definition.logical-expression.shell</string> </dict> </dict> <key>end</key> <string>(\]{2})</string> <key>name</key> <string>meta.scope.logical-expression.shell</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#logical-expression</string> </dict> <dict> <key>include</key> <string>$self</string> </dict> </array> </dict> <dict> <key>begin</key> <string>(\({2})</string> <key>beginCaptures</key> <dict> <key>0</key> <dict> <key>name</key> <string>punctuation.definition.string.begin.shell</string> </dict> </dict> <key>end</key> <string>(\){2})</string> <key>endCaptures</key> <dict> <key>0</key> <dict> <key>name</key> <string>punctuation.definition.string.end.shell</string> </dict> </dict> <key>name</key> <string>string.other.math.shell</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#math</string> </dict> </array> </dict> <dict> <key>begin</key> <string>(\()</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>punctuation.definition.subshell.shell</string> </dict> </dict> <key>end</key> <string>(\))</string> <key>name</key> <string>meta.scope.subshell.shell</string> <key>patterns</key> <array> <dict> <key>include</key> <string>$self</string> </dict> </array> </dict> <dict> <key>begin</key> <string>(?&lt;=\s|^)(\{)(?=\s|$)</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>punctuation.definition.group.shell</string> </dict> </dict> <key>end</key> <string>(?&lt;=^|;)\s*(\})</string> <key>name</key> <string>meta.scope.group.shell</string> <key>patterns</key> <array> <dict> <key>include</key> <string>$self</string> </dict> </array> </dict> </array> </dict> <key>function-definition</key> <dict> <key>patterns</key> <array> <dict> <key>begin</key> <string>\b(function)\s+([^\s\\]+)(?:\s*(\(\)))?</string> <key>beginCaptures</key> <dict> <key>1</key> <dict> <key>name</key> <string>storage.type.function.shell</string> </dict> <key>2</key> <dict> <key>name</key> <string>entity.name.function.shell</string> </dict> <key>3</key> <dict> <key>name</key> <string>punctuation.definition.arguments.shell</string> </dict> </dict> <key>end</key> <string>;|&amp;|$</string> <key>endCaptures</key> <dict> <key>0</key> <dict> <key>name</key> <string>punctuation.definition.function.shell</string> </dict> </dict> <key>name</key> <string>meta.function.shell</string> <key>patterns</key> <array> <dict> <key>include</key> <string>$self</string> </dict> </array> </dict> <dict> <key>begin</key> <string>\b([^\s\\=]+)\s*(\(\))</string> <key>beginCaptures</key> <dict> <key>1</key> <dict> <key>name</key> <string>entity.name.function.shell</string> </dict> <key>2</key> <dict> <key>name</key> <string>punctuation.definition.arguments.shell</string> </dict> </dict> <key>end</key> <string>;|&amp;|$</string> <key>endCaptures</key> <dict> <key>0</key> <dict> <key>name</key> <string>punctuation.definition.function.shell</string> </dict> </dict> <key>name</key> <string>meta.function.shell</string> <key>patterns</key> <array> <dict> <key>include</key> <string>$self</string> </dict> </array> </dict> </array> </dict> <key>heredoc</key> <dict> <key>patterns</key> <array> <dict> <key>begin</key> <string>(&lt;&lt;)-("|'|)(RUBY)\2</string> <key>beginCaptures</key> <dict> <key>1</key> <dict> <key>name</key> <string>keyword.operator.heredoc.shell</string> </dict> <key>3</key> <dict> <key>name</key> <string>keyword.control.heredoc-token.shell</string> </dict> </dict> <key>captures</key> <dict> <key>0</key> <dict> <key>name</key> <string>punctuation.definition.string.shell</string> </dict> </dict> <key>contentName</key> <string>source.ruby.embedded.shell</string> <key>end</key> <string>^\t*(RUBY)\b</string> <key>endCaptures</key> <dict> <key>1</key> <dict> <key>name</key> <string>keyword.control.heredoc-token.shell</string> </dict> </dict> <key>name</key> <string>string.unquoted.heredoc.no-indent.ruby.shell</string> <key>patterns</key> <array> <dict> <key>include</key> <string>source.ruby</string> </dict> </array> </dict> <dict> <key>begin</key> <string>(&lt;&lt;)("|'|)(RUBY)\2</string> <key>beginCaptures</key> <dict> <key>1</key> <dict> <key>name</key> <string>keyword.operator.heredoc.shell</string> </dict> <key>3</key> <dict> <key>name</key> <string>keyword.control.heredoc-token.shell</string> </dict> </dict> <key>captures</key> <dict> <key>0</key> <dict> <key>name</key> <string>punctuation.definition.string.shell</string> </dict> </dict> <key>contentName</key> <string>source.ruby.embedded.shell</string> <key>end</key> <string>^(RUBY)\b</string> <key>endCaptures</key> <dict> <key>1</key> <dict> <key>name</key> <string>keyword.control.heredoc-token.shell</string> </dict> </dict> <key>name</key> <string>string.unquoted.heredoc.ruby.shell</string> <key>patterns</key> <array> <dict> <key>include</key> <string>source.ruby</string> </dict> </array> </dict> <dict> <key>begin</key> <string>(&lt;&lt;)-("|'|)(PYTHON)\2</string> <key>beginCaptures</key> <dict> <key>1</key> <dict> <key>name</key> <string>keyword.operator.heredoc.shell</string> </dict> <key>3</key> <dict> <key>name</key> <string>keyword.control.heredoc-token.shell</string> </dict> </dict> <key>captures</key> <dict> <key>0</key> <dict> <key>name</key> <string>punctuation.definition.string.shell</string> </dict> </dict> <key>contentName</key> <string>source.python.embedded.shell</string> <key>end</key> <string>^\t*(PYTHON)\b</string> <key>endCaptures</key> <dict> <key>1</key> <dict> <key>name</key> <string>keyword.control.heredoc-token.shell</string> </dict> </dict> <key>name</key> <string>string.unquoted.heredoc.no-indent.python.shell</string> <key>patterns</key> <array> <dict> <key>include</key> <string>source.python</string> </dict> </array> </dict> <dict> <key>begin</key> <string>(&lt;&lt;)("|'|)(PYTHON)\2</string> <key>beginCaptures</key> <dict> <key>1</key> <dict> <key>name</key> <string>keyword.operator.heredoc.shell</string> </dict> <key>3</key> <dict> <key>name</key> <string>keyword.control.heredoc-token.shell</string> </dict> </dict> <key>captures</key> <dict> <key>0</key> <dict> <key>name</key> <string>punctuation.definition.string.shell</string> </dict> </dict> <key>contentName</key> <string>source.python.embedded.shell</string> <key>end</key> <string>^(PYTHON)\b</string> <key>endCaptures</key> <dict> <key>1</key> <dict> <key>name</key> <string>keyword.control.heredoc-token.shell</string> </dict> </dict> <key>name</key> <string>string.unquoted.heredoc.python.shell</string> <key>patterns</key> <array> <dict> <key>include</key> <string>source.python</string> </dict> </array> </dict> <dict> <key>begin</key> <string>(&lt;&lt;)-("|'|)(APPLESCRIPT)\2</string> <key>beginCaptures</key> <dict> <key>1</key> <dict> <key>name</key> <string>keyword.operator.heredoc.shell</string> </dict> <key>3</key> <dict> <key>name</key> <string>keyword.control.heredoc-token.shell</string> </dict> </dict> <key>captures</key> <dict> <key>0</key> <dict> <key>name</key> <string>punctuation.definition.string.shell</string> </dict> </dict> <key>contentName</key> <string>source.applescript.embedded.shell</string> <key>end</key> <string>^\t*(APPLESCRIPT)\b</string> <key>endCaptures</key> <dict> <key>1</key> <dict> <key>name</key> <string>keyword.control.heredoc-token.shell</string> </dict> </dict> <key>name</key> <string>string.unquoted.heredoc.no-indent.applescript.shell</string> <key>patterns</key> <array> <dict> <key>include</key> <string>source.applescript</string> </dict> </array> </dict> <dict> <key>begin</key> <string>(&lt;&lt;)("|'|)(APPLESCRIPT)\2</string> <key>beginCaptures</key> <dict> <key>1</key> <dict> <key>name</key> <string>keyword.operator.heredoc.shell</string> </dict> <key>3</key> <dict> <key>name</key> <string>keyword.control.heredoc-token.shell</string> </dict> </dict> <key>captures</key> <dict> <key>0</key> <dict> <key>name</key> <string>punctuation.definition.string.shell</string> </dict> </dict> <key>contentName</key> <string>source.applescript.embedded.shell</string> <key>end</key> <string>^(APPLESCRIPT)\b</string> <key>endCaptures</key> <dict> <key>1</key> <dict> <key>name</key> <string>keyword.control.heredoc-token.shell</string> </dict> </dict> <key>name</key> <string>string.unquoted.heredoc.applescript.shell</string> <key>patterns</key> <array> <dict> <key>include</key> <string>source.applescript</string> </dict> </array> </dict> <dict> <key>begin</key> <string>(&lt;&lt;)-("|'|)(HTML)\2</string> <key>beginCaptures</key> <dict> <key>1</key> <dict> <key>name</key> <string>keyword.operator.heredoc.shell</string> </dict> <key>3</key> <dict> <key>name</key> <string>keyword.control.heredoc-token.shell</string> </dict> </dict> <key>captures</key> <dict> <key>0</key> <dict> <key>name</key> <string>punctuation.definition.string.shell</string> </dict> </dict> <key>contentName</key> <string>text.html.embedded.shell</string> <key>end</key> <string>^\t*(HTML)\b</string> <key>endCaptures</key> <dict> <key>1</key> <dict> <key>name</key> <string>keyword.control.heredoc-token.shell</string> </dict> </dict> <key>name</key> <string>string.unquoted.heredoc.no-indent.html.shell</string> <key>patterns</key> <array> <dict> <key>include</key> <string>text.html.basic</string> </dict> </array> </dict> <dict> <key>begin</key> <string>(&lt;&lt;)("|'|)(HTML)\2</string> <key>beginCaptures</key> <dict> <key>1</key> <dict> <key>name</key> <string>keyword.operator.heredoc.shell</string> </dict> <key>3</key> <dict> <key>name</key> <string>keyword.control.heredoc-token.shell</string> </dict> </dict> <key>captures</key> <dict> <key>0</key> <dict> <key>name</key> <string>punctuation.definition.string.shell</string> </dict> </dict> <key>contentName</key> <string>text.html.embedded.shell</string> <key>end</key> <string>^(HTML)\b</string> <key>endCaptures</key> <dict> <key>1</key> <dict> <key>name</key> <string>keyword.control.heredoc-token.shell</string> </dict> </dict> <key>name</key> <string>string.unquoted.heredoc.html.shell</string> <key>patterns</key> <array> <dict> <key>include</key> <string>text.html.basic</string> </dict> </array> </dict> <dict> <key>begin</key> <string>(&lt;&lt;)-("|'|)(MARKDOWN)\2</string> <key>beginCaptures</key> <dict> <key>1</key> <dict> <key>name</key> <string>keyword.operator.heredoc.shell</string> </dict> <key>3</key> <dict> <key>name</key> <string>keyword.control.heredoc-token.shell</string> </dict> </dict> <key>captures</key> <dict> <key>0</key> <dict> <key>name</key> <string>punctuation.definition.string.shell</string> </dict> </dict> <key>contentName</key> <string>text.html.markdown.embedded.shell</string> <key>end</key> <string>^\t*(MARKDOWN)\b</string> <key>endCaptures</key> <dict> <key>1</key> <dict> <key>name</key> <string>keyword.control.heredoc-token.shell</string> </dict> </dict> <key>name</key> <string>string.unquoted.heredoc.no-indent.markdown.shell</string> <key>patterns</key> <array> <dict> <key>include</key> <string>text.html.markdown</string> </dict> </array> </dict> <dict> <key>begin</key> <string>(&lt;&lt;)("|'|)(MARKDOWN)\2</string> <key>beginCaptures</key> <dict> <key>1</key> <dict> <key>name</key> <string>keyword.operator.heredoc.shell</string> </dict> <key>3</key> <dict> <key>name</key> <string>keyword.control.heredoc-token.shell</string> </dict> </dict> <key>captures</key> <dict> <key>0</key> <dict> <key>name</key> <string>punctuation.definition.string.shell</string> </dict> </dict> <key>contentName</key> <string>text.html.markdown.embedded.shell</string> <key>end</key> <string>^(MARKDOWN)\b</string> <key>endCaptures</key> <dict> <key>1</key> <dict> <key>name</key> <string>keyword.control.heredoc-token.shell</string> </dict> </dict> <key>name</key> <string>string.unquoted.heredoc.markdown.shell</string> <key>patterns</key> <array> <dict> <key>include</key> <string>text.html.markdown</string> </dict> </array> </dict> <dict> <key>begin</key> <string>(&lt;&lt;)-("|'|)(TEXTILE)\2</string> <key>beginCaptures</key> <dict> <key>1</key> <dict> <key>name</key> <string>keyword.operator.heredoc.shell</string> </dict> <key>3</key> <dict> <key>name</key> <string>keyword.control.heredoc-token.shell</string> </dict> </dict> <key>captures</key> <dict> <key>0</key> <dict> <key>name</key> <string>punctuation.definition.string.shell</string> </dict> </dict> <key>contentName</key> <string>text.html.textile.embedded.shell</string> <key>end</key> <string>^\t*(TEXTILE)\b</string> <key>endCaptures</key> <dict> <key>1</key> <dict> <key>name</key> <string>keyword.control.heredoc-token.shell</string> </dict> </dict> <key>name</key> <string>string.unquoted.heredoc.no-indent.textile.shell</string> <key>patterns</key> <array> <dict> <key>include</key> <string>text.html.textile</string> </dict> </array> </dict> <dict> <key>begin</key> <string>(&lt;&lt;)("|'|)(TEXTILE)\2</string> <key>beginCaptures</key> <dict> <key>1</key> <dict> <key>name</key> <string>keyword.operator.heredoc.shell</string> </dict> <key>3</key> <dict> <key>name</key> <string>keyword.control.heredoc-token.shell</string> </dict> </dict> <key>captures</key> <dict> <key>0</key> <dict> <key>name</key> <string>punctuation.definition.string.shell</string> </dict> </dict> <key>contentName</key> <string>text.html.textile.embedded.shell</string> <key>end</key> <string>^(TEXTILE)\b</string> <key>endCaptures</key> <dict> <key>1</key> <dict> <key>name</key> <string>keyword.control.heredoc-token.shell</string> </dict> </dict> <key>name</key> <string>string.unquoted.heredoc.textile.shell</string> <key>patterns</key> <array> <dict> <key>include</key> <string>text.html.textile</string> </dict> </array> </dict> <dict> <key>begin</key> <string>(&lt;&lt;)-("|'|)\\?(\w+)\2</string> <key>beginCaptures</key> <dict> <key>1</key> <dict> <key>name</key> <string>keyword.operator.heredoc.shell</string> </dict> <key>3</key> <dict> <key>name</key> <string>keyword.control.heredoc-token.shell</string> </dict> </dict> <key>captures</key> <dict> <key>0</key> <dict> <key>name</key> <string>punctuation.definition.string.shell</string> </dict> </dict> <key>end</key> <string>^\t*(\3)\b</string> <key>endCaptures</key> <dict> <key>1</key> <dict> <key>name</key> <string>keyword.control.heredoc-token.shell</string> </dict> </dict> <key>name</key> <string>string.unquoted.heredoc.no-indent.shell</string> </dict> <dict> <key>begin</key> <string>(&lt;&lt;)("|'|)\\?(\w+)\2</string> <key>beginCaptures</key> <dict> <key>1</key> <dict> <key>name</key> <string>keyword.operator.heredoc.shell</string> </dict> <key>3</key> <dict> <key>name</key> <string>keyword.control.heredoc-token.shell</string> </dict> </dict> <key>captures</key> <dict> <key>0</key> <dict> <key>name</key> <string>punctuation.definition.string.shell</string> </dict> </dict> <key>end</key> <string>^(\3)\b</string> <key>endCaptures</key> <dict> <key>1</key> <dict> <key>name</key> <string>keyword.control.heredoc-token.shell</string> </dict> </dict> <key>name</key> <string>string.unquoted.heredoc.shell</string> </dict> </array> </dict> <key>herestring</key> <dict> <key>patterns</key> <array> <dict> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>keyword.operator.herestring.shell</string> </dict> <key>2</key> <dict> <key>name</key> <string>string.quoted.single.herestring.shell</string> </dict> <key>3</key> <dict> <key>name</key> <string>punctuation.definition.string.begin.shell</string> </dict> <key>4</key> <dict> <key>name</key> <string>punctuation.definition.string.end.shell</string> </dict> </dict> <key>match</key> <string>(&lt;&lt;&lt;)((')[^']*('))</string> <key>name</key> <string>meta.herestring.shell</string> </dict> <dict> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>keyword.operator.herestring.shell</string> </dict> <key>2</key> <dict> <key>name</key> <string>string.quoted.double.herestring.shell</string> </dict> <key>3</key> <dict> <key>name</key> <string>punctuation.definition.string.begin.shell</string> </dict> <key>6</key> <dict> <key>name</key> <string>punctuation.definition.string.end.shell</string> </dict> </dict> <key>match</key> <string>(&lt;&lt;&lt;)((")(\\("|\\)|[^"])*("))</string> <key>name</key> <string>meta.herestring.shell</string> </dict> <dict> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>keyword.operator.herestring.shell</string> </dict> <key>2</key> <dict> <key>name</key> <string>string.unquoted.herestring.shell</string> </dict> </dict> <key>match</key> <string>(&lt;&lt;&lt;)(([^\s\\]|\\.)+)</string> <key>name</key> <string>meta.herestring.shell</string> </dict> </array> </dict> <key>interpolation</key> <dict> <key>patterns</key> <array> <dict> <key>begin</key> <string>\$\({2}</string> <key>beginCaptures</key> <dict> <key>0</key> <dict> <key>name</key> <string>punctuation.definition.string.begin.shell</string> </dict> </dict> <key>end</key> <string>\){2}</string> <key>endCaptures</key> <dict> <key>0</key> <dict> <key>name</key> <string>punctuation.definition.string.end.shell</string> </dict> </dict> <key>name</key> <string>string.other.math.shell</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#math</string> </dict> </array> </dict> <dict> <key>begin</key> <string>`</string> <key>beginCaptures</key> <dict> <key>0</key> <dict> <key>name</key> <string>punctuation.definition.string.begin.shell</string> </dict> </dict> <key>end</key> <string>`</string> <key>endCaptures</key> <dict> <key>0</key> <dict> <key>name</key> <string>punctuation.definition.string.end.shell</string> </dict> </dict> <key>name</key> <string>string.interpolated.backtick.shell</string> <key>patterns</key> <array> <dict> <key>match</key> <string>\\[`\\$]</string> <key>name</key> <string>constant.character.escape.shell</string> </dict> <dict> <key>include</key> <string>$self</string> </dict> </array> </dict> <dict> <key>begin</key> <string>\$\(</string> <key>beginCaptures</key> <dict> <key>0</key> <dict> <key>name</key> <string>punctuation.definition.string.begin.shell</string> </dict> </dict> <key>end</key> <string>\)</string> <key>endCaptures</key> <dict> <key>0</key> <dict> <key>name</key> <string>punctuation.definition.string.end.shell</string> </dict> </dict> <key>name</key> <string>string.interpolated.dollar.shell</string> <key>patterns</key> <array> <dict> <key>include</key> <string>$self</string> </dict> </array> </dict> </array> </dict> <key>keyword</key> <dict> <key>patterns</key> <array> <dict> <key>match</key> <string>\b(?:if|then|else|elif|fi|for|in|do|done|select|case|continue|esac|while|until|return)\b</string> <key>name</key> <string>keyword.control.shell</string> </dict> <dict> <key>match</key> <string>(?&lt;![-/])\b(?:export|declare|typeset|local|readonly)\b</string> <key>name</key> <string>storage.modifier.shell</string> </dict> </array> </dict> <key>list</key> <dict> <key>patterns</key> <array> <dict> <key>match</key> <string>;|&amp;&amp;|&amp;|\|\|</string> <key>name</key> <string>keyword.operator.list.shell</string> </dict> </array> </dict> <key>logical-expression</key> <dict> <key>patterns</key> <array> <dict> <key>comment</key> <string>do we want a special rule for ( expr )?</string> <key>match</key> <string>=[=~]?|!=?|&lt;|&gt;|&amp;&amp;|\|\|</string> <key>name</key> <string>keyword.operator.logical.shell</string> </dict> <dict> <key>match</key> <string>(?&lt;!\S)-(nt|ot|ef|eq|ne|l[te]|g[te]|[a-hknoprstuwxzOGLSN])</string> <key>name</key> <string>keyword.operator.logical.shell</string> </dict> </array> </dict> <key>loop</key> <dict> <key>patterns</key> <array> <dict> <key>begin</key> <string>\b(for)\s+(?=\({2})</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>keyword.control.shell</string> </dict> </dict> <key>end</key> <string>\b(done)\b</string> <key>name</key> <string>meta.scope.for-loop.shell</string> <key>patterns</key> <array> <dict> <key>include</key> <string>$self</string> </dict> </array> </dict> <dict> <key>begin</key> <string>\b(for)\s+((?:[^\s\\]|\\.)+)\b</string> <key>beginCaptures</key> <dict> <key>1</key> <dict> <key>name</key> <string>keyword.control.shell</string> </dict> <key>2</key> <dict> <key>name</key> <string>variable.other.loop.shell</string> </dict> </dict> <key>end</key> <string>\b(done)\b</string> <key>endCaptures</key> <dict> <key>1</key> <dict> <key>name</key> <string>keyword.control.shell</string> </dict> </dict> <key>name</key> <string>meta.scope.for-in-loop.shell</string> <key>patterns</key> <array> <dict> <key>include</key> <string>$self</string> </dict> </array> </dict> <dict> <key>begin</key> <string>\b(while|until)\b</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>keyword.control.shell</string> </dict> </dict> <key>end</key> <string>\b(done)\b</string> <key>name</key> <string>meta.scope.while-loop.shell</string> <key>patterns</key> <array> <dict> <key>include</key> <string>$self</string> </dict> </array> </dict> <dict> <key>begin</key> <string>\b(select)\s+((?:[^\s\\]|\\.)+)\b</string> <key>beginCaptures</key> <dict> <key>1</key> <dict> <key>name</key> <string>keyword.control.shell</string> </dict> <key>2</key> <dict> <key>name</key> <string>variable.other.loop.shell</string> </dict> </dict> <key>end</key> <string>\b(done)\b</string> <key>endCaptures</key> <dict> <key>1</key> <dict> <key>name</key> <string>keyword.control.shell</string> </dict> </dict> <key>name</key> <string>meta.scope.select-block.shell</string> <key>patterns</key> <array> <dict> <key>include</key> <string>$self</string> </dict> </array> </dict> <dict> <key>begin</key> <string>\b(case)\b</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>keyword.control.shell</string> </dict> </dict> <key>end</key> <string>\b(esac)\b</string> <key>name</key> <string>meta.scope.case-block.shell</string> <key>patterns</key> <array> <dict> <key>begin</key> <string>\b(?:in)\b</string> <key>beginCaptures</key> <dict> <key>1</key> <dict> <key>name</key> <string>keyword.control.shell</string> </dict> </dict> <key>end</key> <string>(?=\b(?:esac)\b)</string> <key>name</key> <string>meta.scope.case-body.shell</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#comment</string> </dict> <dict> <key>include</key> <string>#case-clause</string> </dict> <dict> <key>include</key> <string>$self</string> </dict> </array> </dict> <dict> <key>include</key> <string>$self</string> </dict> </array> </dict> <dict> <key>begin</key> <string>(^|(?&lt;=[&amp;;|]))\s*(if)\b</string> <key>beginCaptures</key> <dict> <key>2</key> <dict> <key>name</key> <string>keyword.control.shell</string> </dict> </dict> <key>comment</key> <string>Restrict match to avoid matching in lines like `dd if=/dev/sda1 …`</string> <key>end</key> <string>\b(fi)\b</string> <key>endCaptures</key> <dict> <key>1</key> <dict> <key>name</key> <string>keyword.control.shell</string> </dict> </dict> <key>name</key> <string>meta.scope.if-block.shell</string> <key>patterns</key> <array> <dict> <key>include</key> <string>$self</string> </dict> </array> </dict> </array> </dict> <key>math</key> <dict> <key>patterns</key> <array> <dict> <key>include</key> <string>#variable</string> </dict> <dict> <key>match</key> <string>\+{1,2}|-{1,2}|!|~|\*{1,2}|/|%|&lt;[&lt;=]?|&gt;[&gt;=]?|==|!=|\^|\|{1,2}|&amp;{1,2}|\?|\:|,|=|[*/%+\-&amp;^|]=|&lt;&lt;=|&gt;&gt;=</string> <key>name</key> <string>keyword.operator.arithmetic.shell</string> </dict> <dict> <key>match</key> <string>0[xX]\h+</string> <key>name</key> <string>constant.numeric.hex.shell</string> </dict> <dict> <key>match</key> <string>0\d+</string> <key>name</key> <string>constant.numeric.octal.shell</string> </dict> <dict> <key>match</key> <string>\d{1,2}#[0-9a-zA-Z@_]+</string> <key>name</key> <string>constant.numeric.other.shell</string> </dict> <dict> <key>match</key> <string>\d+</string> <key>name</key> <string>constant.numeric.integer.shell</string> </dict> </array> </dict> <key>pathname</key> <dict> <key>patterns</key> <array> <dict> <key>match</key> <string>(?&lt;=\s|:|=|^)~</string> <key>name</key> <string>keyword.operator.tilde.shell</string> </dict> <dict> <key>match</key> <string>\*|\?</string> <key>name</key> <string>keyword.operator.glob.shell</string> </dict> <dict> <key>begin</key> <string>([?*+@!])(\()</string> <key>beginCaptures</key> <dict> <key>1</key> <dict> <key>name</key> <string>keyword.operator.extglob.shell</string> </dict> <key>2</key> <dict> <key>name</key> <string>punctuation.definition.extglob.shell</string> </dict> </dict> <key>end</key> <string>(\))</string> <key>endCaptures</key> <dict> <key>1</key> <dict> <key>name</key> <string>punctuation.definition.extglob.shell</string> </dict> </dict> <key>name</key> <string>meta.structure.extglob.shell</string> <key>patterns</key> <array> <dict> <key>include</key> <string>$self</string> </dict> </array> </dict> </array> </dict> <key>pipeline</key> <dict> <key>patterns</key> <array> <dict> <key>match</key> <string>\b(time)\b</string> <key>name</key> <string>keyword.other.shell</string> </dict> <dict> <key>match</key> <string>[|!]</string> <key>name</key> <string>keyword.operator.pipe.shell</string> </dict> </array> </dict> <key>redirection</key> <dict> <key>patterns</key> <array> <dict> <key>begin</key> <string>[&gt;&lt;]\(</string> <key>beginCaptures</key> <dict> <key>0</key> <dict> <key>name</key> <string>punctuation.definition.string.begin.shell</string> </dict> </dict> <key>end</key> <string>\)</string> <key>endCaptures</key> <dict> <key>0</key> <dict> <key>name</key> <string>punctuation.definition.string.end.shell</string> </dict> </dict> <key>name</key> <string>string.interpolated.process-substitution.shell</string> <key>patterns</key> <array> <dict> <key>include</key> <string>$self</string> </dict> </array> </dict> <dict> <key>comment</key> <string>valid: &amp;&gt;word &gt;&amp;word &gt;word [n]&gt;&amp;[n] [n]&lt;word [n]&gt;word [n]&gt;&gt;word [n]&lt;&amp;word (last one is duplicate)</string> <key>match</key> <string>&amp;&gt;|\d*&gt;&amp;\d*|\d*(&gt;&gt;|&gt;|&lt;)|\d*&lt;&amp;|\d*&lt;&gt;</string> <key>name</key> <string>keyword.operator.redirect.shell</string> </dict> </array> </dict> <key>string</key> <dict> <key>patterns</key> <array> <dict> <key>match</key> <string>\\.</string> <key>name</key> <string>constant.character.escape.shell</string> </dict> <dict> <key>begin</key> <string>'</string> <key>beginCaptures</key> <dict> <key>0</key> <dict> <key>name</key> <string>punctuation.definition.string.begin.shell</string> </dict> </dict> <key>end</key> <string>'</string> <key>endCaptures</key> <dict> <key>0</key> <dict> <key>name</key> <string>punctuation.definition.string.end.shell</string> </dict> </dict> <key>name</key> <string>string.quoted.single.shell</string> </dict> <dict> <key>begin</key> <string>\$?"</string> <key>beginCaptures</key> <dict> <key>0</key> <dict> <key>name</key> <string>punctuation.definition.string.begin.shell</string> </dict> </dict> <key>end</key> <string>"</string> <key>endCaptures</key> <dict> <key>0</key> <dict> <key>name</key> <string>punctuation.definition.string.end.shell</string> </dict> </dict> <key>name</key> <string>string.quoted.double.shell</string> <key>patterns</key> <array> <dict> <key>match</key> <string>\\[\$`"\\\n]</string> <key>name</key> <string>constant.character.escape.shell</string> </dict> <dict> <key>include</key> <string>#variable</string> </dict> <dict> <key>include</key> <string>#interpolation</string> </dict> </array> </dict> <dict> <key>begin</key> <string>\$'</string> <key>beginCaptures</key> <dict> <key>0</key> <dict> <key>name</key> <string>punctuation.definition.string.begin.shell</string> </dict> </dict> <key>end</key> <string>'</string> <key>endCaptures</key> <dict> <key>0</key> <dict> <key>name</key> <string>punctuation.definition.string.end.shell</string> </dict> </dict> <key>name</key> <string>string.quoted.single.dollar.shell</string> <key>patterns</key> <array> <dict> <key>match</key> <string>\\(a|b|e|f|n|r|t|v|\\|')</string> <key>name</key> <string>constant.character.escape.ansi-c.shell</string> </dict> <dict> <key>match</key> <string>\\[0-9]{3}</string> <key>name</key> <string>constant.character.escape.octal.shell</string> </dict> <dict> <key>match</key> <string>\\x[0-9a-fA-F]{2}</string> <key>name</key> <string>constant.character.escape.hex.shell</string> </dict> <dict> <key>match</key> <string>\\c.</string> <key>name</key> <string>constant.character.escape.control-char.shell</string> </dict> </array> </dict> </array> </dict> <key>support</key> <dict> <key>patterns</key> <array> <dict> <key>match</key> <string>(?&lt;=^|\s)(?::|\.)(?=\s|;|&amp;|$)</string> <key>name</key> <string>support.function.builtin.shell</string> </dict> <dict> <key>match</key> <string>(?&lt;![-/])\b(?:alias|bg|bind|break|builtin|caller|cd|command|compgen|complete|dirs|disown|echo|enable|eval|exec|exit|false|fc|fg|getopts|hash|help|history|jobs|kill|let|logout|popd|printf|pushd|pwd|read|readonly|set|shift|shopt|source|suspend|test|times|trap|true|type|ulimit|umask|unalias|unset|wait)\b</string> <key>name</key> <string>support.function.builtin.shell</string> </dict> </array> </dict> <key>variable</key> <dict> <key>patterns</key> <array> <dict> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>punctuation.definition.variable.shell</string> </dict> </dict> <key>match</key> <string>(\$)[a-zA-Z_][a-zA-Z0-9_]*</string> <key>name</key> <string>variable.other.normal.shell</string> </dict> <dict> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>punctuation.definition.variable.shell</string> </dict> </dict> <key>match</key> <string>(\$)[-*@#?$!0_]</string> <key>name</key> <string>variable.other.special.shell</string> </dict> <dict> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>punctuation.definition.variable.shell</string> </dict> </dict> <key>match</key> <string>(\$)[1-9]</string> <key>name</key> <string>variable.other.positional.shell</string> </dict> <dict> <key>begin</key> <string>\$\{</string> <key>captures</key> <dict> <key>0</key> <dict> <key>name</key> <string>punctuation.definition.variable.shell</string> </dict> </dict> <key>end</key> <string>\}</string> <key>name</key> <string>variable.other.bracket.shell</string> <key>patterns</key> <array> <dict> <key>match</key> <string>!|:[-=?+]?|\*|@|#{1,2}|%{1,2}|/</string> <key>name</key> <string>keyword.operator.expansion.shell</string> </dict> <dict> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>punctuation.section.array.shell</string> </dict> <key>3</key> <dict> <key>name</key> <string>punctuation.section.array.shell</string> </dict> </dict> <key>match</key> <string>(\[)([^\]]+)(\])</string> </dict> <dict> <key>include</key> <string>#string</string> </dict> <dict> <key>include</key> <string>#variable</string> </dict> <dict> <key>include</key> <string>#interpolation</string> </dict> </array> </dict> </array> </dict> </dict> <key>scopeName</key> <string>source.shell</string> <key>uuid</key> <string>DDEEA3ED-6B1C-11D9-8B10-000D93589AF6</string> </dict> </plist>
extensions/shellscript/syntaxes/Shell-Unix-Bash.tmLanguage
0
https://github.com/microsoft/vscode/commit/8435ddcf464fd995936ff6f877ff4744dc3ca2b6
[ 0.00017587582988198847, 0.00017394286987837404, 0.0001673886872595176, 0.00017409404972568154, 0.0000012374133575576707 ]
{ "id": 1, "code_window": [ "\n", "\t\t// Right Container for Binary\n", "\t\tlet rightBinaryContainerElement = document.createElement('div');\n", "\t\trightBinaryContainerElement.className = 'binary-container';\n", "\t\tthis.rightBinaryContainer = $(rightBinaryContainerElement);\n", "\n", "\t\t// Right Custom Scrollbars\n", "\t\tthis.rightScrollbar = new ScrollableElement(rightBinaryContainerElement, { horizontal: 'hidden', vertical: 'hidden' });\n", "\t\tparent.getHTMLElement().appendChild(this.rightScrollbar.getDomNode());\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis.rightBinaryContainer.tabindex(0); // enable focus support from the editor part (do not remove)\n" ], "file_path": "src/vs/workbench/browser/parts/editor/binaryDiffEditor.ts", "type": "add", "edit_start_line_idx": 74 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import assert = require('assert'); import scanner = require('vs/languages/css/common/parser/cssScanner'); import lessScanner = require('vs/languages/less/common/parser/lessScanner'); function assertSingleToken(source: string, len: number, offset: number, text: string, type: scanner.TokenType, ignoreWhitespace?:boolean):void { var scan = new lessScanner.LessScanner(); scan.setSource(source); var token = scan.scan(ignoreWhitespace); assert.equal(token.len, len); assert.equal(token.offset, offset); assert.equal(token.text, text); assert.equal(token.type, type); } suite('LESS - Scanner', () => { test('Test Escaped JavaScript', function() { assertSingleToken('`', 1, 0, '`', scanner.TokenType.BadEscapedJavaScript); assertSingleToken('`a', 2, 0, '`a', scanner.TokenType.BadEscapedJavaScript); assertSingleToken('`var a = "ssss"`', 16, 0, '`var a = "ssss"`', scanner.TokenType.EscapedJavaScript); assertSingleToken('`var a = "ss\ns"`', 16, 0, '`var a = "ss\ns"`', scanner.TokenType.EscapedJavaScript); }); // less deactivated comments test('Test Token SingleLineComment', function() { assertSingleToken('//', 0, 2, '', scanner.TokenType.EOF); assertSingleToken('//this is a comment test', 0, 24, '', scanner.TokenType.EOF); assertSingleToken('// this is a comment test', 0, 25, '', scanner.TokenType.EOF); assertSingleToken('// this is a\na', 1, 13, 'a', scanner.TokenType.Ident); }); });
src/vs/languages/less/test/common/scanner.test.ts
0
https://github.com/microsoft/vscode/commit/8435ddcf464fd995936ff6f877ff4744dc3ca2b6
[ 0.0001778765144990757, 0.00017690841923467815, 0.00017639106954447925, 0.0001766830391716212, 5.860380838385026e-7 ]
{ "id": 1, "code_window": [ "\n", "\t\t// Right Container for Binary\n", "\t\tlet rightBinaryContainerElement = document.createElement('div');\n", "\t\trightBinaryContainerElement.className = 'binary-container';\n", "\t\tthis.rightBinaryContainer = $(rightBinaryContainerElement);\n", "\n", "\t\t// Right Custom Scrollbars\n", "\t\tthis.rightScrollbar = new ScrollableElement(rightBinaryContainerElement, { horizontal: 'hidden', vertical: 'hidden' });\n", "\t\tparent.getHTMLElement().appendChild(this.rightScrollbar.getDomNode());\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis.rightBinaryContainer.tabindex(0); // enable focus support from the editor part (do not remove)\n" ], "file_path": "src/vs/workbench/browser/parts/editor/binaryDiffEditor.ts", "type": "add", "edit_start_line_idx": 74 }
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16"><path d="M3 9v5h10v-5h-10z" fill="#424242"/><polygon points="7,8 9,8 9,5 11,7 11,5 8,2 5,5 5,7 7,5" fill="#00539C"/></svg>
src/vs/workbench/parts/git/browser/media/push.svg
0
https://github.com/microsoft/vscode/commit/8435ddcf464fd995936ff6f877ff4744dc3ca2b6
[ 0.00017479064990766346, 0.00017479064990766346, 0.00017479064990766346, 0.00017479064990766346, 0 ]
{ "id": 2, "code_window": [ "\t\t// Container for Binary\n", "\t\tlet binaryContainerElement = document.createElement('div');\n", "\t\tbinaryContainerElement.className = 'binary-container monaco-editor-background'; // Inherit the background color from selected theme'\n", "\t\tthis.binaryContainer = $(binaryContainerElement);\n", "\t\tparent.getHTMLElement().appendChild(this.binaryContainer.getHTMLElement());\n", "\t}\n", "\n", "\tpublic setInput(input: EditorInput, options: EditorOptions): TPromise<void> {\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis.binaryContainer.tabindex(0); // enable focus support from the editor part (do not remove)\n" ], "file_path": "src/vs/workbench/browser/parts/editor/binaryEditor.ts", "type": "add", "edit_start_line_idx": 42 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; // import 'vs/css!./media/iframeeditor'; import {localize} from 'vs/nls'; import {TPromise} from 'vs/base/common/winjs.base'; import {IModel, EventType} from 'vs/editor/common/editorCommon'; import {Dimension, Builder} from 'vs/base/browser/builder'; import {cAll} from 'vs/base/common/lifecycle'; import {EditorOptions, EditorInput} from 'vs/workbench/common/editor'; import {BaseEditor} from 'vs/workbench/browser/parts/editor/baseEditor'; import {Position} from 'vs/platform/editor/common/editor'; import {ITelemetryService} from 'vs/platform/telemetry/common/telemetry'; import {IStorageService, StorageEventType, StorageScope} from 'vs/platform/storage/common/storage'; import {IWorkbenchEditorService} from 'vs/workbench/services/editor/common/editorService'; import {BaseTextEditorModel} from 'vs/workbench/common/editor/textEditorModel'; import {Preferences} from 'vs/workbench/common/constants'; import {HtmlInput} from 'vs/workbench/parts/html/common/htmlInput'; import {isLightTheme} from 'vs/platform/theme/common/themes'; import {DEFAULT_THEME_ID} from 'vs/workbench/services/themes/common/themeService'; /** * An implementation of editor for showing HTML content in an IFrame by leveraging the IFrameEditorInput. */ export class HtmlPreviewPart extends BaseEditor { static ID: string = 'workbench.editor.htmlPreviewPart'; private _editorService: IWorkbenchEditorService; private _storageService: IStorageService; private _iFrameElement: HTMLIFrameElement; private _model: IModel; private _modelChangeUnbind: Function; private _lastModelVersion: number; private _themeChangeUnbind: Function; constructor( @ITelemetryService telemetryService: ITelemetryService, @IWorkbenchEditorService editorService: IWorkbenchEditorService, @IStorageService storageService: IStorageService ) { super(HtmlPreviewPart.ID, telemetryService); this._editorService = editorService; this._storageService = storageService; } dispose(): void { // remove from dome const element = this._iFrameElement.parentElement; element.parentElement.removeChild(element); // unhook from model this._modelChangeUnbind = cAll(this._modelChangeUnbind); this._model = undefined; this._themeChangeUnbind = cAll(this._themeChangeUnbind); } public createEditor(parent: Builder): void { // IFrame // this.iframeBuilder.removeProperty(IFrameEditor.RESOURCE_PROPERTY); this._iFrameElement = document.createElement('iframe'); this._iFrameElement.setAttribute('frameborder', '0'); this._iFrameElement.className = 'iframe'; // Container for IFrame const iFrameContainerElement = document.createElement('div'); iFrameContainerElement.className = 'iframe-container monaco-editor-background'; // Inherit the background color from selected theme iFrameContainerElement.appendChild(this._iFrameElement); parent.getHTMLElement().appendChild(iFrameContainerElement); this._themeChangeUnbind = this._storageService.addListener(StorageEventType.STORAGE, event => { if (event.key === Preferences.THEME && this.isVisible()) { this._updateIFrameContent(true); } }); } public layout(dimension: Dimension): void { let {width, height} = dimension; this._iFrameElement.parentElement.style.width = `${width}px`; this._iFrameElement.parentElement.style.height = `${height}px`; this._iFrameElement.style.width = `${width}px`; this._iFrameElement.style.height = `${height}px`; } public focus(): void { // this.iframeContainer.domFocus(); this._iFrameElement.focus(); } // --- input public getTitle(): string { if (!this.input) { return localize('iframeEditor', 'Preview Html'); } return this.input.getName(); } public setVisible(visible: boolean, position?: Position): TPromise<void> { return super.setVisible(visible, position).then(() => { if (visible && this._model) { this._modelChangeUnbind = this._model.addListener(EventType.ModelContentChanged2, () => this._updateIFrameContent()); this._updateIFrameContent(); } else { this._modelChangeUnbind = cAll(this._modelChangeUnbind); } }) } public changePosition(position: Position): void { super.changePosition(position); // reparenting an IFRAME into another DOM element yields weird results when the contents are made // of a string and not a URL. to be on the safe side we reload the iframe when the position changes // and we do it using a timeout of 0 to reload only after the position has been changed in the DOM setTimeout(() => { this._updateIFrameContent(true); }, 0); } public setInput(input: EditorInput, options: EditorOptions): TPromise<void> { this._model = undefined; this._modelChangeUnbind = cAll(this._modelChangeUnbind); this._lastModelVersion = -1; if (!(input instanceof HtmlInput)) { return TPromise.wrapError<void>('Invalid input'); } return this._editorService.resolveEditorModel({ resource: (<HtmlInput>input).getResource() }).then(model => { if (model instanceof BaseTextEditorModel) { this._model = model.textEditorModel } if (!this._model) { return TPromise.wrapError<void>(localize('html.voidInput', "Invalid editor input.")); } this._modelChangeUnbind = this._model.addListener(EventType.ModelContentChanged2, () => this._updateIFrameContent()); this._updateIFrameContent(); return super.setInput(input, options); }); } private _updateIFrameContent(refresh: boolean = false): void { if (!this._model || (!refresh && this._lastModelVersion === this._model.getVersionId())) { // nothing to do return; } const html = this._model.getValue(); const iFrameDocument = this._iFrameElement.contentDocument; if (!iFrameDocument) { // not visible anymore return; } // the very first time we load just our script // to integrate with the outside world if ((<HTMLElement>iFrameDocument.firstChild).innerHTML === '<head></head><body></body>') { iFrameDocument.open('text/html', 'replace'); iFrameDocument.write(Integration.defaultHtml()); iFrameDocument.close(); } // diff a little against the current input and the new state const parser = new DOMParser(); const newDocument = parser.parseFromString(html, 'text/html'); const styleElement = Integration.defaultStyle(this._iFrameElement.parentElement, this._storageService.get(Preferences.THEME, StorageScope.GLOBAL, DEFAULT_THEME_ID)); if (newDocument.head.hasChildNodes()) { newDocument.head.insertBefore(styleElement, newDocument.head.firstChild); } else { newDocument.head.appendChild(styleElement) } if (newDocument.head.innerHTML !== iFrameDocument.head.innerHTML) { iFrameDocument.head.innerHTML = newDocument.head.innerHTML; } if (newDocument.body.innerHTML !== iFrameDocument.body.innerHTML) { iFrameDocument.body.innerHTML = newDocument.body.innerHTML; } this._lastModelVersion = this._model.getVersionId(); } } namespace Integration { 'use strict'; const scriptSource = [ 'var ignoredKeys = [9 /* tab */, 32 /* space */, 33 /* page up */, 34 /* page down */, 38 /* up */, 40 /* down */];', 'var ignoredCtrlCmdKeys = [65 /* a */, 67 /* c */];', 'var ignoredShiftKeys = [9 /* tab */];', 'window.document.body.addEventListener("keydown", function(event) {', // Listen to keydown events in the iframe ' try {', ' if (ignoredKeys.some(function(i) { return i === event.keyCode; })) {', ' if (!event.ctrlKey && !event.altKey && !event.shiftKey && !event.metaKey) {', ' return;', // we want some single keys to be supported (e.g. Page Down for scrolling) ' }', ' }', '', ' if (ignoredCtrlCmdKeys.some(function(i) { return i === event.keyCode; })) {', ' if (event.ctrlKey || event.metaKey) {', ' return;', // we want some ctrl/cmd keys to be supported (e.g. Ctrl+C for copy) ' }', ' }', '', ' if (ignoredShiftKeys.some(function(i) { return i === event.keyCode; })) {', ' if (event.shiftKey) {', ' return;', // we want some shift keys to be supported (e.g. Shift+Tab for copy) ' }', ' }', '', ' event.preventDefault();', // very important to not get duplicate actions when this one bubbles up! '', ' var fakeEvent = document.createEvent("KeyboardEvent");', // create a keyboard event ' Object.defineProperty(fakeEvent, "keyCode", {', // we need to set some properties that Chrome wants ' get : function() {', ' return event.keyCode;', ' }', ' });', ' Object.defineProperty(fakeEvent, "which", {', ' get : function() {', ' return event.keyCode;', ' }', ' });', ' Object.defineProperty(fakeEvent, "target", {', ' get : function() {', ' return window && window.parent.document.body;', ' }', ' });', '', ' fakeEvent.initKeyboardEvent("keydown", true, true, document.defaultView, null, null, event.ctrlKey, event.altKey, event.shiftKey, event.metaKey);', // the API shape of this method is not clear to me, but it works ;) '', ' window.parent.document.dispatchEvent(fakeEvent);', // dispatch the event onto the parent ' } catch (error) {}', '});', // disable dropping into iframe! 'window.document.addEventListener("dragover", function (e) {', ' e.preventDefault();', '});', 'window.document.addEventListener("drop", function (e) {', ' e.preventDefault();', '});', 'window.document.body.addEventListener("dragover", function (e) {', ' e.preventDefault();', '});', 'window.document.body.addEventListener("drop", function (e) {', ' e.preventDefault();', '});' ]; export function defaultHtml() { let all = [ '<html><head></head><body><script>', ...scriptSource, '</script></body></html>', ]; return all.join('\n'); } const defaultLightScrollbarStyle = [ '::-webkit-scrollbar-thumb {', ' background-color: rgba(100, 100, 100, 0.4);', '}', '::-webkit-scrollbar-thumb:hover {', ' background-color: rgba(100, 100, 100, 0.7);', '}', '::-webkit-scrollbar-thumb:active {', ' background-color: rgba(0, 0, 0, 0.6);', '}' ].join('\n'); const defaultDarkScrollbarStyle = [ '::-webkit-scrollbar-thumb {', ' background-color: rgba(121, 121, 121, 0.4);', '}', '::-webkit-scrollbar-thumb:hover {', ' background-color: rgba(100, 100, 100, 0.7);', '}', '::-webkit-scrollbar-thumb:active {', ' background-color: rgba(85, 85, 85, 0.8);', '}' ].join('\n') export function defaultStyle(element: HTMLElement, themeId: string): HTMLStyleElement { const styles = window.getComputedStyle(element); const styleElement = document.createElement('style'); styleElement.innerHTML = `* { color: ${styles.color}; background: ${styles.background}; font-family: ${styles.fontFamily}; font-size: ${styles.fontSize}; } img { max-width: 100%; max-height: 100%; } a:focus, input:focus, select:focus, textarea:focus { outline: 1px solid -webkit-focus-ring-color; outline-offset: -1px; } ::-webkit-scrollbar { width: 14px; height: 14px; } ${isLightTheme(themeId) ? defaultLightScrollbarStyle : defaultDarkScrollbarStyle}`; return styleElement; } }
src/vs/workbench/parts/html/browser/htmlPreviewPart.ts
1
https://github.com/microsoft/vscode/commit/8435ddcf464fd995936ff6f877ff4744dc3ca2b6
[ 0.9984869956970215, 0.05784850940108299, 0.00016405165661126375, 0.0001711510994937271, 0.22844669222831726 ]
{ "id": 2, "code_window": [ "\t\t// Container for Binary\n", "\t\tlet binaryContainerElement = document.createElement('div');\n", "\t\tbinaryContainerElement.className = 'binary-container monaco-editor-background'; // Inherit the background color from selected theme'\n", "\t\tthis.binaryContainer = $(binaryContainerElement);\n", "\t\tparent.getHTMLElement().appendChild(this.binaryContainer.getHTMLElement());\n", "\t}\n", "\n", "\tpublic setInput(input: EditorInput, options: EditorOptions): TPromise<void> {\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis.binaryContainer.tabindex(0); // enable focus support from the editor part (do not remove)\n" ], "file_path": "src/vs/workbench/browser/parts/editor/binaryEditor.ts", "type": "add", "edit_start_line_idx": 42 }
{ "ms-vscode.omnisharp": "{**/*.cs,**/project.json,**/global.json,**/*.csproj,**/*.sln}", "msjsdiag.debugger-for-chrome": "{**/*.ts,**/*.tsx**/*.js,**/*.jsx,**/*.es6}", "lukehoban.Go": "**/*.go", "ms-vscode.PowerShell": "{**/*.ps,**/*.ps1}", "austin.code-gnu-global": "{**/*.c,**/*.cpp,**/*.h}", "Ionide.Ionide-fsharp": "{**/*.fsx,**/*.fsi,**/*.fs,**/*.ml,**/*.mli}", "dbaeumer.vscode-eslint": "{**/*.js,**/*.jsx,**/*.es6}", "eg2.tslint": "{**/*.ts,**/*.tsx}" }
src/vs/workbench/parts/extensions/electron-browser/extensionTips.json
0
https://github.com/microsoft/vscode/commit/8435ddcf464fd995936ff6f877ff4744dc3ca2b6
[ 0.0001737862330628559, 0.0001728973293211311, 0.0001720084110274911, 0.0001728973293211311, 8.889110176824033e-7 ]
{ "id": 2, "code_window": [ "\t\t// Container for Binary\n", "\t\tlet binaryContainerElement = document.createElement('div');\n", "\t\tbinaryContainerElement.className = 'binary-container monaco-editor-background'; // Inherit the background color from selected theme'\n", "\t\tthis.binaryContainer = $(binaryContainerElement);\n", "\t\tparent.getHTMLElement().appendChild(this.binaryContainer.getHTMLElement());\n", "\t}\n", "\n", "\tpublic setInput(input: EditorInput, options: EditorOptions): TPromise<void> {\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis.binaryContainer.tabindex(0); // enable focus support from the editor part (do not remove)\n" ], "file_path": "src/vs/workbench/browser/parts/editor/binaryEditor.ts", "type": "add", "edit_start_line_idx": 42 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; function createModuleDescription(name, exclude) { var result= {}; var excludes = ['vs/css', 'vs/nls', 'vs/text']; result.name= name; if (Array.isArray(exclude) && exclude.length > 0) { excludes = excludes.concat(exclude); } result.exclude= excludes; return result; } exports.collectModules= function(excludes) { var languageMainExcludes = ['vs/editor/common/languages.common']; var languageWorkerExcludes = ['vs/base/common/worker/workerServer', 'vs/editor/common/worker/editorWorkerServer']; return [ createModuleDescription('vs/workbench/electron-main/main', []), createModuleDescription('vs/workbench/parts/search/browser/searchViewlet', excludes), createModuleDescription('vs/workbench/parts/search/browser/openAnythingHandler', excludes), createModuleDescription('vs/workbench/parts/git/browser/gitViewlet', excludes), createModuleDescription('vs/workbench/parts/git/electron-browser/gitApp', []), createModuleDescription('vs/workbench/parts/git/electron-main/askpass', []), createModuleDescription('vs/workbench/parts/output/common/outputMode', languageMainExcludes), createModuleDescription('vs/workbench/parts/output/common/outputWorker', languageWorkerExcludes), createModuleDescription('vs/workbench/parts/output/browser/outputPanel', excludes), createModuleDescription('vs/workbench/parts/debug/browser/debugViewlet', excludes), createModuleDescription('vs/workbench/parts/debug/browser/repl', excludes), createModuleDescription('vs/workbench/services/search/node/searchApp', []), createModuleDescription('vs/workbench/services/files/node/watcher/unix/watcherApp', []), createModuleDescription('vs/workbench/node/pluginHostProcess', []), createModuleDescription('vs/workbench/electron-main/sharedProcessMain', []) ]; };
src/vs/workbench/buildfile.js
0
https://github.com/microsoft/vscode/commit/8435ddcf464fd995936ff6f877ff4744dc3ca2b6
[ 0.00017654470866546035, 0.000175127133843489, 0.00017281409236602485, 0.00017540088447276503, 0.0000012442085335351294 ]
{ "id": 2, "code_window": [ "\t\t// Container for Binary\n", "\t\tlet binaryContainerElement = document.createElement('div');\n", "\t\tbinaryContainerElement.className = 'binary-container monaco-editor-background'; // Inherit the background color from selected theme'\n", "\t\tthis.binaryContainer = $(binaryContainerElement);\n", "\t\tparent.getHTMLElement().appendChild(this.binaryContainer.getHTMLElement());\n", "\t}\n", "\n", "\tpublic setInput(input: EditorInput, options: EditorOptions): TPromise<void> {\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis.binaryContainer.tabindex(0); // enable focus support from the editor part (do not remove)\n" ], "file_path": "src/vs/workbench/browser/parts/editor/binaryEditor.ts", "type": "add", "edit_start_line_idx": 42 }
{ "name": "python", "version": "0.1.0", "publisher": "vscode", "engines": { "vscode": "*" }, "contributes": { "languages": [{ "id": "python", "extensions": [ ".py", ".rpy", ".pyw", ".cpy", ".gyp", ".gypi" ], "aliases": [ "Python", "py" ], "firstLine": "^#!/.*\\bpython[0-9.-]*\\b", "configuration": "./python.configuration.json" }], "grammars": [{ "language": "python", "scopeName": "source.python", "path": "./syntaxes/Python.tmLanguage" },{ "scopeName": "source.regexp.python", "path": "./syntaxes/Regular Expressions (Python).tmLanguage" }] } }
extensions/python/package.json
0
https://github.com/microsoft/vscode/commit/8435ddcf464fd995936ff6f877ff4744dc3ca2b6
[ 0.00017575061065144837, 0.0001745724439388141, 0.00017370174464304, 0.0001742649619700387, 8.642413718007447e-7 ]
{ "id": 3, "code_window": [ "\t\t// Container for IFrame\n", "\t\tlet iframeContainerElement = document.createElement('div');\n", "\t\tiframeContainerElement.className = 'iframe-container monaco-editor-background'; // Inherit the background color from selected theme\n", "\t\tthis.iframeContainer = $(iframeContainerElement);\n", "\n", "\t\t// IFrame\n", "\t\tthis.iframeBuilder = $(this.iframeContainer).element('iframe').addClass('iframe');\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis.iframeContainer.tabindex(0); // enable focus support from the editor part (do not remove)\n" ], "file_path": "src/vs/workbench/browser/parts/editor/iframeEditor.ts", "type": "add", "edit_start_line_idx": 54 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ .monaco-shell { height: 100%; width: 100%; color: #6C6C6C; margin: 0; padding: 0; overflow: hidden; font-family: "Segoe WPC", "Segoe UI", "SFUIText-Light", "HelveticaNeue-Light", sans-serif, "Droid Sans Fallback"; font-size: 11px; -webkit-user-select: none; -ms-user-select: none; -khtml-user-select: none; -moz-user-select: -moz-none; -o-user-select: none; user-select: none; } @-webkit-keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } } @-moz-keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } } @-ms-keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } } @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } } .monaco-shell img { border: 0; } .monaco-shell label { cursor: pointer; } .monaco-shell a { text-decoration: none; } .monaco-shell a.plain { color: inherit; text-decoration: none; } .monaco-shell a.plain:hover, .monaco-shell a.plain.hover { color: inherit; text-decoration: none; } /* START Keyboard Focus Indication Styles */ .monaco-shell.vs [tabindex="0"]:focus, .monaco-shell.vs .synthetic-focus, .monaco-shell.vs select:focus, .monaco-shell.vs input[type="button"]:focus, .monaco-shell.vs input[type="submit"]:focus, .monaco-shell.vs input[type="text"]:focus, .monaco-shell.vs textarea:focus, .monaco-shell.vs input[type="checkbox"]:focus { outline: 1px solid rgba(0, 122, 204, 0.4); outline-offset: -1px; opacity: 1 !important; } .monaco-shell.vs-dark [tabindex="0"]:focus, .monaco-shell.vs-dark .synthetic-focus, .monaco-shell.vs-dark select:focus, .monaco-shell.vs-dark input[type="button"]:focus, .monaco-shell.vs-dark input[type="submit"]:focus, .monaco-shell.vs-dark input[type="text"]:focus, .monaco-shell.vs-dark textarea:focus, .monaco-shell.vs-dark input[type="checkbox"]:focus { outline: 1px solid rgba(14, 99, 156, 0.6); outline-offset: -1px; opacity: 1 !important; } .monaco-shell.hc-black [tabindex="0"]:focus, .monaco-shell.hc-black .synthetic-focus, .monaco-shell.hc-black select:focus, .monaco-shell.hc-black input[type="button"]:focus, .monaco-shell.hc-black input[type="submit"]:focus, .monaco-shell.hc-black input[type="text"]:focus, .monaco-shell.hc-black textarea:focus, .monaco-shell.hc-black input[type="checkbox"]:focus { outline: 2px solid #DF740C; outline-offset: -2px; } .monaco-shell.vs .monaco-tree.focused .monaco-tree-row.focused [tabindex="0"]:focus { outline: 1px solid #007ACC; /* higher contrast color for focusable elements in a row that shows focus feedback */ } .monaco-shell.vs-dark .monaco-tree.focused .monaco-tree-row.focused [tabindex="0"]:focus { outline: 1px solid #007ACC; /* higher contrast color for focusable elements in a row that shows focus feedback */ } .monaco-shell .monaco-tree.focused.no-item-focus:focus:before { position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: 5; /* make sure we are on top of the tree items */ content: ""; pointer-events: none; /* enable click through */ } .monaco-shell.vs .monaco-tree.focused.no-item-focus:focus:before { outline: 1px solid rgba(0, 122, 204, 0.4); /* we still need to handle the empty tree or no focus item case */ outline-offset: -1px; } .monaco-shell.vs-dark .monaco-tree.focused.no-item-focus:focus:before { outline: 1px solid rgba(14, 99, 156, 0.6); /* we still need to handle the empty tree or no focus item case */ outline-offset: -1px; } .monaco-shell.hc-black .monaco-tree.focused.no-item-focus:focus:before { outline: 2px solid #DF740C; /* we still need to handle the empty tree or no focus item case */ outline-offset: -2px; } .monaco-shell .synthetic-focus :focus { outline: 0 !important; /* elements within widgets that draw synthetic-focus should never show focus */ } .monaco-shell .monaco-inputbox.info.synthetic-focus, .monaco-shell .monaco-inputbox.warning.synthetic-focus, .monaco-shell .monaco-inputbox.error.synthetic-focus, .monaco-shell .monaco-inputbox.info input[type="text"]:focus, .monaco-shell .monaco-inputbox.warning input[type="text"]:focus, .monaco-shell .monaco-inputbox.error input[type="text"]:focus { outline: 0 !important; /* outline is not going well with decoration */ } .monaco-shell .monaco-tree.focused:focus { outline: 0; /* tree indicates focus not via outline but through the focussed item */ } .monaco-shell [tabindex="0"]:active, .monaco-shell select:active, .monaco-shell input[type="button"]:active, .monaco-shell input[type="submit"]:active, .monaco-shell input[type="checkbox"]:active, .monaco-shell .monaco-tree.focused.no-item-focus:active:before { outline: 0 !important; /* fixes some flashing outlines from showing up when clicking */ } .monaco-shell .activitybar [tabindex="0"]:focus { outline: 0; /* activity bar indicates focus custom */ } /* END Keyboard Focus Indication Styles */ .monaco-shell a.prominent { text-decoration: underline; } .monaco-shell a.strong { font-weight: bold; } a:active { color: inherit; background-color: inherit; } .monaco-shell input { font-family: "Segoe UI", "SFUIText-Light", "HelveticaNeue-Light", sans-serif, "Droid Sans Fallback"; color: inherit; } .monaco-shell select { font-family: "Segoe UI","SFUIText-Light", "HelveticaNeue-Light", sans-serif, "Droid Sans Fallback"; } .monaco-shell .pointer { cursor: pointer; } .monaco-shell .context-view .tooltip { background-color: white; border: 1px solid #ccc; } .monaco-shell .context-view.bottom.right .tooltip:before { border-width: 6px; border-bottom: 6px solid #ccc; } .monaco-shell .context-view.bottom.right .tooltip:after { border-width: 5px; border-bottom: 5px solid white; } .monaco-shell .context-view .monaco-menu .actions-container { min-width: 160px; } .monaco-shell .monaco-menu .action-label.check { font-weight: bold; } .monaco-shell .monaco-menu .action-label.uncheck { font-weight: normal; } /* Notifications */ .monaco-shell .monaco-notification-container { position: absolute; width: 100%; height: 400px; top: calc(50% - 200px); top: -moz-calc(50% - 200px); top: -webkit-calc(50% - 200px); top: -ms-calc(50% - 200px); top: -o-calc(50% - 200px); background-color: #0E6198; color: white; border-top: 2px solid transparent; border-bottom: 2px solid transparent; } .monaco-shell .monaco-notification-container a { color: inherit; opacity: 0.6; text-decoration: underline; } .monaco-shell .monaco-notification-container .buttons { margin-top: 2em; } .monaco-shell .monaco-notification-container button { color: inherit; text-decoration: none; display: inline-block; padding: 6px 16px; margin-right: 12px; font-family: 'Segoe UI Semibold', "Segoe UI", "SFUIText-Light", "HelveticaNeue-Light", sans-serif, "Droid Sans Fallback"; font-weight: 400; font-size: 12px; min-width: 65px; border: 2px solid #fff; background-color: transparent; -moz-box-sizing: border-box; box-sizing: border-box; cursor: pointer; } .monaco-shell .monaco-notification-container button.default { background-color: rgba(255, 255, 255, 0.2); } .monaco-shell .monaco-notification-container button:disabled { opacity: 0.4; } .monaco-shell .monaco-notification-container button:not(:disabled):hover { color: inherit; background-color: rgba(255, 255, 255, 0.1); } .monaco-shell .monaco-notification-container button.default:not(:disabled)hover { background-color: rgba(255, 255, 255, 0.3); } .monaco-shell .monaco-notification-container > .notification { max-width: 800px; height: 100%; margin: 0 auto; padding: 0 16px; overflow-y: auto; overflow-x: hidden; font-family: "Segoe WPC", "Segoe UI", "SFUIText-Light", "HelveticaNeue-Light", sans-serif, "Droid Sans Fallback"; font-size: 14px; } .monaco-shell .monaco-notification-container > .notification > .notification-title { font-family: "Segoe UI Light", "Segoe UI", "SFUIText-Light", "HelveticaNeue-Light", "Helvetica Neue", sans-serif, "Droid Sans Fallback"; font-weight: 300; font-size: 2.5em; } .monaco-shell input:disabled { background-color: #E1E1E1; } /** * Dark Theme */ .monaco-shell.vs-dark { color: #BBB; background-color: #1E1E1E; } .monaco-shell.vs-dark .monaco-action-bar.vertical .action-label.separator { border-bottom-color: #666; } .monaco-shell.vs-dark .context-view .tooltip { background-color: #1E1E1E; border-color: #707070; } .monaco-shell.vs-dark .context-view.bottom.right .tooltip:before { border-bottom: 6px solid #707070; } .monaco-shell.vs-dark .context-view.bottom.right .tooltip:after { border-bottom: 5px solid #1E1E1E; } .monaco-shell.vs-dark input:disabled { background-color: #333; } /** * High Contrast Theme */ .monaco-shell.hc-black { color: #fff; background-color: #000; } .monaco-shell.hc-black .monaco-modal-view.visible .monaco-modal-view-background { opacity: 0.6; } .monaco-shell.hc-black .monaco-notification-container { background-color: #0C141F; color: white; border-top: 2px solid #6FC3DF; border-bottom: 2px solid #6FC3DF; } .monaco-shell.hc-black .monaco-notification-container input { background-color: #000; } .monaco-shell.hc-black .context-view .tooltip { background-color: black; } .monaco-shell.hc-black .context-view .tooltip:before { border-width: 0 !important; } .monaco-shell.hc-black .context-view .tooltip:after { border-width: 0 !important; }
src/vs/workbench/electron-browser/media/shell.css
1
https://github.com/microsoft/vscode/commit/8435ddcf464fd995936ff6f877ff4744dc3ca2b6
[ 0.0002794697938952595, 0.0001760628802003339, 0.00016363748000003397, 0.00016702407447155565, 0.0000214949031942524 ]
{ "id": 3, "code_window": [ "\t\t// Container for IFrame\n", "\t\tlet iframeContainerElement = document.createElement('div');\n", "\t\tiframeContainerElement.className = 'iframe-container monaco-editor-background'; // Inherit the background color from selected theme\n", "\t\tthis.iframeContainer = $(iframeContainerElement);\n", "\n", "\t\t// IFrame\n", "\t\tthis.iframeBuilder = $(this.iframeContainer).element('iframe').addClass('iframe');\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis.iframeContainer.tabindex(0); // enable focus support from the editor part (do not remove)\n" ], "file_path": "src/vs/workbench/browser/parts/editor/iframeEditor.ts", "type": "add", "edit_start_line_idx": 54 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ /// <reference path='../../../../src/vs/vscode.d.ts'/> /// <reference path='../../../../src/typings/mocha.d.ts'/> /// <reference path='../../../../extensions/declares.d.ts'/> /// <reference path='../../../../extensions/node.d.ts'/> /// <reference path='../../../../extensions/lib.core.d.ts'/>
extensions/vscode-api-tests/src/typings/ref.d.ts
0
https://github.com/microsoft/vscode/commit/8435ddcf464fd995936ff6f877ff4744dc3ca2b6
[ 0.00017359676712658256, 0.0001735729310894385, 0.00017354909505229443, 0.0001735729310894385, 2.3836037144064903e-8 ]
{ "id": 3, "code_window": [ "\t\t// Container for IFrame\n", "\t\tlet iframeContainerElement = document.createElement('div');\n", "\t\tiframeContainerElement.className = 'iframe-container monaco-editor-background'; // Inherit the background color from selected theme\n", "\t\tthis.iframeContainer = $(iframeContainerElement);\n", "\n", "\t\t// IFrame\n", "\t\tthis.iframeBuilder = $(this.iframeContainer).element('iframe').addClass('iframe');\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis.iframeContainer.tabindex(0); // enable focus support from the editor part (do not remove)\n" ], "file_path": "src/vs/workbench/browser/parts/editor/iframeEditor.ts", "type": "add", "edit_start_line_idx": 54 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import {ViewEventHandler} from 'vs/editor/common/viewModel/viewEventHandler'; import EditorBrowser = require('vs/editor/browser/editorBrowser'); export interface IRunner { (): void; } export class ViewPart extends ViewEventHandler implements EditorBrowser.IViewPart { _context:EditorBrowser.IViewContext; private _modificationBeforeRenderingRunners:IRunner[]; private _modificationRunners:IRunner[]; constructor(context:EditorBrowser.IViewContext) { super(); this._context = context; this._context.addEventHandler(this); this._modificationBeforeRenderingRunners = []; this._modificationRunners = []; } public dispose(): void { this._context.removeEventHandler(this); this._context = null; this._modificationBeforeRenderingRunners = []; this._modificationRunners = []; } /** * Modify the DOM right before when the orchestrated rendering occurs. */ _requestModificationFrameBeforeRendering(runner:IRunner): void { this._modificationBeforeRenderingRunners.push(runner); } /** * Modify the DOM when the orchestrated rendering occurs. */ _requestModificationFrame(runner:IRunner): void { this._modificationRunners.push(runner); } public onBeforeForcedLayout(): void { if (this._modificationBeforeRenderingRunners.length > 0) { for (var i = 0; i < this._modificationBeforeRenderingRunners.length; i++) { this._modificationBeforeRenderingRunners[i](); } this._modificationBeforeRenderingRunners = []; } } public onReadAfterForcedLayout(ctx:EditorBrowser.IRenderingContext): void { if (!this.shouldRender) { return; } this._render(ctx); } public onWriteAfterForcedLayout(): void { if (!this.shouldRender) { return; } this.shouldRender = false; this._executeModificationRunners(); } _executeModificationRunners(): void { if (this._modificationRunners.length > 0) { for (var i = 0; i < this._modificationRunners.length; i++) { this._modificationRunners[i](); } this._modificationRunners = []; } } _render(ctx:EditorBrowser.IRenderingContext): void { throw new Error('Implement me!'); } }
src/vs/editor/browser/view/viewPart.ts
0
https://github.com/microsoft/vscode/commit/8435ddcf464fd995936ff6f877ff4744dc3ca2b6
[ 0.0001910538412630558, 0.00017322393250651658, 0.00016721912834327668, 0.00017104785365518183, 0.000006774750545446295 ]
{ "id": 3, "code_window": [ "\t\t// Container for IFrame\n", "\t\tlet iframeContainerElement = document.createElement('div');\n", "\t\tiframeContainerElement.className = 'iframe-container monaco-editor-background'; // Inherit the background color from selected theme\n", "\t\tthis.iframeContainer = $(iframeContainerElement);\n", "\n", "\t\t// IFrame\n", "\t\tthis.iframeBuilder = $(this.iframeContainer).element('iframe').addClass('iframe');\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis.iframeContainer.tabindex(0); // enable focus support from the editor part (do not remove)\n" ], "file_path": "src/vs/workbench/browser/parts/editor/iframeEditor.ts", "type": "add", "edit_start_line_idx": 54 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import * as Proto from '../protocol'; export interface IHTMLContentElement { formattedText?: string; text?: string; className?: string; style?: string; customStyle?: any; tagName?: string; children?: IHTMLContentElement[]; isText?: boolean; } export function html(parts: Proto.SymbolDisplayPart[], className: string = ''): IHTMLContentElement { if (!parts) { return {}; } let htmlParts = parts.map(part => { return <IHTMLContentElement>{ tagName: 'span', text: part.text, className: part.kind }; }); return { tagName: 'div', className: 'ts-symbol ' + className, children: htmlParts }; } export function plain(parts: Proto.SymbolDisplayPart[]): string { if (!parts) { return ''; } return parts.map(part => part.text).join(''); }
extensions/typescript/src/features/previewer.ts
0
https://github.com/microsoft/vscode/commit/8435ddcf464fd995936ff6f877ff4744dc3ca2b6
[ 0.0013347803615033627, 0.00040205830009654164, 0.00016518383927177638, 0.00016913424769882113, 0.0004663664731197059 ]
{ "id": 4, "code_window": [ "}\n", "\n", ".monaco-shell .monaco-tree.focused:focus {\n", "\toutline: 0; /* tree indicates focus not via outline but through the focussed item */\n", "}\n", "\n", ".monaco-shell [tabindex=\"0\"]:active,\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\toutline: 0 !important; /* tree indicates focus not via outline but through the focussed item */\n" ], "file_path": "src/vs/workbench/electron-browser/media/shell.css", "type": "replace", "edit_start_line_idx": 134 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; // import 'vs/css!./media/iframeeditor'; import {localize} from 'vs/nls'; import {TPromise} from 'vs/base/common/winjs.base'; import {IModel, EventType} from 'vs/editor/common/editorCommon'; import {Dimension, Builder} from 'vs/base/browser/builder'; import {cAll} from 'vs/base/common/lifecycle'; import {EditorOptions, EditorInput} from 'vs/workbench/common/editor'; import {BaseEditor} from 'vs/workbench/browser/parts/editor/baseEditor'; import {Position} from 'vs/platform/editor/common/editor'; import {ITelemetryService} from 'vs/platform/telemetry/common/telemetry'; import {IStorageService, StorageEventType, StorageScope} from 'vs/platform/storage/common/storage'; import {IWorkbenchEditorService} from 'vs/workbench/services/editor/common/editorService'; import {BaseTextEditorModel} from 'vs/workbench/common/editor/textEditorModel'; import {Preferences} from 'vs/workbench/common/constants'; import {HtmlInput} from 'vs/workbench/parts/html/common/htmlInput'; import {isLightTheme} from 'vs/platform/theme/common/themes'; import {DEFAULT_THEME_ID} from 'vs/workbench/services/themes/common/themeService'; /** * An implementation of editor for showing HTML content in an IFrame by leveraging the IFrameEditorInput. */ export class HtmlPreviewPart extends BaseEditor { static ID: string = 'workbench.editor.htmlPreviewPart'; private _editorService: IWorkbenchEditorService; private _storageService: IStorageService; private _iFrameElement: HTMLIFrameElement; private _model: IModel; private _modelChangeUnbind: Function; private _lastModelVersion: number; private _themeChangeUnbind: Function; constructor( @ITelemetryService telemetryService: ITelemetryService, @IWorkbenchEditorService editorService: IWorkbenchEditorService, @IStorageService storageService: IStorageService ) { super(HtmlPreviewPart.ID, telemetryService); this._editorService = editorService; this._storageService = storageService; } dispose(): void { // remove from dome const element = this._iFrameElement.parentElement; element.parentElement.removeChild(element); // unhook from model this._modelChangeUnbind = cAll(this._modelChangeUnbind); this._model = undefined; this._themeChangeUnbind = cAll(this._themeChangeUnbind); } public createEditor(parent: Builder): void { // IFrame // this.iframeBuilder.removeProperty(IFrameEditor.RESOURCE_PROPERTY); this._iFrameElement = document.createElement('iframe'); this._iFrameElement.setAttribute('frameborder', '0'); this._iFrameElement.className = 'iframe'; // Container for IFrame const iFrameContainerElement = document.createElement('div'); iFrameContainerElement.className = 'iframe-container monaco-editor-background'; // Inherit the background color from selected theme iFrameContainerElement.appendChild(this._iFrameElement); parent.getHTMLElement().appendChild(iFrameContainerElement); this._themeChangeUnbind = this._storageService.addListener(StorageEventType.STORAGE, event => { if (event.key === Preferences.THEME && this.isVisible()) { this._updateIFrameContent(true); } }); } public layout(dimension: Dimension): void { let {width, height} = dimension; this._iFrameElement.parentElement.style.width = `${width}px`; this._iFrameElement.parentElement.style.height = `${height}px`; this._iFrameElement.style.width = `${width}px`; this._iFrameElement.style.height = `${height}px`; } public focus(): void { // this.iframeContainer.domFocus(); this._iFrameElement.focus(); } // --- input public getTitle(): string { if (!this.input) { return localize('iframeEditor', 'Preview Html'); } return this.input.getName(); } public setVisible(visible: boolean, position?: Position): TPromise<void> { return super.setVisible(visible, position).then(() => { if (visible && this._model) { this._modelChangeUnbind = this._model.addListener(EventType.ModelContentChanged2, () => this._updateIFrameContent()); this._updateIFrameContent(); } else { this._modelChangeUnbind = cAll(this._modelChangeUnbind); } }) } public changePosition(position: Position): void { super.changePosition(position); // reparenting an IFRAME into another DOM element yields weird results when the contents are made // of a string and not a URL. to be on the safe side we reload the iframe when the position changes // and we do it using a timeout of 0 to reload only after the position has been changed in the DOM setTimeout(() => { this._updateIFrameContent(true); }, 0); } public setInput(input: EditorInput, options: EditorOptions): TPromise<void> { this._model = undefined; this._modelChangeUnbind = cAll(this._modelChangeUnbind); this._lastModelVersion = -1; if (!(input instanceof HtmlInput)) { return TPromise.wrapError<void>('Invalid input'); } return this._editorService.resolveEditorModel({ resource: (<HtmlInput>input).getResource() }).then(model => { if (model instanceof BaseTextEditorModel) { this._model = model.textEditorModel } if (!this._model) { return TPromise.wrapError<void>(localize('html.voidInput', "Invalid editor input.")); } this._modelChangeUnbind = this._model.addListener(EventType.ModelContentChanged2, () => this._updateIFrameContent()); this._updateIFrameContent(); return super.setInput(input, options); }); } private _updateIFrameContent(refresh: boolean = false): void { if (!this._model || (!refresh && this._lastModelVersion === this._model.getVersionId())) { // nothing to do return; } const html = this._model.getValue(); const iFrameDocument = this._iFrameElement.contentDocument; if (!iFrameDocument) { // not visible anymore return; } // the very first time we load just our script // to integrate with the outside world if ((<HTMLElement>iFrameDocument.firstChild).innerHTML === '<head></head><body></body>') { iFrameDocument.open('text/html', 'replace'); iFrameDocument.write(Integration.defaultHtml()); iFrameDocument.close(); } // diff a little against the current input and the new state const parser = new DOMParser(); const newDocument = parser.parseFromString(html, 'text/html'); const styleElement = Integration.defaultStyle(this._iFrameElement.parentElement, this._storageService.get(Preferences.THEME, StorageScope.GLOBAL, DEFAULT_THEME_ID)); if (newDocument.head.hasChildNodes()) { newDocument.head.insertBefore(styleElement, newDocument.head.firstChild); } else { newDocument.head.appendChild(styleElement) } if (newDocument.head.innerHTML !== iFrameDocument.head.innerHTML) { iFrameDocument.head.innerHTML = newDocument.head.innerHTML; } if (newDocument.body.innerHTML !== iFrameDocument.body.innerHTML) { iFrameDocument.body.innerHTML = newDocument.body.innerHTML; } this._lastModelVersion = this._model.getVersionId(); } } namespace Integration { 'use strict'; const scriptSource = [ 'var ignoredKeys = [9 /* tab */, 32 /* space */, 33 /* page up */, 34 /* page down */, 38 /* up */, 40 /* down */];', 'var ignoredCtrlCmdKeys = [65 /* a */, 67 /* c */];', 'var ignoredShiftKeys = [9 /* tab */];', 'window.document.body.addEventListener("keydown", function(event) {', // Listen to keydown events in the iframe ' try {', ' if (ignoredKeys.some(function(i) { return i === event.keyCode; })) {', ' if (!event.ctrlKey && !event.altKey && !event.shiftKey && !event.metaKey) {', ' return;', // we want some single keys to be supported (e.g. Page Down for scrolling) ' }', ' }', '', ' if (ignoredCtrlCmdKeys.some(function(i) { return i === event.keyCode; })) {', ' if (event.ctrlKey || event.metaKey) {', ' return;', // we want some ctrl/cmd keys to be supported (e.g. Ctrl+C for copy) ' }', ' }', '', ' if (ignoredShiftKeys.some(function(i) { return i === event.keyCode; })) {', ' if (event.shiftKey) {', ' return;', // we want some shift keys to be supported (e.g. Shift+Tab for copy) ' }', ' }', '', ' event.preventDefault();', // very important to not get duplicate actions when this one bubbles up! '', ' var fakeEvent = document.createEvent("KeyboardEvent");', // create a keyboard event ' Object.defineProperty(fakeEvent, "keyCode", {', // we need to set some properties that Chrome wants ' get : function() {', ' return event.keyCode;', ' }', ' });', ' Object.defineProperty(fakeEvent, "which", {', ' get : function() {', ' return event.keyCode;', ' }', ' });', ' Object.defineProperty(fakeEvent, "target", {', ' get : function() {', ' return window && window.parent.document.body;', ' }', ' });', '', ' fakeEvent.initKeyboardEvent("keydown", true, true, document.defaultView, null, null, event.ctrlKey, event.altKey, event.shiftKey, event.metaKey);', // the API shape of this method is not clear to me, but it works ;) '', ' window.parent.document.dispatchEvent(fakeEvent);', // dispatch the event onto the parent ' } catch (error) {}', '});', // disable dropping into iframe! 'window.document.addEventListener("dragover", function (e) {', ' e.preventDefault();', '});', 'window.document.addEventListener("drop", function (e) {', ' e.preventDefault();', '});', 'window.document.body.addEventListener("dragover", function (e) {', ' e.preventDefault();', '});', 'window.document.body.addEventListener("drop", function (e) {', ' e.preventDefault();', '});' ]; export function defaultHtml() { let all = [ '<html><head></head><body><script>', ...scriptSource, '</script></body></html>', ]; return all.join('\n'); } const defaultLightScrollbarStyle = [ '::-webkit-scrollbar-thumb {', ' background-color: rgba(100, 100, 100, 0.4);', '}', '::-webkit-scrollbar-thumb:hover {', ' background-color: rgba(100, 100, 100, 0.7);', '}', '::-webkit-scrollbar-thumb:active {', ' background-color: rgba(0, 0, 0, 0.6);', '}' ].join('\n'); const defaultDarkScrollbarStyle = [ '::-webkit-scrollbar-thumb {', ' background-color: rgba(121, 121, 121, 0.4);', '}', '::-webkit-scrollbar-thumb:hover {', ' background-color: rgba(100, 100, 100, 0.7);', '}', '::-webkit-scrollbar-thumb:active {', ' background-color: rgba(85, 85, 85, 0.8);', '}' ].join('\n') export function defaultStyle(element: HTMLElement, themeId: string): HTMLStyleElement { const styles = window.getComputedStyle(element); const styleElement = document.createElement('style'); styleElement.innerHTML = `* { color: ${styles.color}; background: ${styles.background}; font-family: ${styles.fontFamily}; font-size: ${styles.fontSize}; } img { max-width: 100%; max-height: 100%; } a:focus, input:focus, select:focus, textarea:focus { outline: 1px solid -webkit-focus-ring-color; outline-offset: -1px; } ::-webkit-scrollbar { width: 14px; height: 14px; } ${isLightTheme(themeId) ? defaultLightScrollbarStyle : defaultDarkScrollbarStyle}`; return styleElement; } }
src/vs/workbench/parts/html/browser/htmlPreviewPart.ts
1
https://github.com/microsoft/vscode/commit/8435ddcf464fd995936ff6f877ff4744dc3ca2b6
[ 0.001641076640225947, 0.0002752777363639325, 0.0001660300767980516, 0.00017352111171931028, 0.00033135953708551824 ]
{ "id": 4, "code_window": [ "}\n", "\n", ".monaco-shell .monaco-tree.focused:focus {\n", "\toutline: 0; /* tree indicates focus not via outline but through the focussed item */\n", "}\n", "\n", ".monaco-shell [tabindex=\"0\"]:active,\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\toutline: 0 !important; /* tree indicates focus not via outline but through the focussed item */\n" ], "file_path": "src/vs/workbench/electron-browser/media/shell.css", "type": "replace", "edit_start_line_idx": 134 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import {TPromise} from 'vs/base/common/winjs.base'; import remote = require('vs/base/common/remote'); import descriptors = require('vs/platform/instantiation/common/descriptors'); import abstractThreadService = require('./abstractThreadService'); import {readThreadSynchronizableObjects} from 'vs/platform/thread/common/threadService'; import {IThreadService, IThreadSynchronizableObject, ThreadAffinity, IThreadServiceStatusListener} from 'vs/platform/thread/common/thread'; export class PluginHostThreadService extends abstractThreadService.AbstractThreadService implements IThreadService { public serviceId = IThreadService; protected _remoteCom: remote.IRemoteCom; constructor(remoteCom: remote.IRemoteCom) { super(false); this._remoteCom = remoteCom; this._remoteCom.registerBigHandler(this); // Register all statically instantiated synchronizable objects readThreadSynchronizableObjects().forEach((obj) => this.registerInstance(obj)); } MainThread(obj:IThreadSynchronizableObject<any>, methodName:string, target:Function, params:any[]): TPromise<any> { return target.apply(obj, params); } OneWorker(obj:IThreadSynchronizableObject<any>, methodName:string, target:Function, params:any[], affinity:ThreadAffinity): TPromise<any> { return TPromise.as(null); } AllWorkers(obj:IThreadSynchronizableObject<any>, methodName:string, target:Function, params:any[]): TPromise<any> { return TPromise.as(null); } Everywhere(obj:IThreadSynchronizableObject<any>, methodName:string, target:Function, params:any[]): TPromise<any> { return target.apply(obj, params); } ensureWorkers(): void { // Nothing to do } addStatusListener(listener:IThreadServiceStatusListener): void { // Nothing to do } removeStatusListener(listener:IThreadServiceStatusListener): void { // Nothing to do } protected _registerAndInstantiateMainProcessActor<T>(id: string, descriptor: descriptors.SyncDescriptor0<T>): T { return this._getOrCreateProxyInstance(this._remoteCom, id, descriptor); } protected _registerMainProcessActor<T>(id: string, actor:T): void { throw new Error('Not supported in this runtime context!'); } protected _registerAndInstantiatePluginHostActor<T>(id: string, descriptor: descriptors.SyncDescriptor0<T>): T { return this._getOrCreateLocalInstance(id, descriptor); } protected _registerPluginHostActor<T>(id: string, actor:T): void { this._registerLocalInstance(id, actor); } protected _registerAndInstantiateWorkerActor<T>(id: string, descriptor: descriptors.SyncDescriptor0<T>, whichWorker:ThreadAffinity): T { throw new Error('Not supported in this runtime context! Cannot communicate directly from Plugin Host to Worker!'); } protected _registerWorkerActor<T>(id: string, actor:T): void { throw new Error('Not supported in this runtime context!'); } }
src/vs/platform/thread/common/pluginHostThreadService.ts
0
https://github.com/microsoft/vscode/commit/8435ddcf464fd995936ff6f877ff4744dc3ca2b6
[ 0.0001770446979207918, 0.00017288929666392505, 0.00016826690989546478, 0.00017236813437193632, 0.0000027409050744608976 ]
{ "id": 4, "code_window": [ "}\n", "\n", ".monaco-shell .monaco-tree.focused:focus {\n", "\toutline: 0; /* tree indicates focus not via outline but through the focussed item */\n", "}\n", "\n", ".monaco-shell [tabindex=\"0\"]:active,\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\toutline: 0 !important; /* tree indicates focus not via outline but through the focussed item */\n" ], "file_path": "src/vs/workbench/electron-browser/media/shell.css", "type": "replace", "edit_start_line_idx": 134 }
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>name</key> <string>Red</string> <key>settings</key> <array> <dict> <key>settings</key> <dict> <key>background</key> <string>#390000</string> <key>caret</key> <string>#970000</string> <key>foreground</key> <string>#F8F8F8</string> <key>invisibles</key> <string>#c10000</string> <key>lineHighlight</key> <string>#0000004A</string> <key>selection</key> <string>#750000</string> </dict> </dict> <dict> <key>name</key> <string>Comment</string> <key>scope</key> <string>comment</string> <key>settings</key> <dict> <key>fontStyle</key> <string>italic</string> <key>foreground</key> <string>#e7c0c0ff</string> </dict> </dict> <dict> <key>name</key> <string>Constant</string> <key>scope</key> <string>constant</string> <key>settings</key> <dict> <key>fontStyle</key> <string></string> <key>foreground</key> <string>#994646ff</string> </dict> </dict> <dict> <key>name</key> <string>Keyword</string> <key>scope</key> <string>keyword</string> <key>settings</key> <dict> <key>fontStyle</key> <string></string> <key>foreground</key> <string>#f12727ff</string> </dict> </dict> <dict> <key>name</key> <string>Entity</string> <key>scope</key> <string>entity</string> <key>settings</key> <dict> <key>fontStyle</key> <string></string> <key>foreground</key> <string>#fec758ff</string> </dict> </dict> <dict> <key>name</key> <string>Storage</string> <key>scope</key> <string>storage</string> <key>settings</key> <dict> <key>fontStyle</key> <string>bold</string> <key>foreground</key> <string>#ff6262ff</string> </dict> </dict> <dict> <key>name</key> <string>String</string> <key>scope</key> <string>string</string> <key>settings</key> <dict> <key>fontStyle</key> <string></string> <key>foreground</key> <string>#cd8d8dff</string> </dict> </dict> <dict> <key>name</key> <string>Support</string> <key>scope</key> <string>support</string> <key>settings</key> <dict> <key>fontStyle</key> <string></string> <key>foreground</key> <string>#9df39fff</string> </dict> </dict> <dict> <key>name</key> <string>Variable</string> <key>scope</key> <string>variable</string> <key>settings</key> <dict> <key>fontStyle</key> <string>italic</string> <key>foreground</key> <string>#fb9a4bff</string> </dict> </dict> <dict> <key>name</key> <string>Invalid</string> <key>scope</key> <string>invalid</string> <key>settings</key> <dict> <key>background</key> <string>#fd6209ff</string> <key>foreground</key> <string>#ffffffff</string> </dict> </dict> <dict> <key>name</key> <string>Embedded Source</string> <key>scope</key> <string>text source</string> <key>settings</key> <dict> <key>background</key> <string>#b0b3ba14</string> </dict> </dict> <dict> <key>name</key> <string>Embedded Source (Bright)</string> <key>scope</key> <string>text.html.ruby source</string> <key>settings</key> <dict> <key>background</key> <string>#b1b3ba21</string> </dict> </dict> <dict> <key>name</key> <string>Entity inherited-class</string> <key>scope</key> <string>entity.other.inherited-class</string> <key>settings</key> <dict> <key>fontStyle</key> <string>underline</string> <key>foreground</key> <string>#aa5507ff</string> </dict> </dict> <dict> <key>name</key> <string>String embedded-source</string> <key>scope</key> <string>string.quoted source</string> <key>settings</key> <dict> <key>fontStyle</key> <string></string> <key>foreground</key> <string>#9df39fff</string> </dict> </dict> <dict> <key>name</key> <string>String constant</string> <key>scope</key> <string>string constant</string> <key>settings</key> <dict> <key>fontStyle</key> <string></string> <key>foreground</key> <string>#ffe862ff</string> </dict> </dict> <dict> <key>name</key> <string>String.regexp</string> <key>scope</key> <string>string.regexp</string> <key>settings</key> <dict> <key>foreground</key> <string>#ffb454ff</string> </dict> </dict> <dict> <key>name</key> <string>String variable</string> <key>scope</key> <string>string variable</string> <key>settings</key> <dict> <key>foreground</key> <string>#edef7dff</string> </dict> </dict> <dict> <key>name</key> <string>Support.function</string> <key>scope</key> <string>support.function</string> <key>settings</key> <dict> <key>fontStyle</key> <string></string> <key>foreground</key> <string>#ffb454ff</string> </dict> </dict> <dict> <key>name</key> <string>Support.constant</string> <key>scope</key> <string>support.constant</string> <key>settings</key> <dict> <key>fontStyle</key> <string></string> <key>foreground</key> <string>#eb939aff</string> </dict> </dict> <dict> <key>name</key> <string>Doctype&#x2f;XML Processing</string> <key>scope</key> <string>declaration.sgml.html declaration.doctype, declaration.sgml.html declaration.doctype entity, declaration.sgml.html declaration.doctype string, declaration.xml-processing, declaration.xml-processing entity, declaration.xml-processing string</string> <key>settings</key> <dict> <key>fontStyle</key> <string></string> <key>foreground</key> <string>#73817dff</string> </dict> </dict> <dict> <key>name</key> <string>Meta.tag.A</string> <key>scope</key> <string>declaration.tag, declaration.tag entity, meta.tag, meta.tag entity</string> <key>settings</key> <dict> <key>fontStyle</key> <string></string> <key>foreground</key> <string>#ec0d1eff</string> </dict> </dict> <dict> <key>name</key> <string>css tag-name</string> <key>scope</key> <string>meta.selector.css entity.name.tag</string> <key>settings</key> <dict> <key>fontStyle</key> <string></string> <key>foreground</key> <string>#aa5507ff</string> </dict> </dict> <dict> <key>name</key> <string>css#id</string> <key>scope</key> <string>meta.selector.css entity.other.attribute-name.id</string> <key>settings</key> <dict> <key>foreground</key> <string>#fec758ff</string> </dict> </dict> <dict> <key>name</key> <string>css.class</string> <key>scope</key> <string>meta.selector.css entity.other.attribute-name.class</string> <key>settings</key> <dict> <key>fontStyle</key> <string></string> <key>foreground</key> <string>#41a83eff</string> </dict> </dict> <dict> <key>name</key> <string>css property-name:</string> <key>scope</key> <string>support.type.property-name.css</string> <key>settings</key> <dict> <key>fontStyle</key> <string></string> <key>foreground</key> <string>#96dd3bff</string> </dict> </dict> <dict> <key>name</key> <string>css property-value;</string> <key>scope</key> <string>meta.property-group support.constant.property-value.css, meta.property-value support.constant.property-value.css</string> <key>settings</key> <dict> <key>fontStyle</key> <string>italic</string> <key>foreground</key> <string>#ffe862ff</string> </dict> </dict> <dict> <key>name</key> <string>css additional-constants</string> <key>scope</key> <string>meta.property-value support.constant.named-color.css, meta.property-value constant</string> <key>settings</key> <dict> <key>fontStyle</key> <string></string> <key>foreground</key> <string>#ffe862ff</string> </dict> </dict> <dict> <key>name</key> <string>css @at-rule</string> <key>scope</key> <string>meta.preprocessor.at-rule keyword.control.at-rule</string> <key>settings</key> <dict> <key>foreground</key> <string>#fd6209ff</string> </dict> </dict> <dict> <key>name</key> <string>css constructor.argument</string> <key>scope</key> <string>meta.constructor.argument.css</string> <key>settings</key> <dict> <key>fontStyle</key> <string></string> <key>foreground</key> <string>#ec9799ff</string> </dict> </dict> <dict> <key>name</key> <string>diff.header</string> <key>scope</key> <string>meta.diff, meta.diff.header</string> <key>settings</key> <dict> <key>background</key> <string>#0b2f20ff</string> <key>fontStyle</key> <string>italic</string> <key>foreground</key> <string>#f8f8f8ff</string> </dict> </dict> <dict> <key>name</key> <string>diff.deleted</string> <key>scope</key> <string>markup.deleted</string> <key>settings</key> <dict> <key>background</key> <string>#fedcddff</string> <key>foreground</key> <string>#ec9799ff</string> </dict> </dict> <dict> <key>name</key> <string>diff.changed</string> <key>scope</key> <string>markup.changed</string> <key>settings</key> <dict> <key>background</key> <string>#c4b14aff</string> <key>foreground</key> <string>#f8f8f8ff</string> </dict> </dict> <dict> <key>name</key> <string>diff.inserted</string> <key>scope</key> <string>markup.inserted</string> <key>settings</key> <dict> <key>background</key> <string>#9bf199ff</string> <key>foreground</key> <string>#41a83eff</string> </dict> </dict> </array> <key>uuid</key> <string>AC0A28C5-65E6-42A6-AD05-4D01735652EE</string> <key>colorSpaceName</key> <string>sRGB</string> <key>semanticClass</key> <string>theme.dark.django</string> </dict> </plist>
extensions/theme-red/themes/red.tmTheme
0
https://github.com/microsoft/vscode/commit/8435ddcf464fd995936ff6f877ff4744dc3ca2b6
[ 0.00017600164574105293, 0.00017299168393947184, 0.00016840704483911395, 0.00017356466560158879, 0.0000018633350009622518 ]
{ "id": 4, "code_window": [ "}\n", "\n", ".monaco-shell .monaco-tree.focused:focus {\n", "\toutline: 0; /* tree indicates focus not via outline but through the focussed item */\n", "}\n", "\n", ".monaco-shell [tabindex=\"0\"]:active,\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\toutline: 0 !important; /* tree indicates focus not via outline but through the focussed item */\n" ], "file_path": "src/vs/workbench/electron-browser/media/shell.css", "type": "replace", "edit_start_line_idx": 134 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import objects = require('vs/base/common/objects'); interface Options { suggest: { alwaysAllWords: boolean; useCodeSnippetsOnMethodSuggest: boolean; }; validate: { enable: boolean; semanticValidation: boolean; syntaxValidation: boolean; _surpressSuperWithoutSuperTypeError: boolean; lint: { comparisonOperatorsNotStrict: string; curlyBracketsMustNotBeOmitted: string; emptyBlocksWithoutComment: string; forcedTypeConversion: string; functionsInsideLoops: string; functionsWithoutReturnType: string; missingSemicolon: string; mixedTypesArithmetics: string; newOnLowercaseFunctions: string; newOnReturningFunctions: string; parametersDontMatchSignature: string; parametersOptionalButNotLast: string; primitivesInInstanceOf: string; redeclaredVariables: string; semicolonsInsteadOfBlocks: string; tripleSlashReferenceAlike: string; undeclaredVariables: string; unknownModule: string; unknownProperty: string; unknownTypeOfResults: string; unusedFunctions: string; unusedImports: string; unusedMembers: string; unusedVariables: string; }; }; } namespace Options { export var typeScriptOptions: Options = Object.freeze({ suggest: { alwaysAllWords: false, useCodeSnippetsOnMethodSuggest: false }, validate: { enable: true, semanticValidation: true, syntaxValidation: true, _surpressSuperWithoutSuperTypeError: false, lint: { comparisonOperatorsNotStrict: 'ignore', curlyBracketsMustNotBeOmitted: 'ignore', emptyBlocksWithoutComment: 'ignore', functionsInsideLoops: 'ignore', functionsWithoutReturnType: 'ignore', missingSemicolon: 'ignore', newOnLowercaseFunctions: 'ignore', semicolonsInsteadOfBlocks: 'ignore', tripleSlashReferenceAlike: 'ignore', unknownTypeOfResults: 'ignore', unusedFunctions: 'ignore', unusedImports: 'ignore', unusedMembers: 'ignore', unusedVariables: 'ignore', // the below lint checks are done by // the TypeScript compiler and we can // change the severity with this. Tho // the default remains error forcedTypeConversion: 'error', mixedTypesArithmetics: 'error', newOnReturningFunctions: 'error', parametersDontMatchSignature: 'error', parametersOptionalButNotLast: 'error', primitivesInInstanceOf: 'error', redeclaredVariables: 'error', undeclaredVariables: 'error', unknownModule: 'error', unknownProperty: 'error', } } }); export var javaScriptOptions: Options = Object.freeze({ suggest: { alwaysAllWords: false, useCodeSnippetsOnMethodSuggest: false }, validate: { enable: true, semanticValidation: true, syntaxValidation: true, _surpressSuperWithoutSuperTypeError: false, lint: { comparisonOperatorsNotStrict: 'ignore', curlyBracketsMustNotBeOmitted: 'ignore', emptyBlocksWithoutComment: 'ignore', forcedTypeConversion: 'warning', functionsInsideLoops: 'ignore', functionsWithoutReturnType: 'ignore', missingSemicolon: 'ignore', mixedTypesArithmetics: 'warning', newOnLowercaseFunctions: 'warning', newOnReturningFunctions: 'warning', parametersDontMatchSignature: 'ignore', parametersOptionalButNotLast: 'ignore', primitivesInInstanceOf: 'error', redeclaredVariables: 'warning', semicolonsInsteadOfBlocks: 'ignore', tripleSlashReferenceAlike: 'warning', undeclaredVariables: 'warning', unknownModule: 'ignore', unknownProperty: 'ignore', unknownTypeOfResults: 'warning', unusedFunctions: 'ignore', unusedImports: 'ignore', unusedMembers: 'ignore', unusedVariables: 'warning', } } }); export function withDefaultOptions(something: any, defaults: Options): Options { return objects.mixin(objects.clone(defaults), something); } } export = Options;
src/vs/languages/typescript/common/options.ts
0
https://github.com/microsoft/vscode/commit/8435ddcf464fd995936ff6f877ff4744dc3ca2b6
[ 0.00017899656086228788, 0.00017255207058042288, 0.00016615328786429018, 0.00017312428099103272, 0.0000033956855531869223 ]
{ "id": 5, "code_window": [ ".monaco-shell .monaco-tree.focused.no-item-focus:active:before {\n", "\toutline: 0 !important; /* fixes some flashing outlines from showing up when clicking */\n", "}\n", "\n", ".monaco-shell .activitybar [tabindex=\"0\"]:focus {\n", "\toutline: 0; /* activity bar indicates focus custom */\n", "}\n", "\n", "/* END Keyboard Focus Indication Styles */\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\toutline: 0 !important; /* activity bar indicates focus custom */\n", "}\n", "\n", ".monaco-shell .part.editor .iframe-container,\n", ".monaco-shell .part.editor .binary-container {\n", "\toutline: 0 !important; /* TODO@Ben we need focus indication for those too */\n" ], "file_path": "src/vs/workbench/electron-browser/media/shell.css", "type": "replace", "edit_start_line_idx": 147 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ .monaco-shell { height: 100%; width: 100%; color: #6C6C6C; margin: 0; padding: 0; overflow: hidden; font-family: "Segoe WPC", "Segoe UI", "SFUIText-Light", "HelveticaNeue-Light", sans-serif, "Droid Sans Fallback"; font-size: 11px; -webkit-user-select: none; -ms-user-select: none; -khtml-user-select: none; -moz-user-select: -moz-none; -o-user-select: none; user-select: none; } @-webkit-keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } } @-moz-keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } } @-ms-keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } } @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } } .monaco-shell img { border: 0; } .monaco-shell label { cursor: pointer; } .monaco-shell a { text-decoration: none; } .monaco-shell a.plain { color: inherit; text-decoration: none; } .monaco-shell a.plain:hover, .monaco-shell a.plain.hover { color: inherit; text-decoration: none; } /* START Keyboard Focus Indication Styles */ .monaco-shell.vs [tabindex="0"]:focus, .monaco-shell.vs .synthetic-focus, .monaco-shell.vs select:focus, .monaco-shell.vs input[type="button"]:focus, .monaco-shell.vs input[type="submit"]:focus, .monaco-shell.vs input[type="text"]:focus, .monaco-shell.vs textarea:focus, .monaco-shell.vs input[type="checkbox"]:focus { outline: 1px solid rgba(0, 122, 204, 0.4); outline-offset: -1px; opacity: 1 !important; } .monaco-shell.vs-dark [tabindex="0"]:focus, .monaco-shell.vs-dark .synthetic-focus, .monaco-shell.vs-dark select:focus, .monaco-shell.vs-dark input[type="button"]:focus, .monaco-shell.vs-dark input[type="submit"]:focus, .monaco-shell.vs-dark input[type="text"]:focus, .monaco-shell.vs-dark textarea:focus, .monaco-shell.vs-dark input[type="checkbox"]:focus { outline: 1px solid rgba(14, 99, 156, 0.6); outline-offset: -1px; opacity: 1 !important; } .monaco-shell.hc-black [tabindex="0"]:focus, .monaco-shell.hc-black .synthetic-focus, .monaco-shell.hc-black select:focus, .monaco-shell.hc-black input[type="button"]:focus, .monaco-shell.hc-black input[type="submit"]:focus, .monaco-shell.hc-black input[type="text"]:focus, .monaco-shell.hc-black textarea:focus, .monaco-shell.hc-black input[type="checkbox"]:focus { outline: 2px solid #DF740C; outline-offset: -2px; } .monaco-shell.vs .monaco-tree.focused .monaco-tree-row.focused [tabindex="0"]:focus { outline: 1px solid #007ACC; /* higher contrast color for focusable elements in a row that shows focus feedback */ } .monaco-shell.vs-dark .monaco-tree.focused .monaco-tree-row.focused [tabindex="0"]:focus { outline: 1px solid #007ACC; /* higher contrast color for focusable elements in a row that shows focus feedback */ } .monaco-shell .monaco-tree.focused.no-item-focus:focus:before { position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: 5; /* make sure we are on top of the tree items */ content: ""; pointer-events: none; /* enable click through */ } .monaco-shell.vs .monaco-tree.focused.no-item-focus:focus:before { outline: 1px solid rgba(0, 122, 204, 0.4); /* we still need to handle the empty tree or no focus item case */ outline-offset: -1px; } .monaco-shell.vs-dark .monaco-tree.focused.no-item-focus:focus:before { outline: 1px solid rgba(14, 99, 156, 0.6); /* we still need to handle the empty tree or no focus item case */ outline-offset: -1px; } .monaco-shell.hc-black .monaco-tree.focused.no-item-focus:focus:before { outline: 2px solid #DF740C; /* we still need to handle the empty tree or no focus item case */ outline-offset: -2px; } .monaco-shell .synthetic-focus :focus { outline: 0 !important; /* elements within widgets that draw synthetic-focus should never show focus */ } .monaco-shell .monaco-inputbox.info.synthetic-focus, .monaco-shell .monaco-inputbox.warning.synthetic-focus, .monaco-shell .monaco-inputbox.error.synthetic-focus, .monaco-shell .monaco-inputbox.info input[type="text"]:focus, .monaco-shell .monaco-inputbox.warning input[type="text"]:focus, .monaco-shell .monaco-inputbox.error input[type="text"]:focus { outline: 0 !important; /* outline is not going well with decoration */ } .monaco-shell .monaco-tree.focused:focus { outline: 0; /* tree indicates focus not via outline but through the focussed item */ } .monaco-shell [tabindex="0"]:active, .monaco-shell select:active, .monaco-shell input[type="button"]:active, .monaco-shell input[type="submit"]:active, .monaco-shell input[type="checkbox"]:active, .monaco-shell .monaco-tree.focused.no-item-focus:active:before { outline: 0 !important; /* fixes some flashing outlines from showing up when clicking */ } .monaco-shell .activitybar [tabindex="0"]:focus { outline: 0; /* activity bar indicates focus custom */ } /* END Keyboard Focus Indication Styles */ .monaco-shell a.prominent { text-decoration: underline; } .monaco-shell a.strong { font-weight: bold; } a:active { color: inherit; background-color: inherit; } .monaco-shell input { font-family: "Segoe UI", "SFUIText-Light", "HelveticaNeue-Light", sans-serif, "Droid Sans Fallback"; color: inherit; } .monaco-shell select { font-family: "Segoe UI","SFUIText-Light", "HelveticaNeue-Light", sans-serif, "Droid Sans Fallback"; } .monaco-shell .pointer { cursor: pointer; } .monaco-shell .context-view .tooltip { background-color: white; border: 1px solid #ccc; } .monaco-shell .context-view.bottom.right .tooltip:before { border-width: 6px; border-bottom: 6px solid #ccc; } .monaco-shell .context-view.bottom.right .tooltip:after { border-width: 5px; border-bottom: 5px solid white; } .monaco-shell .context-view .monaco-menu .actions-container { min-width: 160px; } .monaco-shell .monaco-menu .action-label.check { font-weight: bold; } .monaco-shell .monaco-menu .action-label.uncheck { font-weight: normal; } /* Notifications */ .monaco-shell .monaco-notification-container { position: absolute; width: 100%; height: 400px; top: calc(50% - 200px); top: -moz-calc(50% - 200px); top: -webkit-calc(50% - 200px); top: -ms-calc(50% - 200px); top: -o-calc(50% - 200px); background-color: #0E6198; color: white; border-top: 2px solid transparent; border-bottom: 2px solid transparent; } .monaco-shell .monaco-notification-container a { color: inherit; opacity: 0.6; text-decoration: underline; } .monaco-shell .monaco-notification-container .buttons { margin-top: 2em; } .monaco-shell .monaco-notification-container button { color: inherit; text-decoration: none; display: inline-block; padding: 6px 16px; margin-right: 12px; font-family: 'Segoe UI Semibold', "Segoe UI", "SFUIText-Light", "HelveticaNeue-Light", sans-serif, "Droid Sans Fallback"; font-weight: 400; font-size: 12px; min-width: 65px; border: 2px solid #fff; background-color: transparent; -moz-box-sizing: border-box; box-sizing: border-box; cursor: pointer; } .monaco-shell .monaco-notification-container button.default { background-color: rgba(255, 255, 255, 0.2); } .monaco-shell .monaco-notification-container button:disabled { opacity: 0.4; } .monaco-shell .monaco-notification-container button:not(:disabled):hover { color: inherit; background-color: rgba(255, 255, 255, 0.1); } .monaco-shell .monaco-notification-container button.default:not(:disabled)hover { background-color: rgba(255, 255, 255, 0.3); } .monaco-shell .monaco-notification-container > .notification { max-width: 800px; height: 100%; margin: 0 auto; padding: 0 16px; overflow-y: auto; overflow-x: hidden; font-family: "Segoe WPC", "Segoe UI", "SFUIText-Light", "HelveticaNeue-Light", sans-serif, "Droid Sans Fallback"; font-size: 14px; } .monaco-shell .monaco-notification-container > .notification > .notification-title { font-family: "Segoe UI Light", "Segoe UI", "SFUIText-Light", "HelveticaNeue-Light", "Helvetica Neue", sans-serif, "Droid Sans Fallback"; font-weight: 300; font-size: 2.5em; } .monaco-shell input:disabled { background-color: #E1E1E1; } /** * Dark Theme */ .monaco-shell.vs-dark { color: #BBB; background-color: #1E1E1E; } .monaco-shell.vs-dark .monaco-action-bar.vertical .action-label.separator { border-bottom-color: #666; } .monaco-shell.vs-dark .context-view .tooltip { background-color: #1E1E1E; border-color: #707070; } .monaco-shell.vs-dark .context-view.bottom.right .tooltip:before { border-bottom: 6px solid #707070; } .monaco-shell.vs-dark .context-view.bottom.right .tooltip:after { border-bottom: 5px solid #1E1E1E; } .monaco-shell.vs-dark input:disabled { background-color: #333; } /** * High Contrast Theme */ .monaco-shell.hc-black { color: #fff; background-color: #000; } .monaco-shell.hc-black .monaco-modal-view.visible .monaco-modal-view-background { opacity: 0.6; } .monaco-shell.hc-black .monaco-notification-container { background-color: #0C141F; color: white; border-top: 2px solid #6FC3DF; border-bottom: 2px solid #6FC3DF; } .monaco-shell.hc-black .monaco-notification-container input { background-color: #000; } .monaco-shell.hc-black .context-view .tooltip { background-color: black; } .monaco-shell.hc-black .context-view .tooltip:before { border-width: 0 !important; } .monaco-shell.hc-black .context-view .tooltip:after { border-width: 0 !important; }
src/vs/workbench/electron-browser/media/shell.css
1
https://github.com/microsoft/vscode/commit/8435ddcf464fd995936ff6f877ff4744dc3ca2b6
[ 0.9919024109840393, 0.03720471262931824, 0.00016589966253377497, 0.000618548656348139, 0.16470900177955627 ]
{ "id": 5, "code_window": [ ".monaco-shell .monaco-tree.focused.no-item-focus:active:before {\n", "\toutline: 0 !important; /* fixes some flashing outlines from showing up when clicking */\n", "}\n", "\n", ".monaco-shell .activitybar [tabindex=\"0\"]:focus {\n", "\toutline: 0; /* activity bar indicates focus custom */\n", "}\n", "\n", "/* END Keyboard Focus Indication Styles */\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\toutline: 0 !important; /* activity bar indicates focus custom */\n", "}\n", "\n", ".monaco-shell .part.editor .iframe-container,\n", ".monaco-shell .part.editor .binary-container {\n", "\toutline: 0 !important; /* TODO@Ben we need focus indication for those too */\n" ], "file_path": "src/vs/workbench/electron-browser/media/shell.css", "type": "replace", "edit_start_line_idx": 147 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import {Promise, TPromise} from 'vs/base/common/winjs.base'; import nls = require('vs/nls'); import lifecycle = require('vs/base/common/lifecycle'); import objects = require('vs/base/common/objects'); import DOM = require('vs/base/browser/dom'); import URI from 'vs/base/common/uri'; import {MIME_BINARY} from 'vs/base/common/mime'; import async = require('vs/base/common/async'); import paths = require('vs/base/common/paths'); import errors = require('vs/base/common/errors'); import {isString} from 'vs/base/common/types'; import Actions = require('vs/base/common/actions'); import comparers = require('vs/base/common/comparers'); import {InputBox} from 'vs/base/browser/ui/inputbox/inputBox'; import {$} from 'vs/base/browser/builder'; import platform = require('vs/base/common/platform'); import glob = require('vs/base/common/glob'); import {ContributableActionProvider} from 'vs/workbench/browser/actionBarRegistry'; import {LocalFileChangeEvent, ConfirmResult, IFilesConfiguration, ITextFileService} from 'vs/workbench/parts/files/common/files'; import {IFileOperationResult, FileOperationResult, IFileStat, IFileService} from 'vs/platform/files/common/files'; import {FileEditorInput} from 'vs/workbench/parts/files/browser/editors/fileEditorInput'; import {DuplicateFileAction, ImportFileAction, PasteFileAction, keybindingForAction, IEditableData, IFileViewletState} from 'vs/workbench/parts/files/browser/fileActions'; import {EditorOptions} from 'vs/workbench/common/editor'; import {IDataSource, ITree, IElementCallback, IAccessibilityProvider, IRenderer, ContextMenuEvent, ISorter, IFilter, IDragAndDrop, IDragAndDropData, IDragOverReaction, DRAG_OVER_ACCEPT_BUBBLE_DOWN, DRAG_OVER_ACCEPT_BUBBLE_DOWN_COPY, DRAG_OVER_ACCEPT_BUBBLE_UP, DRAG_OVER_ACCEPT_BUBBLE_UP_COPY, DRAG_OVER_REJECT} from 'vs/base/parts/tree/browser/tree'; import labels = require('vs/base/common/labels'); import {DesktopDragAndDropData, ExternalElementsDragAndDropData} from 'vs/base/parts/tree/browser/treeDnd'; import {ClickBehavior, DefaultController} from 'vs/base/parts/tree/browser/treeDefaults'; import {ActionsRenderer} from 'vs/base/parts/tree/browser/actionsRenderer'; import {FileStat, NewStatPlaceholder} from 'vs/workbench/parts/files/common/explorerViewModel'; import {DragMouseEvent, StandardMouseEvent} from 'vs/base/browser/mouseEvent'; import {StandardKeyboardEvent} from 'vs/base/browser/keyboardEvent'; import {IWorkbenchEditorService} from 'vs/workbench/services/editor/common/editorService'; import {IPartService} from 'vs/workbench/services/part/common/partService'; import {IWorkspaceContextService} from 'vs/workbench/services/workspace/common/contextService'; import {IWorkspace} from 'vs/platform/workspace/common/workspace'; import {IContextViewService, IContextMenuService} from 'vs/platform/contextview/browser/contextView'; import {IEventService} from 'vs/platform/event/common/event'; import {IInstantiationService} from 'vs/platform/instantiation/common/instantiation'; import {IMessageService, IConfirmation, Severity} from 'vs/platform/message/common/message'; import {IProgressService} from 'vs/platform/progress/common/progress'; import {ITelemetryService} from 'vs/platform/telemetry/common/telemetry'; import {Keybinding, CommonKeybindings} from 'vs/base/common/keyCodes'; export class FileDataSource implements IDataSource { private workspace: IWorkspace; constructor( @IProgressService private progressService: IProgressService, @IMessageService private messageService: IMessageService, @IFileService private fileService: IFileService, @IPartService private partService: IPartService, @IWorkspaceContextService contextService: IWorkspaceContextService ) { this.workspace = contextService.getWorkspace(); } public getId(tree: ITree, stat: FileStat): string { return stat.getId(); } public hasChildren(tree: ITree, stat: FileStat): boolean { return stat.isDirectory; } public getChildren(tree: ITree, stat: FileStat): TPromise<FileStat[]> { // Return early if stat is already resolved if (stat.isDirectoryResolved) { return TPromise.as(stat.children); } // Resolve children and add to fileStat for future lookup else { // Resolve let promise = this.fileService.resolveFile(stat.resource, { resolveSingleChildDescendants: true }).then((dirStat: IFileStat) => { // Convert to view model let modelDirStat = FileStat.create(dirStat); // Add children to folder for (let i = 0; i < modelDirStat.children.length; i++) { stat.addChild(modelDirStat.children[i]); } stat.isDirectoryResolved = true; return stat.children; }, (e: any) => { this.messageService.show(Severity.Error, e); return []; // we could not resolve any children because of an error }); this.progressService.showWhile(promise, this.partService.isCreated() ? 800 : 3200 /* less ugly initial startup */); return promise; } } public getParent(tree: ITree, stat: FileStat): TPromise<FileStat> { if (!stat) { return TPromise.as(null); // can be null if nothing selected in the tree } // Return if root reached if (this.workspace && stat.resource.toString() === this.workspace.resource.toString()) { return TPromise.as(null); } // Return if parent already resolved if (stat.parent) { return TPromise.as(stat.parent); } // We never actually resolve the parent from the disk for performance reasons. It wouldnt make // any sense to resolve parent by parent with requests to walk up the chain. Instead, the explorer // makes sure to properly resolve a deep path to a specific file and merges the result with the model. return TPromise.as(null); } } export class FileActionProvider extends ContributableActionProvider { private state: FileViewletState; constructor(state: any) { super(); this.state = state; } public hasActions(tree: ITree, stat: FileStat): boolean { if (stat instanceof NewStatPlaceholder) { return false; } return super.hasActions(tree, stat); } public getActions(tree: ITree, stat: FileStat): TPromise<Actions.IAction[]> { if (stat instanceof NewStatPlaceholder) { return TPromise.as([]); } return super.getActions(tree, stat); } public hasSecondaryActions(tree: ITree, stat: FileStat): boolean { if (stat instanceof NewStatPlaceholder) { return false; } return super.hasSecondaryActions(tree, stat); } public getSecondaryActions(tree: ITree, stat: FileStat): TPromise<Actions.IAction[]> { if (stat instanceof NewStatPlaceholder) { return TPromise.as([]); } return super.getSecondaryActions(tree, stat); } public runAction(tree: ITree, stat: FileStat, action: Actions.IAction, context?: any): Promise; public runAction(tree: ITree, stat: FileStat, actionID: string, context?: any): Promise; public runAction(tree: ITree, stat: FileStat, arg: any, context: any = {}): Promise { context = objects.mixin({ viewletState: this.state, stat: stat }, context); if (!isString(arg)) { let action = <Actions.IAction>arg; if (action.enabled) { return action.run(context); } return null; } let id = <string>arg; let promise = this.hasActions(tree, stat) ? this.getActions(tree, stat) : TPromise.as([]); return promise.then((actions: Actions.IAction[]) => { for (let i = 0, len = actions.length; i < len; i++) { if (actions[i].id === id && actions[i].enabled) { return actions[i].run(context); } } promise = this.hasSecondaryActions(tree, stat) ? this.getSecondaryActions(tree, stat) : TPromise.as([]); return promise.then((actions: Actions.IAction[]) => { for (let i = 0, len = actions.length; i < len; i++) { if (actions[i].id === id && actions[i].enabled) { return actions[i].run(context); } } return null; }); }); } } export class FileViewletState implements IFileViewletState { private _actionProvider: FileActionProvider; private editableStats: { [resource: string]: IEditableData; }; constructor() { this._actionProvider = new FileActionProvider(this); this.editableStats = Object.create(null); } public get actionProvider(): FileActionProvider { return this._actionProvider; } public getEditableData(stat: FileStat): IEditableData { return this.editableStats[stat.resource && stat.resource.toString()]; } public setEditable(stat: FileStat, editableData: IEditableData): void { if (editableData) { this.editableStats[stat.resource && stat.resource.toString()] = editableData; } } public clearEditable(stat: FileStat): void { delete this.editableStats[stat.resource && stat.resource.toString()]; } } export class ActionRunner extends Actions.ActionRunner implements Actions.IActionRunner { private viewletState: FileViewletState; constructor(state: FileViewletState) { super(); this.viewletState = state; } public run(action: Actions.IAction, context?: any): Promise { return super.run(action, { viewletState: this.viewletState }); } } // Explorer Renderer export class FileRenderer extends ActionsRenderer implements IRenderer { private state: FileViewletState; constructor( state: FileViewletState, actionRunner: Actions.IActionRunner, @IContextViewService private contextViewService: IContextViewService ) { super({ actionProvider: state.actionProvider, actionRunner: actionRunner }); this.state = state; } public getContentHeight(tree: ITree, element: any): number { return 22; } public renderContents(tree: ITree, stat: FileStat, domElement: HTMLElement, previousCleanupFn: IElementCallback): IElementCallback { let el = $(domElement).clearChildren(); let item = $('.explorer-item').addClass(this.iconClass(stat)).appendTo(el); // File/Folder label let editableData: IEditableData = this.state.getEditableData(stat); if (!editableData) { let label = $('.explorer-item-label').appendTo(item); $('a.plain').text(stat.name).appendTo(label); return null; } // Input field (when creating a new file or folder or renaming) let inputBox = new InputBox(item.getHTMLElement(), this.contextViewService, { validationOptions: { validation: editableData.validator, showMessage: true }, ariaLabel: nls.localize('fileInputAriaLabel', "Type file name. Press Enter to confirm or Escape to cancel.") }); let value = stat.name || ''; let lastDot = value.lastIndexOf('.'); inputBox.value = value; inputBox.select({ start: 0, end: lastDot > 0 && !stat.isDirectory ? lastDot : value.length }); inputBox.focus(); let done = async.once<boolean, void>(commit => { if (commit) { this.state.actionProvider.runAction(tree, stat, editableData.action, { value: inputBox.value }); } tree.clearHighlight(); tree.DOMFocus(); lifecycle.disposeAll(toDispose); }); var toDispose = [ inputBox, DOM.addStandardDisposableListener(inputBox.inputElement, DOM.EventType.KEY_DOWN, (e: DOM.IKeyboardEvent) => { if (e.equals(CommonKeybindings.ENTER)) { if (inputBox.validate()) { done(true); } } else if (e.equals(CommonKeybindings.ESCAPE)) { done(false); } }), DOM.addDisposableListener(inputBox.inputElement, 'blur', () => { done(inputBox.isInputValid()); }) ]; return () => done(true); } private iconClass(element: FileStat): string { if (element.isDirectory) { return 'folder-icon'; } return 'text-file-icon'; } } // Explorer Accessibility Provider export class FileAccessibilityProvider implements IAccessibilityProvider { public getAriaLabel(tree: ITree, stat: FileStat): string { return nls.localize('filesExplorerViewerAriaLabel', "{0}, Files Explorer", stat.name); } } // Explorer Controller export class FileController extends DefaultController { private didCatchEnterDown: boolean; private state: FileViewletState; private workspace: IWorkspace; constructor(state: FileViewletState, @IWorkbenchEditorService private editorService: IWorkbenchEditorService, @ITextFileService private textFileService: ITextFileService, @IContextMenuService private contextMenuService: IContextMenuService, @IEventService private eventService: IEventService, @IInstantiationService private instantiationService: IInstantiationService, @ITelemetryService private telemetryService: ITelemetryService, @IWorkspaceContextService private contextService: IWorkspaceContextService ) { super({ clickBehavior: ClickBehavior.ON_MOUSE_DOWN }); this.workspace = contextService.getWorkspace(); this.didCatchEnterDown = false; this.downKeyBindingDispatcher.set(platform.isMacintosh ? CommonKeybindings.CTRLCMD_DOWN_ARROW : CommonKeybindings.ENTER, this.onEnterDown.bind(this)); this.upKeyBindingDispatcher.set(platform.isMacintosh ? CommonKeybindings.CTRLCMD_DOWN_ARROW : CommonKeybindings.ENTER, this.onEnterUp.bind(this)); if (platform.isMacintosh) { this.upKeyBindingDispatcher.set(CommonKeybindings.WINCTRL_ENTER, this.onModifierEnterUp.bind(this)); // Mac: somehow Cmd+Enter does not work } else { this.upKeyBindingDispatcher.set(CommonKeybindings.CTRLCMD_ENTER, this.onModifierEnterUp.bind(this)); // Mac: somehow Cmd+Enter does not work } this.downKeyBindingDispatcher.set(platform.isMacintosh ? CommonKeybindings.ENTER : CommonKeybindings.F2, this.onF2.bind(this)); this.downKeyBindingDispatcher.set(CommonKeybindings.CTRLCMD_C, this.onCopy.bind(this)); this.downKeyBindingDispatcher.set(CommonKeybindings.CTRLCMD_V, this.onPaste.bind(this)); if (platform.isMacintosh) { this.downKeyBindingDispatcher.set(CommonKeybindings.CTRLCMD_UP_ARROW, this.onLeft.bind(this)); this.downKeyBindingDispatcher.set(CommonKeybindings.CTRLCMD_BACKSPACE, this.onDelete.bind(this)); } else { this.downKeyBindingDispatcher.set(CommonKeybindings.DELETE, this.onDelete.bind(this)); this.downKeyBindingDispatcher.set(CommonKeybindings.SHIFT_DELETE, this.onDelete.bind(this)); } this.state = state; } /* protected */ public onLeftClick(tree: ITree, stat: FileStat, event: StandardMouseEvent, origin: string = 'mouse'): boolean { let payload = { origin: origin }; let isDoubleClick = (origin === 'mouse' && event.detail === 2); // Handle Highlight Mode if (tree.getHighlight()) { // Cancel Event event.preventDefault(); event.stopPropagation(); tree.clearHighlight(payload); return false; } // Handle root if (this.workspace && stat.resource.toString() === this.workspace.resource.toString()) { tree.clearFocus(payload); tree.clearSelection(payload); return false; } // Cancel Event let isMouseDown = event && event.browserEvent && event.browserEvent.type === 'mousedown'; if (!isMouseDown) { event.preventDefault(); // we cannot preventDefault onMouseDown because this would break DND otherwise } event.stopPropagation(); // Set DOM focus tree.DOMFocus(); // Expand / Collapse tree.toggleExpansion(stat); // Allow to unselect if (event.shiftKey && !(stat instanceof NewStatPlaceholder)) { let selection = tree.getSelection(); if (selection && selection.length > 0 && selection[0] === stat) { tree.clearSelection(payload); } } // Select, Focus and open files else if (!(stat instanceof NewStatPlaceholder)) { let preserveFocus = !isDoubleClick; tree.setFocus(stat, payload); if (isDoubleClick) { event.preventDefault(); // focus moves to editor, we need to prevent default } if (!stat.isDirectory) { tree.setSelection([stat], payload); this.openEditor(stat, preserveFocus, event && (event.ctrlKey || event.metaKey)); // Doubleclick: add to working files set if (isDoubleClick) { this.textFileService.getWorkingFilesModel().addEntry(stat); } } } return true; } public onContextMenu(tree: ITree, stat: FileStat, event: ContextMenuEvent): boolean { if (event.target && event.target.tagName && event.target.tagName.toLowerCase() === 'input') { return false; } event.preventDefault(); event.stopPropagation(); tree.setFocus(stat); if (!this.state.actionProvider.hasSecondaryActions(tree, stat)) { return true; } let anchor = { x: event.posx + 1, y: event.posy }; this.contextMenuService.showContextMenu({ getAnchor: () => anchor, getActions: () => this.state.actionProvider.getSecondaryActions(tree, stat), getActionItem: this.state.actionProvider.getActionItem.bind(this.state.actionProvider, tree, stat), getKeyBinding: (a): Keybinding => keybindingForAction(a.id), getActionsContext: () => { return { viewletState: this.state, stat: stat }; }, onHide: (wasCancelled?: boolean) => { if (wasCancelled) { tree.DOMFocus(); } } }); return true; } private onEnterDown(tree: ITree, event: StandardKeyboardEvent): boolean { if (tree.getHighlight()) { return false; } let payload = { origin: 'keyboard' }; let stat: FileStat = tree.getFocus(); if (stat) { // Directory: Toggle expansion if (stat.isDirectory) { tree.toggleExpansion(stat); } // File: Open else { tree.setFocus(stat, payload); this.openEditor(stat, false, false); } } this.didCatchEnterDown = true; return true; } private onEnterUp(tree: ITree, event: StandardKeyboardEvent): boolean { if (!this.didCatchEnterDown || tree.getHighlight()) { return false; } let stat: FileStat = tree.getFocus(); if (stat && !stat.isDirectory) { this.openEditor(stat, false, false); } this.didCatchEnterDown = false; return true; } private onModifierEnterUp(tree: ITree, event: StandardKeyboardEvent): boolean { if (tree.getHighlight()) { return false; } let stat: FileStat = tree.getFocus(); if (stat && !stat.isDirectory) { this.openEditor(stat, false, true); } this.didCatchEnterDown = false; return true; } private onCopy(tree: ITree, event: StandardKeyboardEvent): boolean { let stat: FileStat = tree.getFocus(); if (stat) { this.runAction(tree, stat, 'workbench.files.action.copyFile').done(); return true; } return false; } private onPaste(tree: ITree, event: StandardKeyboardEvent): boolean { let stat: FileStat = tree.getFocus() || tree.getInput() /* root */; if (stat) { let pasteAction = this.instantiationService.createInstance(PasteFileAction, tree, stat); if (pasteAction._isEnabled()) { pasteAction.run().done(null, errors.onUnexpectedError); return true; } } return false; } private openEditor(stat: FileStat, preserveFocus: boolean, sideBySide: boolean): void { if (stat && !stat.isDirectory) { let editorInput = this.instantiationService.createInstance(FileEditorInput, stat.resource, stat.mime, void 0); let editorOptions = new EditorOptions(); if (preserveFocus) { editorOptions.preserveFocus = true; } this.telemetryService.publicLog('workbenchActionExecuted', { id: 'workbench.files.openFile', from: 'explorer' }); this.editorService.openEditor(editorInput, editorOptions, sideBySide).done(null, errors.onUnexpectedError); } } private onF2(tree: ITree, event: StandardKeyboardEvent): boolean { let stat: FileStat = tree.getFocus(); if (stat) { this.runAction(tree, stat, 'workbench.files.action.triggerRename').done(); return true; } return false; } private onDelete(tree: ITree, event: StandardKeyboardEvent): boolean { let useTrash = !event.shiftKey; let stat: FileStat = tree.getFocus(); if (stat) { this.runAction(tree, stat, useTrash ? 'workbench.files.action.moveFileToTrash' : 'workbench.files.action.deleteFile').done(); return true; } return false; } private runAction(tree: ITree, stat: FileStat, id: string): Promise { return this.state.actionProvider.runAction(tree, stat, id); } } // Explorer Sorter export class FileSorter implements ISorter { public compare(tree: ITree, statA: FileStat, statB: FileStat): number { if (statA.isDirectory && !statB.isDirectory) { return -1; } if (statB.isDirectory && !statA.isDirectory) { return 1; } if (statA.isDirectory && statB.isDirectory) { return statA.name.toLowerCase().localeCompare(statB.name.toLowerCase()); } if (statA instanceof NewStatPlaceholder) { return -1; } if (statB instanceof NewStatPlaceholder) { return 1; } return comparers.compareFileNames(statA.name, statB.name); } } // Explorer Filter export class FileFilter implements IFilter { private hiddenExpression: glob.IExpression; constructor( @IWorkspaceContextService private contextService: IWorkspaceContextService) { this.hiddenExpression = Object.create(null); } public updateConfiguration(configuration: IFilesConfiguration): boolean { let excludesConfig = (configuration && configuration.files && configuration.files.exclude) || Object.create(null); let needsRefresh = !objects.equals(this.hiddenExpression, excludesConfig); this.hiddenExpression = objects.clone(excludesConfig); // do not keep the config, as it gets mutated under our hoods return needsRefresh; } public isVisible(tree: ITree, stat: FileStat): boolean { return this.doIsVisible(stat); } private doIsVisible(stat: FileStat): boolean { if (stat instanceof NewStatPlaceholder) { return true; // always visible } let siblings = stat.parent && stat.parent.children && stat.parent.children.map(c => c.name); // Hide those that match Hidden Patterns if (glob.match(this.hiddenExpression, this.contextService.toWorkspaceRelativePath(stat.resource), siblings)) { return false; // hidden through pattern } return true; } } // Explorer Drag And Drop Controller export class FileDragAndDrop implements IDragAndDrop { constructor( @IMessageService private messageService: IMessageService, @IWorkspaceContextService private contextService: IWorkspaceContextService, @IEventService private eventService: IEventService, @IProgressService private progressService: IProgressService, @IFileService private fileService: IFileService, @IInstantiationService private instantiationService: IInstantiationService, @ITextFileService private textFileService: ITextFileService ) { } public getDragURI(tree: ITree, stat: FileStat): string { return stat.resource && stat.resource.toString(); } public onDragStart(tree: ITree, data: IDragAndDropData, originalEvent: DragMouseEvent): void { let sources: FileStat[] = data.getData(); let source: FileStat = null; if (sources.length > 0) { source = sources[0]; } // When dragging folders, make sure to collapse them to free up some space if (source && source.isDirectory && tree.isExpanded(source)) { tree.collapse(source, false); } // Native only: when a DownloadURL attribute is defined on the data transfer it is possible to // drag a file from the browser to the desktop and have it downloaded there. if (!(data instanceof DesktopDragAndDropData)) { if (source && !source.isDirectory) { originalEvent.dataTransfer.setData('DownloadURL', [MIME_BINARY, source.name, source.resource.toString()].join(':')); } } } public onDragOver(tree: ITree, data: IDragAndDropData, target: FileStat, originalEvent: DragMouseEvent): IDragOverReaction { let isCopy = originalEvent && ((originalEvent.ctrlKey && !platform.isMacintosh) || (originalEvent.altKey && platform.isMacintosh)); let fromDesktop = data instanceof DesktopDragAndDropData; if (this.contextService.getOptions().readOnly) { return DRAG_OVER_REJECT; } // Desktop DND if (fromDesktop) { let dragData = (<DesktopDragAndDropData>data).getData(); let types = dragData.types; let typesArray: string[] = []; for (let i = 0; i < types.length; i++) { typesArray.push(types[i]); } if (typesArray.length === 0 || !typesArray.some((type) => { return type === 'Files'; })) { return DRAG_OVER_REJECT; } } // Other-Tree DND else if (data instanceof ExternalElementsDragAndDropData) { return DRAG_OVER_REJECT; } // In-Explorer DND else { let sources: FileStat[] = data.getData(); if (!Array.isArray(sources)) { return DRAG_OVER_REJECT; } if (sources.some((source) => { if (source instanceof NewStatPlaceholder) { return true; // NewStatPlaceholders can not be moved } if (source.resource.toString() === target.resource.toString()) { return true; // Can not move anything onto itself } if (!isCopy && paths.dirname(source.resource.fsPath) === target.resource.fsPath) { return true; // Can not move a file to the same parent unless we copy } if (paths.isEqualOrParent(target.resource.fsPath, source.resource.fsPath)) { return true; // Can not move a parent folder into one of its children } return false; })) { return DRAG_OVER_REJECT; } } // All if (target.isDirectory) { return fromDesktop || isCopy ? DRAG_OVER_ACCEPT_BUBBLE_DOWN_COPY : DRAG_OVER_ACCEPT_BUBBLE_DOWN; } if (target.resource.toString() !== this.contextService.getWorkspace().resource.toString()) { return fromDesktop || isCopy ? DRAG_OVER_ACCEPT_BUBBLE_UP_COPY : DRAG_OVER_ACCEPT_BUBBLE_UP; } return DRAG_OVER_REJECT; } public drop(tree: ITree, data: IDragAndDropData, target: FileStat, originalEvent: DragMouseEvent): void { let promise: Promise = TPromise.as(null); // Desktop DND (Import file) if (data instanceof DesktopDragAndDropData) { let importAction = this.instantiationService.createInstance(ImportFileAction, tree, target, null); promise = importAction.run({ input: { files: <FileList>(<DesktopDragAndDropData>data).getData().files } }); } // In-Explorer DND (Move/Copy file) else { let source: FileStat = data.getData()[0]; let isCopy = (originalEvent.ctrlKey && !platform.isMacintosh) || (originalEvent.altKey && platform.isMacintosh); promise = tree.expand(target).then(() => { // Reuse action if user copies if (isCopy) { let copyAction = this.instantiationService.createInstance(DuplicateFileAction, tree, source, target); return copyAction.run(); } // Handle dirty let saveOrRevertPromise: Promise = TPromise.as(null); if (this.textFileService.isDirty(source.resource)) { let res = this.textFileService.confirmSave([source.resource]); if (res === ConfirmResult.SAVE) { saveOrRevertPromise = this.textFileService.save(source.resource); } else if (res === ConfirmResult.DONT_SAVE) { saveOrRevertPromise = this.textFileService.revert(source.resource); } else if (res === ConfirmResult.CANCEL) { return TPromise.as(null); } } // For move, first check if file is dirty and save return saveOrRevertPromise.then(() => { // If the file is still dirty, do not touch it because a save is pending to the disk and we can not abort it if (this.textFileService.isDirty(source.resource)) { this.messageService.show(Severity.Warning, nls.localize('warningFileDirty', "File '{0}' is currently being saved, please try again later.", labels.getPathLabel(source.resource))); return TPromise.as(null); } let targetResource = URI.file(paths.join(target.resource.fsPath, source.name)); let didHandleConflict = false; let onMove = (result: IFileStat) => { this.eventService.emit('files.internal:fileChanged', new LocalFileChangeEvent(source.clone(), result)); }; // Move File/Folder and emit event return this.fileService.moveFile(source.resource, targetResource).then(onMove, (error) => { // Conflict if ((<IFileOperationResult>error).fileOperationResult === FileOperationResult.FILE_MOVE_CONFLICT) { didHandleConflict = true; let confirm: IConfirmation = { message: nls.localize('confirmOverwriteMessage', "'{0}' already exists in the destination folder. Do you want to replace it?", source.name), detail: nls.localize('irreversible', "This action is irreversible!"), primaryButton: nls.localize('replaceButtonLabel', "&&Replace") }; if (this.messageService.confirm(confirm)) { return this.fileService.moveFile(source.resource, targetResource, true).then((result) => { let fakeTargetState = new FileStat(targetResource); this.eventService.emit('files.internal:fileChanged', new LocalFileChangeEvent(fakeTargetState, null)); onMove(result); }, (error) => { this.messageService.show(Severity.Error, error); }); } return; } this.messageService.show(Severity.Error, error); }); }); }, errors.onUnexpectedError); } this.progressService.showWhile(promise, 800); promise.done(null, errors.onUnexpectedError); } }
src/vs/workbench/parts/files/browser/views/explorerViewer.ts
0
https://github.com/microsoft/vscode/commit/8435ddcf464fd995936ff6f877ff4744dc3ca2b6
[ 0.8282795548439026, 0.017525849863886833, 0.00016482920909766108, 0.00017301022307947278, 0.11166391521692276 ]
{ "id": 5, "code_window": [ ".monaco-shell .monaco-tree.focused.no-item-focus:active:before {\n", "\toutline: 0 !important; /* fixes some flashing outlines from showing up when clicking */\n", "}\n", "\n", ".monaco-shell .activitybar [tabindex=\"0\"]:focus {\n", "\toutline: 0; /* activity bar indicates focus custom */\n", "}\n", "\n", "/* END Keyboard Focus Indication Styles */\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\toutline: 0 !important; /* activity bar indicates focus custom */\n", "}\n", "\n", ".monaco-shell .part.editor .iframe-container,\n", ".monaco-shell .part.editor .binary-container {\n", "\toutline: 0 !important; /* TODO@Ben we need focus indication for those too */\n" ], "file_path": "src/vs/workbench/electron-browser/media/shell.css", "type": "replace", "edit_start_line_idx": 147 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import URI from 'vs/base/common/uri'; import strings = require('vs/base/common/strings'); import ts = require('vs/languages/typescript/common/lib/typescriptServices'); import EditorCommon = require('vs/editor/common/editorCommon'); import Modes = require('vs/editor/common/modes'); export function getEmitOutput(languageService:ts.LanguageService, resource:URI, type:string):Modes.IEmitOutput { var output = languageService.getEmitOutput(resource.toString()), files = output.outputFiles; if(!files) { return null; } for(var i = 0, len = files.length; i < len; i++) { if(strings.endsWith(files[i].name, type)) { return { filename: files[i].name, content: files[i].text }; } } return null; }
src/vs/languages/typescript/common/features/emitting.ts
0
https://github.com/microsoft/vscode/commit/8435ddcf464fd995936ff6f877ff4744dc3ca2b6
[ 0.00017735287838149816, 0.0001752793905325234, 0.00017172013758681715, 0.00017602223670110106, 0.0000022189356059243437 ]
{ "id": 5, "code_window": [ ".monaco-shell .monaco-tree.focused.no-item-focus:active:before {\n", "\toutline: 0 !important; /* fixes some flashing outlines from showing up when clicking */\n", "}\n", "\n", ".monaco-shell .activitybar [tabindex=\"0\"]:focus {\n", "\toutline: 0; /* activity bar indicates focus custom */\n", "}\n", "\n", "/* END Keyboard Focus Indication Styles */\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\toutline: 0 !important; /* activity bar indicates focus custom */\n", "}\n", "\n", ".monaco-shell .part.editor .iframe-container,\n", ".monaco-shell .part.editor .binary-container {\n", "\toutline: 0 !important; /* TODO@Ben we need focus indication for those too */\n" ], "file_path": "src/vs/workbench/electron-browser/media/shell.css", "type": "replace", "edit_start_line_idx": 147 }
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="3 3 16 16" enable-background="new 3 3 16 16"><polygon fill="#C5C5C5" points="12.597,11.042 15.4,13.845 13.844,15.4 11.042,12.598 8.239,15.4 6.683,13.845 9.485,11.042 6.683,8.239 8.238,6.683 11.042,9.486 13.845,6.683 15.4,8.239"/></svg>
src/vs/workbench/parts/feedback/browser/media/close-dark.svg
0
https://github.com/microsoft/vscode/commit/8435ddcf464fd995936ff6f877ff4744dc3ca2b6
[ 0.00017219218716491014, 0.00017219218716491014, 0.00017219218716491014, 0.00017219218716491014, 0 ]
{ "id": 6, "code_window": [ "\t\t// Container for IFrame\n", "\t\tconst iFrameContainerElement = document.createElement('div');\n", "\t\tiFrameContainerElement.className = 'iframe-container monaco-editor-background'; // Inherit the background color from selected theme\n", "\t\tiFrameContainerElement.appendChild(this._iFrameElement);\n", "\n", "\t\tparent.getHTMLElement().appendChild(iFrameContainerElement);\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\tiFrameContainerElement.tabIndex = 0; // enable focus support from the editor part (do not remove)\n" ], "file_path": "src/vs/workbench/parts/html/browser/htmlPreviewPart.ts", "type": "add", "edit_start_line_idx": 74 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import 'vs/css!./media/iframeeditor'; import nls = require('vs/nls'); import {TPromise} from 'vs/base/common/winjs.base'; import URI from 'vs/base/common/uri'; import DOM = require('vs/base/browser/dom'); import {Dimension, Builder, $} from 'vs/base/browser/builder'; import errors = require('vs/base/common/errors'); import {EditorOptions, EditorInput} from 'vs/workbench/common/editor'; import {BaseEditor} from 'vs/workbench/browser/parts/editor/baseEditor'; import {IFrameEditorInput} from 'vs/workbench/common/editor/iframeEditorInput'; import {IFrameEditorModel} from 'vs/workbench/common/editor/iframeEditorModel'; import {IStorageService} from 'vs/platform/storage/common/storage'; import {Position} from 'vs/platform/editor/common/editor'; import {ITelemetryService} from 'vs/platform/telemetry/common/telemetry'; import {IWorkbenchEditorService} from 'vs/workbench/services/editor/common/editorService'; /** * An implementation of editor for showing HTML content in an IFrame by leveraging the IFrameEditorInput. */ export class IFrameEditor extends BaseEditor { public static ID = 'workbench.editors.iFrameEditor'; private static RESOURCE_PROPERTY = 'resource'; private iframeContainer: Builder; private iframeBuilder: Builder; private focusTracker: DOM.IFocusTracker; constructor( @ITelemetryService telemetryService: ITelemetryService, @IWorkbenchEditorService private editorService: IWorkbenchEditorService, @IStorageService private storageService: IStorageService ) { super(IFrameEditor.ID, telemetryService); } public getTitle(): string { return this.getInput() ? this.getInput().getName() : nls.localize('iframeEditor', "IFrame Viewer"); } public createEditor(parent: Builder): void { // Container for IFrame let iframeContainerElement = document.createElement('div'); iframeContainerElement.className = 'iframe-container monaco-editor-background'; // Inherit the background color from selected theme this.iframeContainer = $(iframeContainerElement); // IFrame this.iframeBuilder = $(this.iframeContainer).element('iframe').addClass('iframe'); this.iframeBuilder.attr({ 'frameborder': '0' }); this.iframeBuilder.removeProperty(IFrameEditor.RESOURCE_PROPERTY); parent.getHTMLElement().appendChild(iframeContainerElement); } public setInput(input: EditorInput, options: EditorOptions): TPromise<void> { let oldInput = this.getInput(); super.setInput(input, options); // Detect options let forceOpen = options && options.forceOpen; // Same Input if (!forceOpen && input.matches(oldInput)) { return TPromise.as<void>(null); } // Assert Input if (!(input instanceof IFrameEditorInput)) { return TPromise.wrapError<void>('Invalid editor input. IFrame editor requires an input instance of IFrameEditorInput.'); } // Different Input (Reload) return this.doSetInput(input, true /* isNewInput */); } private doSetInput(input: EditorInput, isNewInput?: boolean): TPromise<void> { return this.editorService.resolveEditorModel(input, true /* Reload */).then((resolvedModel) => { // Assert Model interface if (!(resolvedModel instanceof IFrameEditorModel)) { return TPromise.wrapError<void>('Invalid editor input. IFrame editor requires a model instance of IFrameEditorModel.'); } // Assert that the current input is still the one we expect. This prevents a race condition when loading takes long and another input was set meanwhile if (!this.getInput() || this.getInput() !== input) { return null; } // Set IFrame contents let iframeModel = <IFrameEditorModel>resolvedModel; let isUpdate = !isNewInput && !!this.iframeBuilder.getProperty(IFrameEditor.RESOURCE_PROPERTY); let contents = iframeModel.getContents(); // Crazy hack to get keybindings to bubble out of the iframe to us contents.body = contents.body + this.enableKeybindings(); // Set Contents try { this.setFrameContents(iframeModel.resource, isUpdate ? contents.body : [contents.head, contents.body, contents.tail].join('\n'), isUpdate /* body only */); } catch (error) { setTimeout(() => this.reload(true /* clear */), 1000); // retry in case of an error which indicates the iframe (only) might be on a different URL } // When content is fully replaced, we also need to recreate the focus tracker if (!isUpdate) { this.clearFocusTracker(); } // Track focus on contents and make the editor active when focus is received if (!this.focusTracker) { this.focusTracker = DOM.trackFocus((<HTMLIFrameElement>this.iframeBuilder.getHTMLElement()).contentWindow); this.focusTracker.addFocusListener(() => { this.editorService.activateEditor(this.position); }); } }); } private setFrameContents(resource: URI, contents: string, isUpdate: boolean): void { let iframeWindow = (<HTMLIFrameElement>this.iframeBuilder.getHTMLElement()).contentWindow; // Update body only if this is an update of the same resource (preserves scroll position and does not flicker) if (isUpdate) { iframeWindow.document.body.innerHTML = contents; } // Write directly to iframe document replacing any previous content else { iframeWindow.document.open('text/html', 'replace'); iframeWindow.document.write(contents); iframeWindow.document.close(); // Reset scroll iframeWindow.scrollTo(0, 0); // Associate resource with iframe this.iframeBuilder.setProperty(IFrameEditor.RESOURCE_PROPERTY, resource.toString()); } } private enableKeybindings(): string { return [ '<script>', 'var ignoredKeys = [9 /* tab */, 32 /* space */, 33 /* page up */, 34 /* page down */, 38 /* up */, 40 /* down */];', 'var ignoredCtrlCmdKeys = [65 /* a */, 67 /* c */];', 'var ignoredShiftKeys = [9 /* tab */];', 'window.document.body.addEventListener("keydown", function(event) {', // Listen to keydown events in the iframe ' try {', ' if (ignoredKeys.some(function(i) { return i === event.keyCode; })) {', ' if (!event.ctrlKey && !event.altKey && !event.shiftKey && !event.metaKey) {', ' return;', // we want some single keys to be supported (e.g. Page Down for scrolling) ' }', ' }', '', ' if (ignoredCtrlCmdKeys.some(function(i) { return i === event.keyCode; })) {', ' if (event.ctrlKey || event.metaKey) {', ' return;', // we want some ctrl/cmd keys to be supported (e.g. Ctrl+C for copy) ' }', ' }', '', ' if (ignoredShiftKeys.some(function(i) { return i === event.keyCode; })) {', ' if (event.shiftKey) {', ' return;', // we want some shift keys to be supported (e.g. Shift+Tab for copy) ' }', ' }', '', ' event.preventDefault();', // very important to not get duplicate actions when this one bubbles up! '', ' var fakeEvent = document.createEvent("KeyboardEvent");', // create a keyboard event ' Object.defineProperty(fakeEvent, "keyCode", {', // we need to set some properties that Chrome wants ' get : function() {', ' return event.keyCode;', ' }', ' });', ' Object.defineProperty(fakeEvent, "which", {', ' get : function() {', ' return event.keyCode;', ' }', ' });', ' Object.defineProperty(fakeEvent, "target", {', ' get : function() {', ' return window && window.parent.document.body;', ' }', ' });', '', ' fakeEvent.initKeyboardEvent("keydown", true, true, document.defaultView, null, null, event.ctrlKey, event.altKey, event.shiftKey, event.metaKey);', // the API shape of this method is not clear to me, but it works ;) '', ' window.parent.document.dispatchEvent(fakeEvent);', // dispatch the event onto the parent ' } catch (error) {}', '});', // disable dropping into iframe! 'window.document.addEventListener("dragover", function (e) {', ' e.preventDefault();', '});', 'window.document.addEventListener("drop", function (e) {', ' e.preventDefault();', '});', 'window.document.body.addEventListener("dragover", function (e) {', ' e.preventDefault();', '});', 'window.document.body.addEventListener("drop", function (e) {', ' e.preventDefault();', '});', '</script>' ].join('\n'); } public clearInput(): void { // Reset IFrame this.clearIFrame(); super.clearInput(); } private clearIFrame(): void { this.iframeBuilder.src('about:blank'); this.iframeBuilder.removeProperty(IFrameEditor.RESOURCE_PROPERTY); // Focus Listener this.clearFocusTracker(); } private clearFocusTracker(): void { if (this.focusTracker) { this.focusTracker.dispose(); this.focusTracker = null; } } public layout(dimension: Dimension): void { // Pass on to IFrame Container and IFrame this.iframeContainer.size(dimension.width, dimension.height); this.iframeBuilder.size(dimension.width, dimension.height); } public focus(): void { this.iframeContainer.domFocus(); } public changePosition(position: Position): void { super.changePosition(position); // reparenting an IFRAME into another DOM element yields weird results when the contents are made // of a string and not a URL. to be on the safe side we reload the iframe when the position changes // and we do it using a timeout of 0 to reload only after the position has been changed in the DOM setTimeout(() => this.reload(true)); } public supportsSplitEditor(): boolean { return true; } /** * Reloads the contents of the iframe in this editor by reapplying the input. */ public reload(clearIFrame?: boolean): void { if (this.input) { if (clearIFrame) { this.clearIFrame(); } this.doSetInput(this.input).done(null, errors.onUnexpectedError); } } public dispose(): void { // Destroy Container this.iframeContainer.destroy(); // Focus Listener this.clearFocusTracker(); super.dispose(); } }
src/vs/workbench/browser/parts/editor/iframeEditor.ts
1
https://github.com/microsoft/vscode/commit/8435ddcf464fd995936ff6f877ff4744dc3ca2b6
[ 0.9935163259506226, 0.037825312465429306, 0.0001641647977521643, 0.00017569413466844708, 0.18139201402664185 ]
{ "id": 6, "code_window": [ "\t\t// Container for IFrame\n", "\t\tconst iFrameContainerElement = document.createElement('div');\n", "\t\tiFrameContainerElement.className = 'iframe-container monaco-editor-background'; // Inherit the background color from selected theme\n", "\t\tiFrameContainerElement.appendChild(this._iFrameElement);\n", "\n", "\t\tparent.getHTMLElement().appendChild(iFrameContainerElement);\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\tiFrameContainerElement.tabIndex = 0; // enable focus support from the editor part (do not remove)\n" ], "file_path": "src/vs/workbench/parts/html/browser/htmlPreviewPart.ts", "type": "add", "edit_start_line_idx": 74 }
<svg width="16" height="16" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><g fill="none" fill-rule="evenodd"><g stroke="#5A5A5A" stroke-width="3" stroke-opacity="0.8"><circle cx="8" cy="8" r="4"/></g></g></svg>
src/vs/workbench/parts/debug/browser/media/breakpoint-unverified-dark.svg
0
https://github.com/microsoft/vscode/commit/8435ddcf464fd995936ff6f877ff4744dc3ca2b6
[ 0.00017285498324781656, 0.00017285498324781656, 0.00017285498324781656, 0.00017285498324781656, 0 ]
{ "id": 6, "code_window": [ "\t\t// Container for IFrame\n", "\t\tconst iFrameContainerElement = document.createElement('div');\n", "\t\tiFrameContainerElement.className = 'iframe-container monaco-editor-background'; // Inherit the background color from selected theme\n", "\t\tiFrameContainerElement.appendChild(this._iFrameElement);\n", "\n", "\t\tparent.getHTMLElement().appendChild(iFrameContainerElement);\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\tiFrameContainerElement.tabIndex = 0; // enable focus support from the editor part (do not remove)\n" ], "file_path": "src/vs/workbench/parts/html/browser/htmlPreviewPart.ts", "type": "add", "edit_start_line_idx": 74 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ /*--------------------------------------------------------------------------------------------- *--------------------------------------------------------------------------------------------- *--------------------------------------------------------------------------------------------- *--------------------------------------------------------------------------------------------- *--------------------------------------------------------------------------------------------- * Please make sure to make edits in the .ts file at https://github.com/Microsoft/vscode-loader/ *--------------------------------------------------------------------------------------------- *--------------------------------------------------------------------------------------------- *--------------------------------------------------------------------------------------------- *--------------------------------------------------------------------------------------------- *--------------------------------------------------------------------------------------------*/ /// <reference path="declares.ts" /> /// <reference path="loader.ts" /> 'use strict'; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var _cssPluginGlobal = this; var CSSLoaderPlugin; (function (CSSLoaderPlugin) { var global = _cssPluginGlobal; /** * Known issue: * - In IE there is no way to know if the CSS file loaded successfully or not. */ var BrowserCSSLoader = (function () { function BrowserCSSLoader() { this._pendingLoads = 0; } BrowserCSSLoader.prototype.attachListeners = function (name, linkNode, callback, errorback) { var unbind = function () { linkNode.removeEventListener('load', loadEventListener); linkNode.removeEventListener('error', errorEventListener); }; var loadEventListener = function (e) { unbind(); callback(); }; var errorEventListener = function (e) { unbind(); errorback(e); }; linkNode.addEventListener('load', loadEventListener); linkNode.addEventListener('error', errorEventListener); }; BrowserCSSLoader.prototype._onLoad = function (name, callback) { this._pendingLoads--; callback(); }; BrowserCSSLoader.prototype._onLoadError = function (name, errorback, err) { this._pendingLoads--; errorback(err); }; BrowserCSSLoader.prototype._insertLinkNode = function (linkNode) { this._pendingLoads++; var head = document.head || document.getElementsByTagName('head')[0]; var other = head.getElementsByTagName('link') || document.head.getElementsByTagName('script'); if (other.length > 0) { head.insertBefore(linkNode, other[other.length - 1]); } else { head.appendChild(linkNode); } }; BrowserCSSLoader.prototype.createLinkTag = function (name, cssUrl, externalCallback, externalErrorback) { var _this = this; var linkNode = document.createElement('link'); linkNode.setAttribute('rel', 'stylesheet'); linkNode.setAttribute('type', 'text/css'); linkNode.setAttribute('data-name', name); var callback = function () { return _this._onLoad(name, externalCallback); }; var errorback = function (err) { return _this._onLoadError(name, externalErrorback, err); }; this.attachListeners(name, linkNode, callback, errorback); linkNode.setAttribute('href', cssUrl); return linkNode; }; BrowserCSSLoader.prototype._linkTagExists = function (name, cssUrl) { var i, len, nameAttr, hrefAttr, links = document.getElementsByTagName('link'); for (i = 0, len = links.length; i < len; i++) { nameAttr = links[i].getAttribute('data-name'); hrefAttr = links[i].getAttribute('href'); if (nameAttr === name || hrefAttr === cssUrl) { return true; } } return false; }; BrowserCSSLoader.prototype.load = function (name, cssUrl, externalCallback, externalErrorback) { if (this._linkTagExists(name, cssUrl)) { externalCallback(); return; } var linkNode = this.createLinkTag(name, cssUrl, externalCallback, externalErrorback); this._insertLinkNode(linkNode); }; return BrowserCSSLoader; })(); /** * Prior to IE10, IE could not go above 31 stylesheets in a page * http://blogs.msdn.com/b/ieinternals/archive/2011/05/14/internet-explorer-stylesheet-rule-selector-import-sheet-limit-maximum.aspx * * The general strategy here is to not write more than 31 link nodes to the page at the same time * When stylesheets get loaded, they will get merged one into another to free up * some positions for new link nodes. */ var IE9CSSLoader = (function (_super) { __extends(IE9CSSLoader, _super); function IE9CSSLoader() { _super.call(this); this._blockedLoads = []; this._mergeStyleSheetsTimeout = -1; } IE9CSSLoader.prototype.load = function (name, cssUrl, externalCallback, externalErrorback) { if (this._linkTagExists(name, cssUrl)) { externalCallback(); return; } var linkNode = this.createLinkTag(name, cssUrl, externalCallback, externalErrorback); if (this._styleSheetCount() < 31) { this._insertLinkNode(linkNode); } else { this._blockedLoads.push(linkNode); this._handleBlocked(); } }; IE9CSSLoader.prototype._styleSheetCount = function () { var linkCount = document.getElementsByTagName('link').length; var styleCount = document.getElementsByTagName('style').length; return linkCount + styleCount; }; IE9CSSLoader.prototype._onLoad = function (name, callback) { _super.prototype._onLoad.call(this, name, callback); this._handleBlocked(); }; IE9CSSLoader.prototype._onLoadError = function (name, errorback, err) { _super.prototype._onLoadError.call(this, name, errorback, err); this._handleBlocked(); }; IE9CSSLoader.prototype._handleBlocked = function () { var _this = this; var blockedLoadsCount = this._blockedLoads.length; if (blockedLoadsCount > 0 && this._mergeStyleSheetsTimeout === -1) { this._mergeStyleSheetsTimeout = window.setTimeout(function () { return _this._mergeStyleSheets(); }, 0); } }; IE9CSSLoader.prototype._mergeStyleSheet = function (dstPath, dst, srcPath, src) { for (var i = src.rules.length - 1; i >= 0; i--) { dst.insertRule(Utilities.rewriteUrls(srcPath, dstPath, src.rules[i].cssText), 0); } }; IE9CSSLoader.prototype._asIE9HTMLLinkElement = function (linkElement) { return linkElement; }; IE9CSSLoader.prototype._mergeStyleSheets = function () { this._mergeStyleSheetsTimeout = -1; var blockedLoadsCount = this._blockedLoads.length; var i, linkDomNodes = document.getElementsByTagName('link'); var linkDomNodesCount = linkDomNodes.length; var mergeCandidates = []; for (i = 0; i < linkDomNodesCount; i++) { if (linkDomNodes[i].readyState === 'loaded' || linkDomNodes[i].readyState === 'complete') { mergeCandidates.push({ linkNode: linkDomNodes[i], rulesLength: this._asIE9HTMLLinkElement(linkDomNodes[i]).styleSheet.rules.length }); } } var mergeCandidatesCount = mergeCandidates.length; // Just a little legend here :) // - linkDomNodesCount: total number of link nodes in the DOM (this should be kept <= 31) // - mergeCandidatesCount: loaded (finished) link nodes in the DOM (only these can be merged) // - blockedLoadsCount: remaining number of load requests that did not fit in before (because of the <= 31 constraint) // Now comes the heuristic part, we don't want to do too much work with the merging of styles, // but we do need to merge stylesheets to free up loading slots. var mergeCount = Math.min(Math.floor(mergeCandidatesCount / 2), blockedLoadsCount); // Sort the merge candidates descending (least rules last) mergeCandidates.sort(function (a, b) { return b.rulesLength - a.rulesLength; }); var srcIndex, dstIndex; for (i = 0; i < mergeCount; i++) { srcIndex = mergeCandidates.length - 1 - i; dstIndex = i % (mergeCandidates.length - mergeCount); // Merge rules of src into dst this._mergeStyleSheet(mergeCandidates[dstIndex].linkNode.href, this._asIE9HTMLLinkElement(mergeCandidates[dstIndex].linkNode).styleSheet, mergeCandidates[srcIndex].linkNode.href, this._asIE9HTMLLinkElement(mergeCandidates[srcIndex].linkNode).styleSheet); // Remove dom node of src mergeCandidates[srcIndex].linkNode.parentNode.removeChild(mergeCandidates[srcIndex].linkNode); linkDomNodesCount--; } var styleSheetCount = this._styleSheetCount(); while (styleSheetCount < 31 && this._blockedLoads.length > 0) { this._insertLinkNode(this._blockedLoads.shift()); styleSheetCount++; } }; return IE9CSSLoader; })(BrowserCSSLoader); var IE8CSSLoader = (function (_super) { __extends(IE8CSSLoader, _super); function IE8CSSLoader() { _super.call(this); } IE8CSSLoader.prototype.attachListeners = function (name, linkNode, callback, errorback) { linkNode.onload = function () { linkNode.onload = null; callback(); }; }; return IE8CSSLoader; })(IE9CSSLoader); var NodeCSSLoader = (function () { function NodeCSSLoader() { this.fs = require.nodeRequire('fs'); } NodeCSSLoader.prototype.load = function (name, cssUrl, externalCallback, externalErrorback) { var contents = this.fs.readFileSync(cssUrl, 'utf8'); // Remove BOM if (contents.charCodeAt(0) === NodeCSSLoader.BOM_CHAR_CODE) { contents = contents.substring(1); } externalCallback(contents); }; NodeCSSLoader.BOM_CHAR_CODE = 65279; return NodeCSSLoader; })(); // ------------------------------ Finally, the plugin var CSSPlugin = (function () { function CSSPlugin(cssLoader) { this.cssLoader = cssLoader; } CSSPlugin.prototype.load = function (name, req, load, config) { config = config || {}; var cssUrl = req.toUrl(name + '.css'); this.cssLoader.load(name, cssUrl, function (contents) { // Contents has the CSS file contents if we are in a build if (config.isBuild) { CSSPlugin.BUILD_MAP[name] = contents; } load({}); }, function (err) { if (typeof load.error === 'function') { load.error('Could not find ' + cssUrl + ' or it was empty'); } }); }; CSSPlugin.prototype.write = function (pluginName, moduleName, write) { // getEntryPoint is a Monaco extension to r.js var entryPoint = write.getEntryPoint(); // r.js destroys the context of this plugin between calling 'write' and 'writeFile' // so the only option at this point is to leak the data to a global global.cssPluginEntryPoints = global.cssPluginEntryPoints || {}; global.cssPluginEntryPoints[entryPoint] = global.cssPluginEntryPoints[entryPoint] || []; global.cssPluginEntryPoints[entryPoint].push({ moduleName: moduleName, contents: CSSPlugin.BUILD_MAP[moduleName] }); write.asModule(pluginName + '!' + moduleName, 'define([\'vs/css!' + entryPoint + '\'], {});'); }; CSSPlugin.prototype.writeFile = function (pluginName, moduleName, req, write, config) { if (global.cssPluginEntryPoints && global.cssPluginEntryPoints.hasOwnProperty(moduleName)) { var fileName = req.toUrl(moduleName + '.css'); var contents = [ '/*---------------------------------------------------------', ' * Copyright (C) Microsoft Corporation. All rights reserved.', ' *--------------------------------------------------------*/' ], entries = global.cssPluginEntryPoints[moduleName]; for (var i = 0; i < entries.length; i++) { contents.push(Utilities.rewriteUrls(entries[i].moduleName, moduleName, entries[i].contents)); } write(fileName, contents.join('\r\n')); } }; CSSPlugin.BUILD_MAP = {}; return CSSPlugin; })(); CSSLoaderPlugin.CSSPlugin = CSSPlugin; var Utilities = (function () { function Utilities() { } Utilities.startsWith = function (haystack, needle) { return haystack.length >= needle.length && haystack.substr(0, needle.length) === needle; }; /** * Find the path of a file. */ Utilities.pathOf = function (filename) { var lastSlash = filename.lastIndexOf('/'); if (lastSlash !== -1) { return filename.substr(0, lastSlash + 1); } else { return ''; } }; /** * A conceptual a + b for paths. * Takes into account if `a` contains a protocol. * Also normalizes the result: e.g.: a/b/ + ../c => a/c */ Utilities.joinPaths = function (a, b) { function findSlashIndexAfterPrefix(haystack, prefix) { if (Utilities.startsWith(haystack, prefix)) { return Math.max(prefix.length, haystack.indexOf('/', prefix.length)); } return 0; } var aPathStartIndex = 0; aPathStartIndex = aPathStartIndex || findSlashIndexAfterPrefix(a, '//'); aPathStartIndex = aPathStartIndex || findSlashIndexAfterPrefix(a, 'http://'); aPathStartIndex = aPathStartIndex || findSlashIndexAfterPrefix(a, 'https://'); function pushPiece(pieces, piece) { if (piece === './') { // Ignore return; } if (piece === '../') { var prevPiece = (pieces.length > 0 ? pieces[pieces.length - 1] : null); if (prevPiece && prevPiece === '/') { // Ignore return; } if (prevPiece && prevPiece !== '../') { // Pop pieces.pop(); return; } } // Push pieces.push(piece); } function push(pieces, path) { while (path.length > 0) { var slashIndex = path.indexOf('/'); var piece = (slashIndex >= 0 ? path.substring(0, slashIndex + 1) : path); path = (slashIndex >= 0 ? path.substring(slashIndex + 1) : ''); pushPiece(pieces, piece); } } var pieces = []; push(pieces, a.substr(aPathStartIndex)); if (b.length > 0 && b.charAt(0) === '/') { pieces = []; } push(pieces, b); return a.substring(0, aPathStartIndex) + pieces.join(''); }; Utilities.commonPrefix = function (str1, str2) { var len = Math.min(str1.length, str2.length); for (var i = 0; i < len; i++) { if (str1.charCodeAt(i) !== str2.charCodeAt(i)) { break; } } return str1.substring(0, i); }; Utilities.commonFolderPrefix = function (fromPath, toPath) { var prefix = Utilities.commonPrefix(fromPath, toPath); var slashIndex = prefix.lastIndexOf('/'); if (slashIndex === -1) { return ''; } return prefix.substring(0, slashIndex + 1); }; Utilities.relativePath = function (fromPath, toPath) { if (Utilities.startsWith(toPath, '/') || Utilities.startsWith(toPath, 'http://') || Utilities.startsWith(toPath, 'https://')) { return toPath; } // Ignore common folder prefix var prefix = Utilities.commonFolderPrefix(fromPath, toPath); fromPath = fromPath.substr(prefix.length); toPath = toPath.substr(prefix.length); var upCount = fromPath.split('/').length; var result = ''; for (var i = 1; i < upCount; i++) { result += '../'; } return result + toPath; }; Utilities.rewriteUrls = function (originalFile, newFile, contents) { // Use ")" as the terminator as quotes are oftentimes not used at all return contents.replace(/url\(\s*([^\)]+)\s*\)?/g, function (_) { var matches = []; for (var _i = 1; _i < arguments.length; _i++) { matches[_i - 1] = arguments[_i]; } var url = matches[0]; // Eliminate starting quotes (the initial whitespace is not captured) if (url.charAt(0) === '"' || url.charAt(0) === '\'') { url = url.substring(1); } // The ending whitespace is captured while (url.length > 0 && (url.charAt(url.length - 1) === ' ' || url.charAt(url.length - 1) === '\t')) { url = url.substring(0, url.length - 1); } // Eliminate ending quotes if (url.charAt(url.length - 1) === '"' || url.charAt(url.length - 1) === '\'') { url = url.substring(0, url.length - 1); } if (!Utilities.startsWith(url, 'data:') && !Utilities.startsWith(url, 'http://') && !Utilities.startsWith(url, 'https://')) { var absoluteUrl = Utilities.joinPaths(Utilities.pathOf(originalFile), url); url = Utilities.relativePath(newFile, absoluteUrl); } return 'url(' + url + ')'; }); }; return Utilities; })(); CSSLoaderPlugin.Utilities = Utilities; (function () { var cssLoader = null; var isElectron = (typeof process !== 'undefined' && typeof process.versions !== 'undefined' && typeof process.versions['electron'] !== 'undefined'); if (typeof process !== 'undefined' && process.versions && !!process.versions.node && !isElectron) { cssLoader = new NodeCSSLoader(); } else if (typeof navigator !== 'undefined' && navigator.userAgent.indexOf('MSIE 9') >= 0) { cssLoader = new IE9CSSLoader(); } else if (typeof navigator !== 'undefined' && navigator.userAgent.indexOf('MSIE 8') >= 0) { cssLoader = new IE8CSSLoader(); } else { cssLoader = new BrowserCSSLoader(); } define('vs/css', new CSSPlugin(cssLoader)); })(); })(CSSLoaderPlugin || (CSSLoaderPlugin = {}));
src/vs/css.js
0
https://github.com/microsoft/vscode/commit/8435ddcf464fd995936ff6f877ff4744dc3ca2b6
[ 0.00017578396364115179, 0.00017025652050506324, 0.00016213313210755587, 0.00017071879119612277, 0.0000031119204777496634 ]
{ "id": 6, "code_window": [ "\t\t// Container for IFrame\n", "\t\tconst iFrameContainerElement = document.createElement('div');\n", "\t\tiFrameContainerElement.className = 'iframe-container monaco-editor-background'; // Inherit the background color from selected theme\n", "\t\tiFrameContainerElement.appendChild(this._iFrameElement);\n", "\n", "\t\tparent.getHTMLElement().appendChild(iFrameContainerElement);\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\tiFrameContainerElement.tabIndex = 0; // enable focus support from the editor part (do not remove)\n" ], "file_path": "src/vs/workbench/parts/html/browser/htmlPreviewPart.ts", "type": "add", "edit_start_line_idx": 74 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import { assign } from 'vs/base/common/objects'; import { TPromise } from 'vs/base/common/winjs.base'; import { IGalleryService, IExtension } from 'vs/workbench/parts/extensions/common/extensions'; import { IRequestService } from 'vs/platform/request/common/request'; import { IWorkspaceContextService } from 'vs/workbench/services/workspace/common/contextService'; import { nfcall } from 'vs/base/common/async'; import * as fs from 'fs'; export interface IGalleryExtensionFile { assetType: string; } export interface IGalleryExtensionVersion { version: string; lastUpdated: string; assetUri: string; files: IGalleryExtensionFile[]; } export interface IGalleryExtension { extensionId: string; extensionName: string; displayName: string; shortDescription: string; publisher: { displayName: string, publisherId: string, publisherName: string; }; versions: IGalleryExtensionVersion[]; galleryApiUrl: string; statistics: IGalleryExtensionStatistics[]; } export interface IGalleryExtensionStatistics { statisticName: string; value: number; } function getInstallCount(statistics: IGalleryExtensionStatistics[]): number { if (!statistics) { return 0; } const result = statistics.filter(s => s.statisticName === 'install')[0]; return result ? result.value : 0; } export class GalleryService implements IGalleryService { public serviceId = IGalleryService; private extensionsGalleryUrl: string; constructor( @IRequestService private requestService: IRequestService, @IWorkspaceContextService contextService: IWorkspaceContextService ) { const extensionsGalleryConfig = contextService.getConfiguration().env.extensionsGallery; this.extensionsGalleryUrl = extensionsGalleryConfig && extensionsGalleryConfig.serviceUrl; } private api(path = ''): string { return `${ this.extensionsGalleryUrl }${ path }`; } public isEnabled(): boolean { return !!this.extensionsGalleryUrl; } public query(): TPromise<IExtension[]> { if (!this.extensionsGalleryUrl) { return TPromise.wrapError(new Error('No extension gallery service configured.')); } const data = JSON.stringify({ filters: [{ criteria:[{ filterType: 1, value: 'vscode' }] }], flags: 0x1 | 0x4 | 0x80 | 0x100 }); const request = { type: 'POST', url: this.api('/extensionquery'), data: data, headers: { 'Content-Type': 'application/json', 'Accept': 'application/json;api-version=3.0-preview.1', 'Content-Length': data.length } }; return this.requestService.makeRequest(request) .then<IGalleryExtension[]>(r => JSON.parse(r.responseText).results[0].extensions || []) .then<IExtension[]>(extensions => { return extensions.map(extension => ({ name: extension.extensionName, displayName: extension.displayName || extension.extensionName, publisher: extension.publisher.publisherName, version: extension.versions[0].version, description: extension.shortDescription || '', galleryInformation: { galleryApiUrl: this.extensionsGalleryUrl, id: extension.extensionId, downloadUrl: `${ extension.versions[0].assetUri }/Microsoft.VisualStudio.Services.VSIXPackage?install=true`, publisherId: extension.publisher.publisherId, publisherDisplayName: extension.publisher.displayName, installCount: getInstallCount(extension.statistics), date: extension.versions[0].lastUpdated, } })); }); } }
src/vs/workbench/parts/extensions/node/vsoGalleryService.ts
0
https://github.com/microsoft/vscode/commit/8435ddcf464fd995936ff6f877ff4744dc3ca2b6
[ 0.00017694782582111657, 0.00017436033522244543, 0.00017053063493221998, 0.00017505518917459995, 0.000002210737193308887 ]
{ "id": 7, "code_window": [ "\t\t\t\tthis._modelChangeUnbind = this._model.addListener(EventType.ModelContentChanged2, () => this._updateIFrameContent());\n", "\t\t\t\tthis._updateIFrameContent();\n", "\t\t\t} else {\n", "\t\t\t\tthis._modelChangeUnbind = cAll(this._modelChangeUnbind);\n", "\t\t\t}\n", "\t\t})\n", "\t}\n", "\n", "\tpublic changePosition(position: Position): void {\n", "\t\tsuper.changePosition(position);\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t});\n" ], "file_path": "src/vs/workbench/parts/html/browser/htmlPreviewPart.ts", "type": "replace", "edit_start_line_idx": 115 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; // import 'vs/css!./media/iframeeditor'; import {localize} from 'vs/nls'; import {TPromise} from 'vs/base/common/winjs.base'; import {IModel, EventType} from 'vs/editor/common/editorCommon'; import {Dimension, Builder} from 'vs/base/browser/builder'; import {cAll} from 'vs/base/common/lifecycle'; import {EditorOptions, EditorInput} from 'vs/workbench/common/editor'; import {BaseEditor} from 'vs/workbench/browser/parts/editor/baseEditor'; import {Position} from 'vs/platform/editor/common/editor'; import {ITelemetryService} from 'vs/platform/telemetry/common/telemetry'; import {IStorageService, StorageEventType, StorageScope} from 'vs/platform/storage/common/storage'; import {IWorkbenchEditorService} from 'vs/workbench/services/editor/common/editorService'; import {BaseTextEditorModel} from 'vs/workbench/common/editor/textEditorModel'; import {Preferences} from 'vs/workbench/common/constants'; import {HtmlInput} from 'vs/workbench/parts/html/common/htmlInput'; import {isLightTheme} from 'vs/platform/theme/common/themes'; import {DEFAULT_THEME_ID} from 'vs/workbench/services/themes/common/themeService'; /** * An implementation of editor for showing HTML content in an IFrame by leveraging the IFrameEditorInput. */ export class HtmlPreviewPart extends BaseEditor { static ID: string = 'workbench.editor.htmlPreviewPart'; private _editorService: IWorkbenchEditorService; private _storageService: IStorageService; private _iFrameElement: HTMLIFrameElement; private _model: IModel; private _modelChangeUnbind: Function; private _lastModelVersion: number; private _themeChangeUnbind: Function; constructor( @ITelemetryService telemetryService: ITelemetryService, @IWorkbenchEditorService editorService: IWorkbenchEditorService, @IStorageService storageService: IStorageService ) { super(HtmlPreviewPart.ID, telemetryService); this._editorService = editorService; this._storageService = storageService; } dispose(): void { // remove from dome const element = this._iFrameElement.parentElement; element.parentElement.removeChild(element); // unhook from model this._modelChangeUnbind = cAll(this._modelChangeUnbind); this._model = undefined; this._themeChangeUnbind = cAll(this._themeChangeUnbind); } public createEditor(parent: Builder): void { // IFrame // this.iframeBuilder.removeProperty(IFrameEditor.RESOURCE_PROPERTY); this._iFrameElement = document.createElement('iframe'); this._iFrameElement.setAttribute('frameborder', '0'); this._iFrameElement.className = 'iframe'; // Container for IFrame const iFrameContainerElement = document.createElement('div'); iFrameContainerElement.className = 'iframe-container monaco-editor-background'; // Inherit the background color from selected theme iFrameContainerElement.appendChild(this._iFrameElement); parent.getHTMLElement().appendChild(iFrameContainerElement); this._themeChangeUnbind = this._storageService.addListener(StorageEventType.STORAGE, event => { if (event.key === Preferences.THEME && this.isVisible()) { this._updateIFrameContent(true); } }); } public layout(dimension: Dimension): void { let {width, height} = dimension; this._iFrameElement.parentElement.style.width = `${width}px`; this._iFrameElement.parentElement.style.height = `${height}px`; this._iFrameElement.style.width = `${width}px`; this._iFrameElement.style.height = `${height}px`; } public focus(): void { // this.iframeContainer.domFocus(); this._iFrameElement.focus(); } // --- input public getTitle(): string { if (!this.input) { return localize('iframeEditor', 'Preview Html'); } return this.input.getName(); } public setVisible(visible: boolean, position?: Position): TPromise<void> { return super.setVisible(visible, position).then(() => { if (visible && this._model) { this._modelChangeUnbind = this._model.addListener(EventType.ModelContentChanged2, () => this._updateIFrameContent()); this._updateIFrameContent(); } else { this._modelChangeUnbind = cAll(this._modelChangeUnbind); } }) } public changePosition(position: Position): void { super.changePosition(position); // reparenting an IFRAME into another DOM element yields weird results when the contents are made // of a string and not a URL. to be on the safe side we reload the iframe when the position changes // and we do it using a timeout of 0 to reload only after the position has been changed in the DOM setTimeout(() => { this._updateIFrameContent(true); }, 0); } public setInput(input: EditorInput, options: EditorOptions): TPromise<void> { this._model = undefined; this._modelChangeUnbind = cAll(this._modelChangeUnbind); this._lastModelVersion = -1; if (!(input instanceof HtmlInput)) { return TPromise.wrapError<void>('Invalid input'); } return this._editorService.resolveEditorModel({ resource: (<HtmlInput>input).getResource() }).then(model => { if (model instanceof BaseTextEditorModel) { this._model = model.textEditorModel } if (!this._model) { return TPromise.wrapError<void>(localize('html.voidInput', "Invalid editor input.")); } this._modelChangeUnbind = this._model.addListener(EventType.ModelContentChanged2, () => this._updateIFrameContent()); this._updateIFrameContent(); return super.setInput(input, options); }); } private _updateIFrameContent(refresh: boolean = false): void { if (!this._model || (!refresh && this._lastModelVersion === this._model.getVersionId())) { // nothing to do return; } const html = this._model.getValue(); const iFrameDocument = this._iFrameElement.contentDocument; if (!iFrameDocument) { // not visible anymore return; } // the very first time we load just our script // to integrate with the outside world if ((<HTMLElement>iFrameDocument.firstChild).innerHTML === '<head></head><body></body>') { iFrameDocument.open('text/html', 'replace'); iFrameDocument.write(Integration.defaultHtml()); iFrameDocument.close(); } // diff a little against the current input and the new state const parser = new DOMParser(); const newDocument = parser.parseFromString(html, 'text/html'); const styleElement = Integration.defaultStyle(this._iFrameElement.parentElement, this._storageService.get(Preferences.THEME, StorageScope.GLOBAL, DEFAULT_THEME_ID)); if (newDocument.head.hasChildNodes()) { newDocument.head.insertBefore(styleElement, newDocument.head.firstChild); } else { newDocument.head.appendChild(styleElement) } if (newDocument.head.innerHTML !== iFrameDocument.head.innerHTML) { iFrameDocument.head.innerHTML = newDocument.head.innerHTML; } if (newDocument.body.innerHTML !== iFrameDocument.body.innerHTML) { iFrameDocument.body.innerHTML = newDocument.body.innerHTML; } this._lastModelVersion = this._model.getVersionId(); } } namespace Integration { 'use strict'; const scriptSource = [ 'var ignoredKeys = [9 /* tab */, 32 /* space */, 33 /* page up */, 34 /* page down */, 38 /* up */, 40 /* down */];', 'var ignoredCtrlCmdKeys = [65 /* a */, 67 /* c */];', 'var ignoredShiftKeys = [9 /* tab */];', 'window.document.body.addEventListener("keydown", function(event) {', // Listen to keydown events in the iframe ' try {', ' if (ignoredKeys.some(function(i) { return i === event.keyCode; })) {', ' if (!event.ctrlKey && !event.altKey && !event.shiftKey && !event.metaKey) {', ' return;', // we want some single keys to be supported (e.g. Page Down for scrolling) ' }', ' }', '', ' if (ignoredCtrlCmdKeys.some(function(i) { return i === event.keyCode; })) {', ' if (event.ctrlKey || event.metaKey) {', ' return;', // we want some ctrl/cmd keys to be supported (e.g. Ctrl+C for copy) ' }', ' }', '', ' if (ignoredShiftKeys.some(function(i) { return i === event.keyCode; })) {', ' if (event.shiftKey) {', ' return;', // we want some shift keys to be supported (e.g. Shift+Tab for copy) ' }', ' }', '', ' event.preventDefault();', // very important to not get duplicate actions when this one bubbles up! '', ' var fakeEvent = document.createEvent("KeyboardEvent");', // create a keyboard event ' Object.defineProperty(fakeEvent, "keyCode", {', // we need to set some properties that Chrome wants ' get : function() {', ' return event.keyCode;', ' }', ' });', ' Object.defineProperty(fakeEvent, "which", {', ' get : function() {', ' return event.keyCode;', ' }', ' });', ' Object.defineProperty(fakeEvent, "target", {', ' get : function() {', ' return window && window.parent.document.body;', ' }', ' });', '', ' fakeEvent.initKeyboardEvent("keydown", true, true, document.defaultView, null, null, event.ctrlKey, event.altKey, event.shiftKey, event.metaKey);', // the API shape of this method is not clear to me, but it works ;) '', ' window.parent.document.dispatchEvent(fakeEvent);', // dispatch the event onto the parent ' } catch (error) {}', '});', // disable dropping into iframe! 'window.document.addEventListener("dragover", function (e) {', ' e.preventDefault();', '});', 'window.document.addEventListener("drop", function (e) {', ' e.preventDefault();', '});', 'window.document.body.addEventListener("dragover", function (e) {', ' e.preventDefault();', '});', 'window.document.body.addEventListener("drop", function (e) {', ' e.preventDefault();', '});' ]; export function defaultHtml() { let all = [ '<html><head></head><body><script>', ...scriptSource, '</script></body></html>', ]; return all.join('\n'); } const defaultLightScrollbarStyle = [ '::-webkit-scrollbar-thumb {', ' background-color: rgba(100, 100, 100, 0.4);', '}', '::-webkit-scrollbar-thumb:hover {', ' background-color: rgba(100, 100, 100, 0.7);', '}', '::-webkit-scrollbar-thumb:active {', ' background-color: rgba(0, 0, 0, 0.6);', '}' ].join('\n'); const defaultDarkScrollbarStyle = [ '::-webkit-scrollbar-thumb {', ' background-color: rgba(121, 121, 121, 0.4);', '}', '::-webkit-scrollbar-thumb:hover {', ' background-color: rgba(100, 100, 100, 0.7);', '}', '::-webkit-scrollbar-thumb:active {', ' background-color: rgba(85, 85, 85, 0.8);', '}' ].join('\n') export function defaultStyle(element: HTMLElement, themeId: string): HTMLStyleElement { const styles = window.getComputedStyle(element); const styleElement = document.createElement('style'); styleElement.innerHTML = `* { color: ${styles.color}; background: ${styles.background}; font-family: ${styles.fontFamily}; font-size: ${styles.fontSize}; } img { max-width: 100%; max-height: 100%; } a:focus, input:focus, select:focus, textarea:focus { outline: 1px solid -webkit-focus-ring-color; outline-offset: -1px; } ::-webkit-scrollbar { width: 14px; height: 14px; } ${isLightTheme(themeId) ? defaultLightScrollbarStyle : defaultDarkScrollbarStyle}`; return styleElement; } }
src/vs/workbench/parts/html/browser/htmlPreviewPart.ts
1
https://github.com/microsoft/vscode/commit/8435ddcf464fd995936ff6f877ff4744dc3ca2b6
[ 0.9981840252876282, 0.037724629044532776, 0.0001655766536714509, 0.00017496115469839424, 0.17103339731693268 ]
{ "id": 7, "code_window": [ "\t\t\t\tthis._modelChangeUnbind = this._model.addListener(EventType.ModelContentChanged2, () => this._updateIFrameContent());\n", "\t\t\t\tthis._updateIFrameContent();\n", "\t\t\t} else {\n", "\t\t\t\tthis._modelChangeUnbind = cAll(this._modelChangeUnbind);\n", "\t\t\t}\n", "\t\t})\n", "\t}\n", "\n", "\tpublic changePosition(position: Position): void {\n", "\t\tsuper.changePosition(position);\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t});\n" ], "file_path": "src/vs/workbench/parts/html/browser/htmlPreviewPart.ts", "type": "replace", "edit_start_line_idx": 115 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import URI from './utils/uri'; import Parser = require('./jsonParser'); import SchemaService = require('./jsonSchemaService'); import JsonSchema = require('./json-toolbox/jsonSchema'); import nls = require('./utils/nls'); import {IJSONWorkerContribution} from './jsonContributions'; import {CompletionItem, CompletionItemKind, CompletionList, CompletionOptions, ITextDocument, TextDocumentIdentifier, TextDocumentPosition, Range, TextEdit} from 'vscode-languageserver'; export interface ISuggestionsCollector { add(suggestion: CompletionItem): void; error(message:string): void; setAsIncomplete(): void; } export class JSONCompletion { private schemaService: SchemaService.IJSONSchemaService; private contributions: IJSONWorkerContribution[]; constructor(schemaService: SchemaService.IJSONSchemaService, contributions: IJSONWorkerContribution[] = []) { this.schemaService = schemaService; this.contributions = contributions; } public doSuggest(document: ITextDocument, textDocumentPosition: TextDocumentPosition, doc: Parser.JSONDocument): Thenable<CompletionList> { let offset = document.offsetAt(textDocumentPosition.position); let node = doc.getNodeFromOffsetEndInclusive(offset); let currentWord = this.getCurrentWord(document, offset); let overwriteRange = null; let result: CompletionList = { items: [], isIncomplete: false } if (node && (node.type === 'string' || node.type === 'number' || node.type === 'boolean' || node.type === 'null')) { overwriteRange = Range.create(document.positionAt(node.start), document.positionAt(node.end)); } else { overwriteRange = Range.create(document.positionAt(offset - currentWord.length), textDocumentPosition.position); } let proposed: { [key: string]: boolean } = {}; let collector: ISuggestionsCollector = { add: (suggestion: CompletionItem) => { if (!proposed[suggestion.label]) { proposed[suggestion.label] = true; if (overwriteRange) { suggestion.textEdit = TextEdit.replace(overwriteRange, suggestion.insertText); } result.items.push(suggestion); } }, setAsIncomplete: () => { result.isIncomplete = true; }, error: (message: string) => { console.log(message); } }; return this.schemaService.getSchemaForResource(textDocumentPosition.uri, doc).then((schema) => { let collectionPromises: Thenable<any>[] = []; let addValue = true; let currentKey = ''; let currentProperty: Parser.PropertyASTNode = null; if (node) { if (node.type === 'string') { let stringNode = <Parser.StringASTNode>node; if (stringNode.isKey) { addValue = !(node.parent && ((<Parser.PropertyASTNode>node.parent).value)); currentProperty = node.parent ? <Parser.PropertyASTNode>node.parent : null; currentKey = document.getText().substring(node.start + 1, node.end - 1); if (node.parent) { node = node.parent.parent; } } } } // proposals for properties if (node && node.type === 'object') { // don't suggest keys when the cursor is just before the opening curly brace if (node.start === offset) { return result; } // don't suggest properties that are already present let properties = (<Parser.ObjectASTNode>node).properties; properties.forEach(p => { if (!currentProperty || currentProperty !== p) { proposed[p.key.value] = true; } }); let isLast = properties.length === 0 || offset >= properties[properties.length - 1].start; if (schema) { // property proposals with schema this.getPropertySuggestions(schema, doc, node, addValue, isLast, collector); } else { // property proposals without schema this.getSchemaLessPropertySuggestions(doc, node, currentKey, currentWord, isLast, collector); } let location = node.getNodeLocation(); this.contributions.forEach((contribution) => { let collectPromise = contribution.collectPropertySuggestions(textDocumentPosition.uri, location, currentWord, addValue, isLast, collector); if (collectPromise) { collectionPromises.push(collectPromise); } }); } // proposals for values if (node && (node.type === 'string' || node.type === 'number' || node.type === 'boolean' || node.type === 'null')) { node = node.parent; } if (schema) { // value proposals with schema this.getValueSuggestions(schema, doc, node, offset, collector); } else { // value proposals without schema this.getSchemaLessValueSuggestions(doc, node, offset, document, collector); } if (!node) { this.contributions.forEach((contribution) => { let collectPromise = contribution.collectDefaultSuggestions(textDocumentPosition.uri, collector); if (collectPromise) { collectionPromises.push(collectPromise); } }); } else { if ((node.type === 'property') && offset > (<Parser.PropertyASTNode> node).colonOffset) { let parentKey = (<Parser.PropertyASTNode>node).key.value; let valueNode = (<Parser.PropertyASTNode> node).value; if (!valueNode || offset <= valueNode.end) { let location = node.parent.getNodeLocation(); this.contributions.forEach((contribution) => { let collectPromise = contribution.collectValueSuggestions(textDocumentPosition.uri, location, parentKey, collector); if (collectPromise) { collectionPromises.push(collectPromise); } }); } } } return Promise.all(collectionPromises).then(() => result ); }); } private getPropertySuggestions(schema: SchemaService.ResolvedSchema, doc: Parser.JSONDocument, node: Parser.ASTNode, addValue: boolean, isLast: boolean, collector: ISuggestionsCollector): void { let matchingSchemas: Parser.IApplicableSchema[] = []; doc.validate(schema.schema, matchingSchemas, node.start); matchingSchemas.forEach((s) => { if (s.node === node && !s.inverted) { let schemaProperties = s.schema.properties; if (schemaProperties) { Object.keys(schemaProperties).forEach((key: string) => { let propertySchema = schemaProperties[key]; collector.add({ kind: CompletionItemKind.Property, label: key, insertText: this.getSnippetForProperty(key, propertySchema, addValue, isLast), documentation: propertySchema.description || '' }); }); } } }); } private getSchemaLessPropertySuggestions(doc: Parser.JSONDocument, node: Parser.ASTNode, currentKey: string, currentWord: string, isLast: boolean, collector: ISuggestionsCollector): void { let collectSuggestionsForSimilarObject = (obj: Parser.ObjectASTNode) => { obj.properties.forEach((p) => { let key = p.key.value; collector.add({ kind: CompletionItemKind.Property, label: key, insertText: this.getSnippetForSimilarProperty(key, p.value), documentation: '' }); }); }; if (node.parent) { if (node.parent.type === 'property') { // if the object is a property value, check the tree for other objects that hang under a property of the same name let parentKey = (<Parser.PropertyASTNode>node.parent).key.value; doc.visit((n) => { if (n.type === 'property' && (<Parser.PropertyASTNode>n).key.value === parentKey && (<Parser.PropertyASTNode>n).value && (<Parser.PropertyASTNode>n).value.type === 'object') { collectSuggestionsForSimilarObject(<Parser.ObjectASTNode>(<Parser.PropertyASTNode>n).value); } return true; }); } else if (node.parent.type === 'array') { // if the object is in an array, use all other array elements as similar objects (<Parser.ArrayASTNode>node.parent).items.forEach((n) => { if (n.type === 'object' && n !== node) { collectSuggestionsForSimilarObject(<Parser.ObjectASTNode>n); } }); } } if (!currentKey && currentWord.length > 0) { collector.add({ kind: CompletionItemKind.Property, label: JSON.stringify(currentWord), insertText: this.getSnippetForProperty(currentWord, null, true, isLast), documentation: '' }); } } private getSchemaLessValueSuggestions(doc: Parser.JSONDocument, node: Parser.ASTNode, offset: number, document: ITextDocument, collector: ISuggestionsCollector): void { let collectSuggestionsForValues = (value: Parser.ASTNode) => { if (!value.contains(offset)) { let content = this.getMatchingSnippet(value, document); collector.add({ kind: this.getSuggestionKind(value.type), label: content, insertText: content, documentation: '' }); } if (value.type === 'boolean') { this.addBooleanSuggestion(!value.getValue(), collector); } }; if (!node) { collector.add({ kind: this.getSuggestionKind('object'), label: 'Empty object', insertText: '{\n\t{{}}\n}', documentation: '' }); collector.add({ kind: this.getSuggestionKind('array'), label: 'Empty array', insertText: '[\n\t{{}}\n]', documentation: '' }); } else { if (node.type === 'property' && offset > (<Parser.PropertyASTNode>node).colonOffset) { let valueNode = (<Parser.PropertyASTNode>node).value; if (valueNode && offset > valueNode.end) { return; } // suggest values at the same key let parentKey = (<Parser.PropertyASTNode>node).key.value; doc.visit((n) => { if (n.type === 'property' && (<Parser.PropertyASTNode>n).key.value === parentKey && (<Parser.PropertyASTNode>n).value) { collectSuggestionsForValues((<Parser.PropertyASTNode>n).value); } return true; }); } if (node.type === 'array') { if (node.parent && node.parent.type === 'property') { // suggest items of an array at the same key let parentKey = (<Parser.PropertyASTNode>node.parent).key.value; doc.visit((n) => { if (n.type === 'property' && (<Parser.PropertyASTNode>n).key.value === parentKey && (<Parser.PropertyASTNode>n).value && (<Parser.PropertyASTNode>n).value.type === 'array') { ((<Parser.ArrayASTNode>(<Parser.PropertyASTNode>n).value).items).forEach((n) => { collectSuggestionsForValues(<Parser.ObjectASTNode>n); }); } return true; }); } else { // suggest items in the same array (<Parser.ArrayASTNode>node).items.forEach((n) => { collectSuggestionsForValues(<Parser.ObjectASTNode>n); }); } } } } private getValueSuggestions(schema: SchemaService.ResolvedSchema, doc: Parser.JSONDocument, node: Parser.ASTNode, offset: number, collector: ISuggestionsCollector): void { if (!node) { this.addDefaultSuggestion(schema.schema, collector); } else { let parentKey: string = null; if (node && (node.type === 'property') && offset > (<Parser.PropertyASTNode>node).colonOffset) { let valueNode = (<Parser.PropertyASTNode>node).value; if (valueNode && offset > valueNode.end) { return; // we are past the value node } parentKey = (<Parser.PropertyASTNode>node).key.value; node = node.parent; } if (node && (parentKey !== null || node.type === 'array')) { let matchingSchemas: Parser.IApplicableSchema[] = []; doc.validate(schema.schema, matchingSchemas, node.start); matchingSchemas.forEach((s) => { if (s.node === node && !s.inverted && s.schema) { if (s.schema.items) { this.addDefaultSuggestion(s.schema.items, collector); this.addEnumSuggestion(s.schema.items, collector); } if (s.schema.properties) { let propertySchema = s.schema.properties[parentKey]; if (propertySchema) { this.addDefaultSuggestion(propertySchema, collector); this.addEnumSuggestion(propertySchema, collector); } } } }); } } } private addBooleanSuggestion(value: boolean, collector: ISuggestionsCollector): void { collector.add({ kind: this.getSuggestionKind('boolean'), label: value ? 'true' : 'false', insertText: this.getTextForValue(value), documentation: '' }); } private addEnumSuggestion(schema: JsonSchema.IJSONSchema, collector: ISuggestionsCollector): void { if (Array.isArray(schema.enum)) { schema.enum.forEach((enm) => collector.add({ kind: this.getSuggestionKind(schema.type), label: this.getLabelForValue(enm), insertText: this.getTextForValue(enm), documentation: '' })); } else if (schema.type === 'boolean') { this.addBooleanSuggestion(true, collector); this.addBooleanSuggestion(false, collector); } if (Array.isArray(schema.allOf)) { schema.allOf.forEach((s) => this.addEnumSuggestion(s, collector)); } if (Array.isArray(schema.anyOf)) { schema.anyOf.forEach((s) => this.addEnumSuggestion(s, collector)); } if (Array.isArray(schema.oneOf)) { schema.oneOf.forEach((s) => this.addEnumSuggestion(s, collector)); } } private addDefaultSuggestion(schema: JsonSchema.IJSONSchema, collector: ISuggestionsCollector): void { if (schema.default) { collector.add({ kind: this.getSuggestionKind(schema.type), label: this.getLabelForValue(schema.default), insertText: this.getTextForValue(schema.default), detail: nls.localize('json.suggest.default', 'Default value'), }); } if (Array.isArray(schema.allOf)) { schema.allOf.forEach((s) => this.addDefaultSuggestion(s, collector)); } if (Array.isArray(schema.anyOf)) { schema.anyOf.forEach((s) => this.addDefaultSuggestion(s, collector)); } if (Array.isArray(schema.oneOf)) { schema.oneOf.forEach((s) => this.addDefaultSuggestion(s, collector)); } } private getLabelForValue(value: any): string { let label = JSON.stringify(value); label = label.replace('{{', '').replace('}}', ''); if (label.length > 57) { return label.substr(0, 57).trim() + '...'; } return label; } private getTextForValue(value: any): string { return JSON.stringify(value, null, '\t'); } private getSnippetForValue(value: any): string { let snippet = JSON.stringify(value, null, '\t'); switch (typeof value) { case 'object': if (value === null) { return '{{null}}'; } return snippet; case 'string': return '"{{' + snippet.substr(1, snippet.length - 2) + '}}"'; case 'number': case 'boolean': return '{{' + snippet + '}}'; } return snippet; } private getSuggestionKind(type: any): CompletionItemKind { if (Array.isArray(type)) { let array = <any[]>type; type = array.length > 0 ? array[0] : null; } if (!type) { return CompletionItemKind.Text; } switch (type) { case 'string': return CompletionItemKind.Text; case 'object': return CompletionItemKind.Module; case 'property': return CompletionItemKind.Property; default: return CompletionItemKind.Value } } private getMatchingSnippet(node: Parser.ASTNode, document: ITextDocument): string { switch (node.type) { case 'array': return '[]'; case 'object': return '{}'; default: let content = document.getText().substr(node.start, node.end - node.start); return content; } } private getSnippetForProperty(key: string, propertySchema: JsonSchema.IJSONSchema, addValue: boolean, isLast: boolean): string { let result = '"' + key + '"'; if (!addValue) { return result; } result += ': '; if (propertySchema) { let defaultVal = propertySchema.default; if (typeof defaultVal !== 'undefined') { result = result + this.getSnippetForValue(defaultVal); } else if (propertySchema.enum && propertySchema.enum.length > 0) { result = result + this.getSnippetForValue(propertySchema.enum[0]); } else { switch (propertySchema.type) { case 'boolean': result += '{{false}}'; break; case 'string': result += '"{{}}"'; break; case 'object': result += '{\n\t{{}}\n}'; break; case 'array': result += '[\n\t{{}}\n]'; break; case 'number': result += '{{0}}'; break; case 'null': result += '{{null}}'; break; default: return result; } } } else { result += '{{0}}'; } if (!isLast) { result += ','; } return result; } private getSnippetForSimilarProperty(key: string, templateValue: Parser.ASTNode): string { return '"' + key + '"'; } private getCurrentWord(document: ITextDocument, offset: number) { var i = offset - 1; var text = document.getText(); while (i >= 0 && ' \t\n\r\v":{[,'.indexOf(text.charAt(i)) === -1) { i--; } return text.substring(i+1, offset); } }
extensions/json/server/src/jsonCompletion.ts
0
https://github.com/microsoft/vscode/commit/8435ddcf464fd995936ff6f877ff4744dc3ca2b6
[ 0.0001791179383872077, 0.00017310006660409272, 0.00016659018001519144, 0.00017355506133753806, 0.000002495000444469042 ]
{ "id": 7, "code_window": [ "\t\t\t\tthis._modelChangeUnbind = this._model.addListener(EventType.ModelContentChanged2, () => this._updateIFrameContent());\n", "\t\t\t\tthis._updateIFrameContent();\n", "\t\t\t} else {\n", "\t\t\t\tthis._modelChangeUnbind = cAll(this._modelChangeUnbind);\n", "\t\t\t}\n", "\t\t})\n", "\t}\n", "\n", "\tpublic changePosition(position: Position): void {\n", "\t\tsuper.changePosition(position);\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t});\n" ], "file_path": "src/vs/workbench/parts/html/browser/htmlPreviewPart.ts", "type": "replace", "edit_start_line_idx": 115 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ .git-viewlet > .disabled-view { padding: 0 20px 0 20px; }
src/vs/workbench/parts/git/browser/views/disabled/disabledView.css
0
https://github.com/microsoft/vscode/commit/8435ddcf464fd995936ff6f877ff4744dc3ca2b6
[ 0.00017787313845474273, 0.00017787313845474273, 0.00017787313845474273, 0.00017787313845474273, 0 ]
{ "id": 7, "code_window": [ "\t\t\t\tthis._modelChangeUnbind = this._model.addListener(EventType.ModelContentChanged2, () => this._updateIFrameContent());\n", "\t\t\t\tthis._updateIFrameContent();\n", "\t\t\t} else {\n", "\t\t\t\tthis._modelChangeUnbind = cAll(this._modelChangeUnbind);\n", "\t\t\t}\n", "\t\t})\n", "\t}\n", "\n", "\tpublic changePosition(position: Position): void {\n", "\t\tsuper.changePosition(position);\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t});\n" ], "file_path": "src/vs/workbench/parts/html/browser/htmlPreviewPart.ts", "type": "replace", "edit_start_line_idx": 115 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import {EventEmitter, IEventEmitter, EmitterEvent, IEmitterEvent, ListenerUnbind} from 'vs/base/common/eventEmitter'; import Strings = require('vs/base/common/strings'); import {Selection} from 'vs/editor/common/core/selection'; import {Range} from 'vs/editor/common/core/range'; import {ViewModelDecorations} from 'vs/editor/common/viewModel/viewModelDecorations'; import {ViewModelCursors} from 'vs/editor/common/viewModel/viewModelCursors'; import {IDisposable, disposeAll} from 'vs/base/common/lifecycle'; import {Position} from 'vs/editor/common/core/position'; import EditorCommon = require('vs/editor/common/editorCommon'); export interface ILinesCollection { setTabSize(newTabSize:number, emit:(evenType:string, payload:any)=>void): boolean; setWrappingColumn(newWrappingColumn:number, columnsForFullWidthChar:number, emit:(evenType:string, payload:any)=>void): boolean; setWrappingIndent(newWrappingIndent:EditorCommon.WrappingIndent, emit:(evenType:string, payload:any)=>void): boolean; onModelFlushed(versionId:number, emit:(evenType:string, payload:any)=>void): void; onModelLinesDeleted(versionId:number, fromLineNumber:number, toLineNumber:number, emit:(evenType:string, payload:any)=>void): void; onModelLinesInserted(versionId:number, fromLineNumber:number, toLineNumber:number, text:string[], emit:(evenType:string, payload:any)=>void): void; onModelLineChanged(versionId:number, lineNumber:number, newText:string, emit:(evenType:string, payload:any)=>void): boolean; getOutputLineCount(): number; getOutputLineContent(outputLineNumber:number): string; getOutputLineMinColumn(outputLineNumber:number): number; getOutputLineMaxColumn(outputLineNumber:number): number; getOutputLineTokens(outputLineNumber:number, inaccurateTokensAcceptable:boolean): EditorCommon.IViewLineTokens; convertOutputPositionToInputPosition(viewLineNumber:number, viewColumn:number): EditorCommon.IEditorPosition; convertInputPositionToOutputPosition(inputLineNumber:number, inputColumn:number): EditorCommon.IEditorPosition; } export class ViewModel extends EventEmitter implements EditorCommon.IViewModel { private editorId:number; private configuration:EditorCommon.IConfiguration; private model:EditorCommon.IModel; private listenersToRemove:ListenerUnbind[]; private _toDispose: IDisposable[]; private lines:ILinesCollection; private decorations:ViewModelDecorations; private cursors:ViewModelCursors; private shouldForceTokenization:boolean; private getCurrentCenteredModelRange:()=>EditorCommon.IEditorRange; constructor(lines:ILinesCollection, editorId:number, configuration:EditorCommon.IConfiguration, model:EditorCommon.IModel, getCurrentCenteredModelRange:()=>EditorCommon.IEditorRange) { super(); this.lines = lines; this.editorId = editorId; this.configuration = configuration; this.model = model; this.getCurrentCenteredModelRange = getCurrentCenteredModelRange; this.decorations = new ViewModelDecorations(this.editorId, this.configuration, { convertModelRangeToViewRange: (modelRange:EditorCommon.IRange, isWholeLine:boolean) => { if (isWholeLine) { return this.convertWholeLineModelRangeToViewRange(modelRange); } return this.convertModelRangeToViewRange(modelRange); } }); this.decorations.reset(this.model); this.cursors = new ViewModelCursors(this.configuration, this); this._updateShouldForceTokenization(); this.listenersToRemove = []; this._toDispose = []; this.listenersToRemove.push(this.model.addBulkListener((events:IEmitterEvent[]) => this.onEvents(events))); this._toDispose.push(this.configuration.onDidChange((e) => { this.onEvents([new EmitterEvent(EditorCommon.EventType.ConfigurationChanged, e)]); })); } public dispose(): void { this.listenersToRemove.forEach((element) => { element(); }); this._toDispose = disposeAll(this._toDispose); this.listenersToRemove = []; this.decorations.dispose(); this.decorations = null; this.lines = null; this.configuration = null; this.model = null; } private _updateShouldForceTokenization(): void { this.shouldForceTokenization = (this.lines.getOutputLineCount() <= this.configuration.editor.forcedTokenizationBoundary); } private _onTabSizeChange(newTabSize:number): boolean { var lineMappingChanged = this.lines.setTabSize(newTabSize, (eventType:string, payload:any) => this.emit(eventType, payload)); if (lineMappingChanged) { this.emit(EditorCommon.ViewEventNames.LineMappingChangedEvent); this.decorations.onLineMappingChanged((eventType:string, payload:any) => this.emit(eventType, payload)); this.cursors.onLineMappingChanged((eventType: string, payload: any) => this.emit(eventType, payload)); this._updateShouldForceTokenization(); } return lineMappingChanged; } private _onWrappingIndentChange(newWrappingIndent:string): boolean { var lineMappingChanged = this.lines.setWrappingIndent(EditorCommon.wrappingIndentFromString(newWrappingIndent), (eventType:string, payload:any) => this.emit(eventType, payload)); if (lineMappingChanged) { this.emit(EditorCommon.ViewEventNames.LineMappingChangedEvent); this.decorations.onLineMappingChanged((eventType:string, payload:any) => this.emit(eventType, payload)); this.cursors.onLineMappingChanged((eventType: string, payload: any) => this.emit(eventType, payload)); this._updateShouldForceTokenization(); } return lineMappingChanged; } private _restoreCenteredModelRange(range:EditorCommon.IEditorRange): void { // modelLine -> viewLine var newCenteredViewRange = this.convertModelRangeToViewRange(range); // Send a reveal event to restore the centered content var restoreRevealEvent:EditorCommon.IViewRevealRangeEvent = { range: newCenteredViewRange, verticalType: EditorCommon.VerticalRevealType.Center, revealHorizontal: false }; this.emit(EditorCommon.ViewEventNames.RevealRangeEvent, restoreRevealEvent); } private _onWrappingColumnChange(newWrappingColumn:number, columnsForFullWidthChar:number): boolean { let lineMappingChanged = this.lines.setWrappingColumn(newWrappingColumn, columnsForFullWidthChar, (eventType:string, payload:any) => this.emit(eventType, payload)); if (lineMappingChanged) { this.emit(EditorCommon.ViewEventNames.LineMappingChangedEvent); this.decorations.onLineMappingChanged((eventType:string, payload:any) => this.emit(eventType, payload)); this.cursors.onLineMappingChanged((eventType: string, payload: any) => this.emit(eventType, payload)); this._updateShouldForceTokenization(); } return lineMappingChanged; } public addEventSource(eventSource:IEventEmitter): void { this.listenersToRemove.push(eventSource.addBulkListener((events:IEmitterEvent[]) => this.onEvents(events))); } private onEvents(events:IEmitterEvent[]): void { this.deferredEmit(() => { let hasContentChange = events.some((e) => e.getType() === EditorCommon.EventType.ModelContentChanged), previousCenteredModelRange:EditorCommon.IEditorRange; if (!hasContentChange) { // We can only convert the current centered view range to the current centered model range if the model has no changes. previousCenteredModelRange = this.getCurrentCenteredModelRange(); } let i:number, len:number, e: IEmitterEvent, data:any, shouldUpdateForceTokenization = false, modelContentChangedEvent:EditorCommon.IModelContentChangedEvent, hadOtherModelChange = false, hadModelLineChangeThatChangedLineMapping = false, revealPreviousCenteredModelRange = false; for (i = 0, len = events.length; i < len; i++) { e = events[i]; data = e.getData(); switch (e.getType()) { case EditorCommon.EventType.ModelContentChanged: modelContentChangedEvent = <EditorCommon.IModelContentChangedEvent>data; switch (modelContentChangedEvent.changeType) { case EditorCommon.EventType.ModelContentChangedFlush: this.onModelFlushed(<EditorCommon.IModelContentChangedFlushEvent>modelContentChangedEvent); hadOtherModelChange = true; break; case EditorCommon.EventType.ModelContentChangedLinesDeleted: this.onModelLinesDeleted(<EditorCommon.IModelContentChangedLinesDeletedEvent>modelContentChangedEvent); hadOtherModelChange = true; break; case EditorCommon.EventType.ModelContentChangedLinesInserted: this.onModelLinesInserted(<EditorCommon.IModelContentChangedLinesInsertedEvent>modelContentChangedEvent); hadOtherModelChange = true; break; case EditorCommon.EventType.ModelContentChangedLineChanged: hadModelLineChangeThatChangedLineMapping = this.onModelLineChanged(<EditorCommon.IModelContentChangedLineChangedEvent>modelContentChangedEvent); break; default: console.info('ViewModel received unknown event: '); console.info(e); } shouldUpdateForceTokenization = true; break; case EditorCommon.EventType.ModelTokensChanged: this.onModelTokensChanged(<EditorCommon.IModelTokensChangedEvent>data); break; case EditorCommon.EventType.ModelModeChanged: // That's ok, a model tokens changed event will follow shortly break; case EditorCommon.EventType.ModelModeSupportChanged: // That's ok, no work to do break; case EditorCommon.EventType.ModelPropertiesChanged: // Ignore break; case EditorCommon.EventType.ModelContentChanged2: // Ignore break; case EditorCommon.EventType.ModelDecorationsChanged: this.onModelDecorationsChanged(<EditorCommon.IModelDecorationsChangedEvent>data); break; case EditorCommon.EventType.ModelDispose: // Ignore, since the editor will take care of this and destroy the view shortly break; case EditorCommon.EventType.CursorPositionChanged: this.onCursorPositionChanged(<EditorCommon.ICursorPositionChangedEvent>data); break; case EditorCommon.EventType.CursorSelectionChanged: this.onCursorSelectionChanged(<EditorCommon.ICursorSelectionChangedEvent>data); break; case EditorCommon.EventType.CursorRevealRange: this.onCursorRevealRange(<EditorCommon.ICursorRevealRangeEvent>data); break; case EditorCommon.EventType.CursorScrollRequest: this.onCursorScrollRequest(<EditorCommon.ICursorScrollRequestEvent>data); break; case EditorCommon.EventType.ConfigurationChanged: revealPreviousCenteredModelRange = this._onTabSizeChange(this.configuration.getIndentationOptions().tabSize) || revealPreviousCenteredModelRange; revealPreviousCenteredModelRange = this._onWrappingIndentChange(this.configuration.editor.wrappingIndent) || revealPreviousCenteredModelRange; revealPreviousCenteredModelRange = this._onWrappingColumnChange(this.configuration.editor.wrappingInfo.wrappingColumn, this.configuration.editor.typicalFullwidthCharacterWidth / this.configuration.editor.typicalHalfwidthCharacterWidth) || revealPreviousCenteredModelRange; if ((<EditorCommon.IConfigurationChangedEvent>data).readOnly) { // Must read again all decorations due to readOnly filtering this.decorations.reset(this.model); var decorationsChangedEvent:EditorCommon.IViewDecorationsChangedEvent = { inlineDecorationsChanged: false }; this.emit(EditorCommon.ViewEventNames.DecorationsChangedEvent, decorationsChangedEvent); } this.emit(e.getType(), <EditorCommon.IConfigurationChangedEvent>data); break; default: console.info('View received unknown event: '); console.info(e); } } if (shouldUpdateForceTokenization) { this._updateShouldForceTokenization(); } if (!hadOtherModelChange && hadModelLineChangeThatChangedLineMapping) { this.emit(EditorCommon.ViewEventNames.LineMappingChangedEvent); this.decorations.onLineMappingChanged((eventType:string, payload:any) => this.emit(eventType, payload)); this.cursors.onLineMappingChanged((eventType: string, payload: any) => this.emit(eventType, payload)); this._updateShouldForceTokenization(); } if (revealPreviousCenteredModelRange && previousCenteredModelRange) { this._restoreCenteredModelRange(previousCenteredModelRange); } }); } // --- begin inbound event conversion private onModelFlushed(e:EditorCommon.IModelContentChangedFlushEvent): void { this.lines.onModelFlushed(e.versionId, (eventType:string, payload:any) => this.emit(eventType, payload)); this.decorations.reset(this.model); } private onModelDecorationsChanged(e:EditorCommon.IModelDecorationsChangedEvent): void { this.decorations.onModelDecorationsChanged(e, (eventType:string, payload:any) => this.emit(eventType, payload)); } private onModelLinesDeleted(e:EditorCommon.IModelContentChangedLinesDeletedEvent): void { this.lines.onModelLinesDeleted(e.versionId, e.fromLineNumber, e.toLineNumber, (eventType:string, payload:any) => this.emit(eventType, payload)); } private onModelTokensChanged(e:EditorCommon.IModelTokensChangedEvent): void { var viewStartLineNumber = this.convertModelPositionToViewPosition(e.fromLineNumber, 1).lineNumber; var viewEndLineNumber = this.convertModelPositionToViewPosition(e.toLineNumber, this.model.getLineMaxColumn(e.toLineNumber)).lineNumber; var e:EditorCommon.IViewTokensChangedEvent = { fromLineNumber: viewStartLineNumber, toLineNumber: viewEndLineNumber }; this.emit(EditorCommon.ViewEventNames.TokensChangedEvent, e); } private onModelLineChanged(e:EditorCommon.IModelContentChangedLineChangedEvent): boolean { var lineMappingChanged = this.lines.onModelLineChanged(e.versionId, e.lineNumber, e.detail, (eventType:string, payload:any) => this.emit(eventType, payload)); return lineMappingChanged; } private onModelLinesInserted(e:EditorCommon.IModelContentChangedLinesInsertedEvent): void { this.lines.onModelLinesInserted(e.versionId, e.fromLineNumber, e.toLineNumber, e.detail.split('\n'), (eventType:string, payload:any) => this.emit(eventType, payload)); } public validateViewRange(viewStartLineNumber:number, viewStartColumn:number, viewEndLineNumber:number, viewEndColumn:number, modelRange:EditorCommon.IEditorRange): EditorCommon.IEditorRange { var validViewStart = this.validateViewPosition(viewStartColumn, viewStartColumn, modelRange.getStartPosition()); var validViewEnd = this.validateViewPosition(viewEndLineNumber, viewEndColumn, modelRange.getEndPosition()); return new Range(validViewStart.lineNumber, validViewStart.column, validViewEnd.lineNumber, validViewEnd.column); } public validateViewPosition(viewLineNumber:number, viewColumn:number, modelPosition:EditorCommon.IEditorPosition): EditorCommon.IEditorPosition { if (viewLineNumber < 1) { viewLineNumber = 1; } var lineCount = this.getLineCount(); if (viewLineNumber > lineCount) { viewLineNumber = lineCount; } var viewMinColumn = this.getLineMinColumn(viewLineNumber); var viewMaxColumn = this.getLineMaxColumn(viewLineNumber); if (viewColumn < viewMinColumn) { viewColumn = viewMinColumn; } if (viewColumn > viewMaxColumn) { viewColumn = viewMaxColumn; } var computedModelPosition = this.convertViewPositionToModelPosition(viewLineNumber, viewColumn); if (computedModelPosition.equals(modelPosition)) { return new Position(viewLineNumber, viewColumn); } return this.convertModelPositionToViewPosition(modelPosition.lineNumber, modelPosition.column); } public validateViewSelection(viewSelection:EditorCommon.IEditorSelection, modelSelection:EditorCommon.IEditorSelection): EditorCommon.IEditorSelection { let modelSelectionStart = new Position(modelSelection.selectionStartLineNumber, modelSelection.selectionStartColumn); let modelPosition = new Position(modelSelection.positionLineNumber, modelSelection.positionColumn); let viewSelectionStart = this.validateViewPosition(viewSelection.selectionStartLineNumber, viewSelection.selectionStartColumn, modelSelectionStart); let viewPosition = this.validateViewPosition(viewSelection.positionLineNumber, viewSelection.positionColumn, modelPosition); return new Selection(viewSelectionStart.lineNumber, viewSelectionStart.column, viewPosition.lineNumber, viewPosition.column); } private onCursorPositionChanged(e:EditorCommon.ICursorPositionChangedEvent): void { this.cursors.onCursorPositionChanged(e, (eventType:string, payload:any) => this.emit(eventType, payload)); } private onCursorSelectionChanged(e:EditorCommon.ICursorSelectionChangedEvent): void { this.cursors.onCursorSelectionChanged(e, (eventType:string, payload:any) => this.emit(eventType, payload)); } private onCursorRevealRange(e:EditorCommon.ICursorRevealRangeEvent): void { this.cursors.onCursorRevealRange(e, (eventType:string, payload:any) => this.emit(eventType, payload)); } private onCursorScrollRequest(e:EditorCommon.ICursorScrollRequestEvent): void { this.cursors.onCursorScrollRequest(e, (eventType:string, payload:any) => this.emit(eventType, payload)); } // --- end inbound event conversion public getLineCount(): number { return this.lines.getOutputLineCount(); } public getLineContent(lineNumber:number): string { return this.lines.getOutputLineContent(lineNumber); } public getLineMinColumn(lineNumber:number): number { return this.lines.getOutputLineMinColumn(lineNumber); } public getLineMaxColumn(lineNumber:number): number { return this.lines.getOutputLineMaxColumn(lineNumber); } public getLineFirstNonWhitespaceColumn(lineNumber: number): number { var result = Strings.firstNonWhitespaceIndex(this.getLineContent(lineNumber)); if (result === -1) { return 0; } return result + 1; } public getLineLastNonWhitespaceColumn(lineNumber: number): number { var result = Strings.lastNonWhitespaceIndex(this.getLineContent(lineNumber)); if (result === -1) { return 0; } return result + 2; } public getLineTokens(lineNumber:number): EditorCommon.IViewLineTokens { return this.lines.getOutputLineTokens(lineNumber, !this.shouldForceTokenization); } public getLineRenderLineNumber(viewLineNumber:number): string { var modelPosition = this.convertViewPositionToModelPosition(viewLineNumber, 1); if (modelPosition.column !== 1) { return ''; } var modelLineNumber = modelPosition.lineNumber; if (typeof this.configuration.editor.lineNumbers === 'function') { return this.configuration.editor.lineNumbers(modelLineNumber); } return modelLineNumber.toString(); } public getDecorationsResolver(startLineNumber:number, endLineNumber:number): EditorCommon.IViewModelDecorationsResolver { return this.decorations.getDecorationsResolver(startLineNumber, endLineNumber); } public getAllDecorations(): EditorCommon.IModelDecoration[] { return this.decorations.getAllDecorations(); } public getEOL(): string { return this.model.getEOL(); } public getValueInRange(range:EditorCommon.IRange, eol:EditorCommon.EndOfLinePreference): string { var modelRange = this.convertViewRangeToModelRange(range); return this.model.getValueInRange(modelRange, eol); } public getModelLineContent(modelLineNumber:number): string { return this.model.getLineContent(modelLineNumber); } public getSelections(): EditorCommon.IEditorSelection[] { return this.cursors.getSelections(); } public getModelLineMaxColumn(modelLineNumber:number): number { return this.model.getLineMaxColumn(modelLineNumber); } public validateModelPosition(position:EditorCommon.IPosition): EditorCommon.IEditorPosition { return this.model.validatePosition(position); } public convertViewPositionToModelPosition(viewLineNumber:number, viewColumn:number): EditorCommon.IEditorPosition { return this.lines.convertOutputPositionToInputPosition(viewLineNumber, viewColumn); } public convertViewRangeToModelRange(viewRange:EditorCommon.IRange): EditorCommon.IEditorRange { var start = this.convertViewPositionToModelPosition(viewRange.startLineNumber, viewRange.startColumn); var end = this.convertViewPositionToModelPosition(viewRange.endLineNumber, viewRange.endColumn); return new Range(start.lineNumber, start.column, end.lineNumber, end.column); } public convertModelPositionToViewPosition(modelLineNumber:number, modelColumn:number): EditorCommon.IEditorPosition { return this.lines.convertInputPositionToOutputPosition(modelLineNumber, modelColumn); } public convertModelSelectionToViewSelection(modelSelection:EditorCommon.IEditorSelection): EditorCommon.IEditorSelection { var selectionStart = this.convertModelPositionToViewPosition(modelSelection.selectionStartLineNumber, modelSelection.selectionStartColumn); var position = this.convertModelPositionToViewPosition(modelSelection.positionLineNumber, modelSelection.positionColumn); return new Selection(selectionStart.lineNumber, selectionStart.column, position.lineNumber, position.column); } public convertModelRangeToViewRange(modelRange:EditorCommon.IRange): EditorCommon.IEditorRange { var start = this.convertModelPositionToViewPosition(modelRange.startLineNumber, modelRange.startColumn); var end = this.convertModelPositionToViewPosition(modelRange.endLineNumber, modelRange.endColumn); return new Range(start.lineNumber, start.column, end.lineNumber, end.column); } public convertWholeLineModelRangeToViewRange(modelRange:EditorCommon.IRange): EditorCommon.IEditorRange { var start = this.convertModelPositionToViewPosition(modelRange.startLineNumber, 1); var end = this.convertModelPositionToViewPosition(modelRange.endLineNumber, this.model.getLineMaxColumn(modelRange.endLineNumber)); return new Range(start.lineNumber, start.column, end.lineNumber, end.column); } }
src/vs/editor/common/viewModel/viewModel.ts
0
https://github.com/microsoft/vscode/commit/8435ddcf464fd995936ff6f877ff4744dc3ca2b6
[ 0.0092909662052989, 0.0009674130124039948, 0.00016225159924943, 0.0001733932876959443, 0.002104935934767127 ]
{ "id": 8, "code_window": [ "\t\t}\n", "\n", "\t\treturn this._editorService.resolveEditorModel({ resource: (<HtmlInput>input).getResource() }).then(model => {\n", "\t\t\tif (model instanceof BaseTextEditorModel) {\n", "\t\t\t\tthis._model = model.textEditorModel\n", "\t\t\t}\n", "\n", "\t\t\tif (!this._model) {\n", "\t\t\t\treturn TPromise.wrapError<void>(localize('html.voidInput', \"Invalid editor input.\"));\n", "\t\t\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tthis._model = model.textEditorModel;\n" ], "file_path": "src/vs/workbench/parts/html/browser/htmlPreviewPart.ts", "type": "replace", "edit_start_line_idx": 141 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; // import 'vs/css!./media/iframeeditor'; import {localize} from 'vs/nls'; import {TPromise} from 'vs/base/common/winjs.base'; import {IModel, EventType} from 'vs/editor/common/editorCommon'; import {Dimension, Builder} from 'vs/base/browser/builder'; import {cAll} from 'vs/base/common/lifecycle'; import {EditorOptions, EditorInput} from 'vs/workbench/common/editor'; import {BaseEditor} from 'vs/workbench/browser/parts/editor/baseEditor'; import {Position} from 'vs/platform/editor/common/editor'; import {ITelemetryService} from 'vs/platform/telemetry/common/telemetry'; import {IStorageService, StorageEventType, StorageScope} from 'vs/platform/storage/common/storage'; import {IWorkbenchEditorService} from 'vs/workbench/services/editor/common/editorService'; import {BaseTextEditorModel} from 'vs/workbench/common/editor/textEditorModel'; import {Preferences} from 'vs/workbench/common/constants'; import {HtmlInput} from 'vs/workbench/parts/html/common/htmlInput'; import {isLightTheme} from 'vs/platform/theme/common/themes'; import {DEFAULT_THEME_ID} from 'vs/workbench/services/themes/common/themeService'; /** * An implementation of editor for showing HTML content in an IFrame by leveraging the IFrameEditorInput. */ export class HtmlPreviewPart extends BaseEditor { static ID: string = 'workbench.editor.htmlPreviewPart'; private _editorService: IWorkbenchEditorService; private _storageService: IStorageService; private _iFrameElement: HTMLIFrameElement; private _model: IModel; private _modelChangeUnbind: Function; private _lastModelVersion: number; private _themeChangeUnbind: Function; constructor( @ITelemetryService telemetryService: ITelemetryService, @IWorkbenchEditorService editorService: IWorkbenchEditorService, @IStorageService storageService: IStorageService ) { super(HtmlPreviewPart.ID, telemetryService); this._editorService = editorService; this._storageService = storageService; } dispose(): void { // remove from dome const element = this._iFrameElement.parentElement; element.parentElement.removeChild(element); // unhook from model this._modelChangeUnbind = cAll(this._modelChangeUnbind); this._model = undefined; this._themeChangeUnbind = cAll(this._themeChangeUnbind); } public createEditor(parent: Builder): void { // IFrame // this.iframeBuilder.removeProperty(IFrameEditor.RESOURCE_PROPERTY); this._iFrameElement = document.createElement('iframe'); this._iFrameElement.setAttribute('frameborder', '0'); this._iFrameElement.className = 'iframe'; // Container for IFrame const iFrameContainerElement = document.createElement('div'); iFrameContainerElement.className = 'iframe-container monaco-editor-background'; // Inherit the background color from selected theme iFrameContainerElement.appendChild(this._iFrameElement); parent.getHTMLElement().appendChild(iFrameContainerElement); this._themeChangeUnbind = this._storageService.addListener(StorageEventType.STORAGE, event => { if (event.key === Preferences.THEME && this.isVisible()) { this._updateIFrameContent(true); } }); } public layout(dimension: Dimension): void { let {width, height} = dimension; this._iFrameElement.parentElement.style.width = `${width}px`; this._iFrameElement.parentElement.style.height = `${height}px`; this._iFrameElement.style.width = `${width}px`; this._iFrameElement.style.height = `${height}px`; } public focus(): void { // this.iframeContainer.domFocus(); this._iFrameElement.focus(); } // --- input public getTitle(): string { if (!this.input) { return localize('iframeEditor', 'Preview Html'); } return this.input.getName(); } public setVisible(visible: boolean, position?: Position): TPromise<void> { return super.setVisible(visible, position).then(() => { if (visible && this._model) { this._modelChangeUnbind = this._model.addListener(EventType.ModelContentChanged2, () => this._updateIFrameContent()); this._updateIFrameContent(); } else { this._modelChangeUnbind = cAll(this._modelChangeUnbind); } }) } public changePosition(position: Position): void { super.changePosition(position); // reparenting an IFRAME into another DOM element yields weird results when the contents are made // of a string and not a URL. to be on the safe side we reload the iframe when the position changes // and we do it using a timeout of 0 to reload only after the position has been changed in the DOM setTimeout(() => { this._updateIFrameContent(true); }, 0); } public setInput(input: EditorInput, options: EditorOptions): TPromise<void> { this._model = undefined; this._modelChangeUnbind = cAll(this._modelChangeUnbind); this._lastModelVersion = -1; if (!(input instanceof HtmlInput)) { return TPromise.wrapError<void>('Invalid input'); } return this._editorService.resolveEditorModel({ resource: (<HtmlInput>input).getResource() }).then(model => { if (model instanceof BaseTextEditorModel) { this._model = model.textEditorModel } if (!this._model) { return TPromise.wrapError<void>(localize('html.voidInput', "Invalid editor input.")); } this._modelChangeUnbind = this._model.addListener(EventType.ModelContentChanged2, () => this._updateIFrameContent()); this._updateIFrameContent(); return super.setInput(input, options); }); } private _updateIFrameContent(refresh: boolean = false): void { if (!this._model || (!refresh && this._lastModelVersion === this._model.getVersionId())) { // nothing to do return; } const html = this._model.getValue(); const iFrameDocument = this._iFrameElement.contentDocument; if (!iFrameDocument) { // not visible anymore return; } // the very first time we load just our script // to integrate with the outside world if ((<HTMLElement>iFrameDocument.firstChild).innerHTML === '<head></head><body></body>') { iFrameDocument.open('text/html', 'replace'); iFrameDocument.write(Integration.defaultHtml()); iFrameDocument.close(); } // diff a little against the current input and the new state const parser = new DOMParser(); const newDocument = parser.parseFromString(html, 'text/html'); const styleElement = Integration.defaultStyle(this._iFrameElement.parentElement, this._storageService.get(Preferences.THEME, StorageScope.GLOBAL, DEFAULT_THEME_ID)); if (newDocument.head.hasChildNodes()) { newDocument.head.insertBefore(styleElement, newDocument.head.firstChild); } else { newDocument.head.appendChild(styleElement) } if (newDocument.head.innerHTML !== iFrameDocument.head.innerHTML) { iFrameDocument.head.innerHTML = newDocument.head.innerHTML; } if (newDocument.body.innerHTML !== iFrameDocument.body.innerHTML) { iFrameDocument.body.innerHTML = newDocument.body.innerHTML; } this._lastModelVersion = this._model.getVersionId(); } } namespace Integration { 'use strict'; const scriptSource = [ 'var ignoredKeys = [9 /* tab */, 32 /* space */, 33 /* page up */, 34 /* page down */, 38 /* up */, 40 /* down */];', 'var ignoredCtrlCmdKeys = [65 /* a */, 67 /* c */];', 'var ignoredShiftKeys = [9 /* tab */];', 'window.document.body.addEventListener("keydown", function(event) {', // Listen to keydown events in the iframe ' try {', ' if (ignoredKeys.some(function(i) { return i === event.keyCode; })) {', ' if (!event.ctrlKey && !event.altKey && !event.shiftKey && !event.metaKey) {', ' return;', // we want some single keys to be supported (e.g. Page Down for scrolling) ' }', ' }', '', ' if (ignoredCtrlCmdKeys.some(function(i) { return i === event.keyCode; })) {', ' if (event.ctrlKey || event.metaKey) {', ' return;', // we want some ctrl/cmd keys to be supported (e.g. Ctrl+C for copy) ' }', ' }', '', ' if (ignoredShiftKeys.some(function(i) { return i === event.keyCode; })) {', ' if (event.shiftKey) {', ' return;', // we want some shift keys to be supported (e.g. Shift+Tab for copy) ' }', ' }', '', ' event.preventDefault();', // very important to not get duplicate actions when this one bubbles up! '', ' var fakeEvent = document.createEvent("KeyboardEvent");', // create a keyboard event ' Object.defineProperty(fakeEvent, "keyCode", {', // we need to set some properties that Chrome wants ' get : function() {', ' return event.keyCode;', ' }', ' });', ' Object.defineProperty(fakeEvent, "which", {', ' get : function() {', ' return event.keyCode;', ' }', ' });', ' Object.defineProperty(fakeEvent, "target", {', ' get : function() {', ' return window && window.parent.document.body;', ' }', ' });', '', ' fakeEvent.initKeyboardEvent("keydown", true, true, document.defaultView, null, null, event.ctrlKey, event.altKey, event.shiftKey, event.metaKey);', // the API shape of this method is not clear to me, but it works ;) '', ' window.parent.document.dispatchEvent(fakeEvent);', // dispatch the event onto the parent ' } catch (error) {}', '});', // disable dropping into iframe! 'window.document.addEventListener("dragover", function (e) {', ' e.preventDefault();', '});', 'window.document.addEventListener("drop", function (e) {', ' e.preventDefault();', '});', 'window.document.body.addEventListener("dragover", function (e) {', ' e.preventDefault();', '});', 'window.document.body.addEventListener("drop", function (e) {', ' e.preventDefault();', '});' ]; export function defaultHtml() { let all = [ '<html><head></head><body><script>', ...scriptSource, '</script></body></html>', ]; return all.join('\n'); } const defaultLightScrollbarStyle = [ '::-webkit-scrollbar-thumb {', ' background-color: rgba(100, 100, 100, 0.4);', '}', '::-webkit-scrollbar-thumb:hover {', ' background-color: rgba(100, 100, 100, 0.7);', '}', '::-webkit-scrollbar-thumb:active {', ' background-color: rgba(0, 0, 0, 0.6);', '}' ].join('\n'); const defaultDarkScrollbarStyle = [ '::-webkit-scrollbar-thumb {', ' background-color: rgba(121, 121, 121, 0.4);', '}', '::-webkit-scrollbar-thumb:hover {', ' background-color: rgba(100, 100, 100, 0.7);', '}', '::-webkit-scrollbar-thumb:active {', ' background-color: rgba(85, 85, 85, 0.8);', '}' ].join('\n') export function defaultStyle(element: HTMLElement, themeId: string): HTMLStyleElement { const styles = window.getComputedStyle(element); const styleElement = document.createElement('style'); styleElement.innerHTML = `* { color: ${styles.color}; background: ${styles.background}; font-family: ${styles.fontFamily}; font-size: ${styles.fontSize}; } img { max-width: 100%; max-height: 100%; } a:focus, input:focus, select:focus, textarea:focus { outline: 1px solid -webkit-focus-ring-color; outline-offset: -1px; } ::-webkit-scrollbar { width: 14px; height: 14px; } ${isLightTheme(themeId) ? defaultLightScrollbarStyle : defaultDarkScrollbarStyle}`; return styleElement; } }
src/vs/workbench/parts/html/browser/htmlPreviewPart.ts
1
https://github.com/microsoft/vscode/commit/8435ddcf464fd995936ff6f877ff4744dc3ca2b6
[ 0.9978410005569458, 0.057705432176589966, 0.00016149358998518437, 0.00017431349260732532, 0.22614534199237823 ]
{ "id": 8, "code_window": [ "\t\t}\n", "\n", "\t\treturn this._editorService.resolveEditorModel({ resource: (<HtmlInput>input).getResource() }).then(model => {\n", "\t\t\tif (model instanceof BaseTextEditorModel) {\n", "\t\t\t\tthis._model = model.textEditorModel\n", "\t\t\t}\n", "\n", "\t\t\tif (!this._model) {\n", "\t\t\t\treturn TPromise.wrapError<void>(localize('html.voidInput', \"Invalid editor input.\"));\n", "\t\t\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tthis._model = model.textEditorModel;\n" ], "file_path": "src/vs/workbench/parts/html/browser/htmlPreviewPart.ts", "type": "replace", "edit_start_line_idx": 141 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import * as assert from 'assert'; import {BaseEditor, EditorInputAction, EditorInputActionContributor, EditorDescriptor, Extensions, IEditorRegistry, IEditorInputFactory} from 'vs/workbench/browser/parts/editor/baseEditor'; import {EditorInput, EditorOptions} from 'vs/workbench/common/editor'; import {IInstantiationService} from 'vs/platform/instantiation/common/instantiation'; import * as InstantiationService from 'vs/platform/instantiation/common/instantiationService'; import * as Platform from 'vs/platform/platform'; import {SyncDescriptor} from 'vs/platform/instantiation/common/descriptors'; import {StringEditorInput} from 'vs/workbench/common/editor/stringEditorInput'; import {ITelemetryService} from 'vs/platform/telemetry/common/telemetry'; import {NullTelemetryService} from 'vs/platform/telemetry/common/nullTelemetryService'; import mime = require('vs/base/common/mime'); let EditorRegistry: IEditorRegistry = Platform.Registry.as(Extensions.Editors); export class MyEditor extends BaseEditor { constructor(id: string, @ITelemetryService telemetryService: ITelemetryService) { super(id, telemetryService); } getId(): string { return "myEditor"; } public layout(): void { } public createEditor(): any { } } export class MyOtherEditor extends BaseEditor { constructor(id: string, @ITelemetryService telemetryService: ITelemetryService) { super(id, telemetryService); } getId(): string { return "myOtherEditor"; } public layout(): void { } public createEditor(): any { } } class MyInputFactory implements IEditorInputFactory { serialize(input: EditorInput): string { return input.toString(); } deserialize(instantiationService: IInstantiationService, raw: string): EditorInput { return <EditorInput>{}; } } class MyInput extends EditorInput { getPreferredEditorId(ids) { return ids[1]; } public getId(): string { return ''; } public resolve(refresh?: boolean): any { return null; } } class MyOtherInput extends EditorInput { public getId(): string { return ''; } public resolve(refresh?: boolean): any { return null; } } class MyStringInput extends StringEditorInput { } class MyAction extends EditorInputAction { public didCallIsEnabled = false; isEnabled() { this.didCallIsEnabled = true; return true; } } class MyAction2 extends EditorInputAction { isEnabled() { return true; } } class MyEditorInputActionContributor extends EditorInputActionContributor { hasActionsForEditorInput(context) { return context.input instanceof StringEditorInput; } getActionsForEditorInput(context) { return [ new MyAction2("id1", "label1"), new MyAction2("id2", "label2") ]; } } class MyClass { } class MyOtherClass { } suite("Workbench BaseEditor", () => { test("BaseEditor API", function(done) { let e = new MyEditor("id", new NullTelemetryService()); let input = new MyOtherInput(); let options = new EditorOptions(); assert(!e.isVisible()); assert(!e.getInput()); assert(!e.getOptions()); e.setInput(input, options).then(function() { assert.strictEqual(input, e.getInput()); assert.strictEqual(options, e.getOptions()); return e.setVisible(true).then(function() { assert(e.isVisible()); input.addListener("dispose", function() { assert(false); }); e.dispose(); e.clearInput(); return e.setVisible(false).then(function() { assert(!e.isVisible()); assert(!e.getInput()); assert(!e.getOptions()); assert(!e.getControl()); }); }); }).done(() => done()); }); test("EditorDescriptor", function() { let d = new EditorDescriptor("id", "name", "vs/workbench/test/browser/parts/editor/baseEditor.test", "MyClass"); assert.strictEqual(d.getId(), "id"); assert.strictEqual(d.getName(), "name"); }); test("Editor Registration", function() { let d1 = new EditorDescriptor("id1", "name", "vs/workbench/test/browser/parts/editor/baseEditor.test", "MyClass"); let d2 = new EditorDescriptor("id2", "name", "vs/workbench/test/browser/parts/editor/baseEditor.test", "MyOtherClass"); let oldEditorsCnt = EditorRegistry.getEditors().length; let oldInputCnt = (<any>EditorRegistry).getEditorInputs().length; EditorRegistry.registerEditor(d1, new SyncDescriptor(MyInput)); EditorRegistry.registerEditor(d2, [new SyncDescriptor(MyInput), new SyncDescriptor(MyOtherInput)]); assert.equal(EditorRegistry.getEditors().length, oldEditorsCnt + 2); assert.equal((<any>EditorRegistry).getEditorInputs().length, oldInputCnt + 3); assert.strictEqual(EditorRegistry.getEditor(new MyInput()), d2); assert.strictEqual(EditorRegistry.getEditor(new MyOtherInput()), d2); assert.strictEqual(EditorRegistry.getEditorById("id1"), d1); assert.strictEqual(EditorRegistry.getEditorById("id2"), d2); assert(!EditorRegistry.getEditorById("id3")); }); test("Editor Lookup favors specific class over superclass (match on specific class)", function(done) { let d1 = new EditorDescriptor("id1", "name", "vs/workbench/test/browser/parts/editor/baseEditor.test", "MyEditor"); let d2 = new EditorDescriptor("id2", "name", "vs/workbench/test/browser/parts/editor/baseEditor.test", "MyOtherEditor"); let oldEditors = EditorRegistry.getEditors(); (<any>EditorRegistry).setEditors([]); EditorRegistry.registerEditor(d2, new SyncDescriptor(StringEditorInput)); EditorRegistry.registerEditor(d1, new SyncDescriptor(MyStringInput)); let inst = InstantiationService.create({}); inst.createInstance(EditorRegistry.getEditor(inst.createInstance(MyStringInput, 'fake', '', '', mime.MIME_TEXT, false)), 'id').then(function(editor) { assert.strictEqual(editor.getId(), "myEditor"); return inst.createInstance(EditorRegistry.getEditor(inst.createInstance(StringEditorInput, 'fake', '', '', mime.MIME_TEXT, false)), 'id').then(function(editor) { assert.strictEqual(editor.getId(), "myOtherEditor"); (<any>EditorRegistry).setEditors(oldEditors); }); }).done(() => done()); }); test("Editor Lookup favors specific class over superclass (match on super class)", function(done) { let d1 = new EditorDescriptor("id1", "name", "vs/workbench/test/browser/parts/editor/baseEditor.test", "MyOtherEditor"); let oldEditors = EditorRegistry.getEditors(); (<any>EditorRegistry).setEditors([]); EditorRegistry.registerEditor(d1, new SyncDescriptor(StringEditorInput)); let inst = InstantiationService.create({}); inst.createInstance(EditorRegistry.getEditor(inst.createInstance(MyStringInput, 'fake', '', '', mime.MIME_TEXT, false)), 'id').then(function(editor) { assert.strictEqual("myOtherEditor", editor.getId()); (<any>EditorRegistry).setEditors(oldEditors); }).done(() => done()); }); test("Editor Input Action - triggers isEnabled properly", function() { let inst = InstantiationService.create({}); let action = new MyAction("id", "label"); action.input = inst.createInstance(StringEditorInput, 'input', '', '', mime.MIME_TEXT, false); assert.equal(action.didCallIsEnabled, true); }); test("Editor Input Action Contributor", function() { let inst = InstantiationService.create({}); let contributor = new MyEditorInputActionContributor(); assert(!contributor.hasActions(null)); assert(contributor.hasActions({ editor: new MyEditor("id", new NullTelemetryService()), input: inst.createInstance(StringEditorInput, 'fake', '', '', mime.MIME_TEXT, false), position: 0 })); let actionsFirst = contributor.getActions({ editor: new MyEditor("id", new NullTelemetryService()), input: inst.createInstance(StringEditorInput, 'fake', '', '', mime.MIME_TEXT, false), position: 0 }); assert.strictEqual(actionsFirst.length, 2); let input = inst.createInstance(StringEditorInput, 'fake', '', '', mime.MIME_TEXT, false); let actions = contributor.getActions({ editor: new MyEditor("id", new NullTelemetryService()), input: input, position: 0 }); assert(actions[0] === actionsFirst[0]); assert(actions[1] === actionsFirst[1]); assert((<any>actions[0]).input === input); assert((<any>actions[1]).input === input); // other editor causes new actions to be created actions = contributor.getActions({ editor: new MyOtherEditor("id2", new NullTelemetryService()), input: input, position: 0 }); assert(actions[0] !== actionsFirst[0]); assert(actions[1] !== actionsFirst[1]); assert((<any>actions[0]).input === input); assert((<any>actions[1]).input === input); // other input causes actions to loose input context let myInput = new MyInput(); myInput.getId = function() { return "foo.id"; }; actions = contributor.getActions({ editor: new MyEditor("id3", new NullTelemetryService()), input: myInput, position: 0 }); assert(!(<any>actionsFirst[0]).input); assert(!(<any>actionsFirst[1]).input); }); test("Editor Input Factory", function() { EditorRegistry.setInstantiationService(InstantiationService.create({})); EditorRegistry.registerEditorInputFactory("myInputId", MyInputFactory); let factory = EditorRegistry.getEditorInputFactory("myInputId"); assert(factory); }); return { MyEditor: MyEditor, MyOtherEditor: MyOtherEditor }; });
src/vs/workbench/test/browser/parts/editor/baseEditor.test.ts
0
https://github.com/microsoft/vscode/commit/8435ddcf464fd995936ff6f877ff4744dc3ca2b6
[ 0.0021182913333177567, 0.0004127012798562646, 0.0001646002201596275, 0.0001764514745445922, 0.0005133200320415199 ]
{ "id": 8, "code_window": [ "\t\t}\n", "\n", "\t\treturn this._editorService.resolveEditorModel({ resource: (<HtmlInput>input).getResource() }).then(model => {\n", "\t\t\tif (model instanceof BaseTextEditorModel) {\n", "\t\t\t\tthis._model = model.textEditorModel\n", "\t\t\t}\n", "\n", "\t\t\tif (!this._model) {\n", "\t\t\t\treturn TPromise.wrapError<void>(localize('html.voidInput', \"Invalid editor input.\"));\n", "\t\t\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tthis._model = model.textEditorModel;\n" ], "file_path": "src/vs/workbench/parts/html/browser/htmlPreviewPart.ts", "type": "replace", "edit_start_line_idx": 141 }
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="3 3 16 16" enable-background="new 3 3 16 16"><polygon fill="#656565" points="12.597,11.042 15.4,13.845 13.844,15.4 11.042,12.598 8.239,15.4 6.683,13.845 9.485,11.042 6.683,8.239 8.238,6.683 11.042,9.486 13.845,6.683 15.4,8.239"/></svg>
src/vs/editor/contrib/find/browser/images/close.svg
0
https://github.com/microsoft/vscode/commit/8435ddcf464fd995936ff6f877ff4744dc3ca2b6
[ 0.0001733989192871377, 0.0001733989192871377, 0.0001733989192871377, 0.0001733989192871377, 0 ]
{ "id": 8, "code_window": [ "\t\t}\n", "\n", "\t\treturn this._editorService.resolveEditorModel({ resource: (<HtmlInput>input).getResource() }).then(model => {\n", "\t\t\tif (model instanceof BaseTextEditorModel) {\n", "\t\t\t\tthis._model = model.textEditorModel\n", "\t\t\t}\n", "\n", "\t\t\tif (!this._model) {\n", "\t\t\t\treturn TPromise.wrapError<void>(localize('html.voidInput', \"Invalid editor input.\"));\n", "\t\t\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tthis._model = model.textEditorModel;\n" ], "file_path": "src/vs/workbench/parts/html/browser/htmlPreviewPart.ts", "type": "replace", "edit_start_line_idx": 141 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import {TPromise} from 'vs/base/common/winjs.base'; /** * @returns whether the provided parameter is a JavaScript Array or not. */ export function isArray(array: any): array is any[] { if (Array.isArray) { return Array.isArray(array); } if (array && typeof (array.length) === 'number' && array.constructor === Array) { return true; } return false; } /** * @returns whether the provided parameter is a JavaScript String or not. */ export function isString(str: any): str is string { if (typeof (str) === 'string' || str instanceof String) { return true; } return false; } /** * @returns whether the provided parameter is a JavaScript Array and each element in the array is a string. */ export function isStringArray(value: any): value is string[] { return isArray(value) && (<any[]>value).every(elem => isString(elem)); } /** * @returns whether the provided parameter is a JavaScript Object or not. */ export function isObject(obj: any): obj is any { // Needed for IE8 if (typeof obj === 'undefined' || obj === null) { return false; } return Object.prototype.toString.call(obj) === '[object Object]'; } /** * @returns whether the provided parameter is a JavaScript Number or not. */ export function isNumber(obj: any): obj is number { if ((typeof (obj) === 'number' || obj instanceof Number) && !isNaN(obj)) { return true; } return false; } /** * @returns whether the provided parameter is a JavaScript Boolean or not. */ export function isBoolean(obj: any): obj is boolean { return obj === true || obj === false; } /** * @returns whether the provided parameter is undefined. */ export function isUndefined(obj: any): boolean { return typeof (obj) === 'undefined'; } /** * @returns whether the provided parameter is undefined or null. */ export function isUndefinedOrNull(obj: any): boolean { return isUndefined(obj) || obj === null; } const hasOwnProperty = Object.prototype.hasOwnProperty; /** * @returns whether the provided parameter is an empty JavaScript Object or not. */ export function isEmptyObject(obj: any): obj is any { if (!isObject(obj)) { return false; } for (let key in obj) { if (hasOwnProperty.call(obj, key)) { return false; } } return true; } /** * @returns whether the provided parameter is a JavaScript Function or not. */ export function isFunction(obj: any): obj is Function { return Object.prototype.toString.call(obj) === '[object Function]'; } /** * @returns whether the provided parameters is are JavaScript Function or not. */ export function areFunctions(...objects: any[]): boolean { return objects && objects.length > 0 && objects.every((object) => isFunction(object)); } export type TypeConstraint = string | Function; export function validateConstraints(args: any[], constraints: TypeConstraint[]): void { const len = Math.min(args.length, constraints.length); for (let i = 0; i < len; i++) { validateConstraint(args[i], constraints[i]); } } export function validateConstraint(arg: any, constraint: TypeConstraint): void { if (typeof constraint === 'string') { if (typeof arg !== constraint) { throw new Error(`argument does not match constraint: typeof ${constraint}`); } } else if (typeof constraint === 'function') { if (arg instanceof constraint) { return; } if (arg && arg.constructor === constraint) { return; } if (constraint.length === 1 && constraint.call(undefined, arg) === true) { return; } throw new Error(`argument does not match one of these constraints: arg instanceof constraint, arg.constructor === constraint, nor constraint(arg) === true`); } } /** * Creates a new object of the provided class and will call the constructor with * any additional argument supplied. */ export function create(ctor: Function, ...args: any[]): any { let obj = Object.create(ctor.prototype); ctor.apply(obj, args); return obj; } export interface IFunction0<T> { (): T; } export interface IFunction1<A1, T> { (a1: A1): T; } export interface IFunction2<A1, A2, T> { (a1: A1, a2: A2): T; } export interface IFunction3<A1, A2, A3, T> { (a1: A1, a2: A2, a3: A3): T; } export interface IFunction4<A1, A2, A3, A4, T> { (a1: A1, a2: A2, a3: A3, a4: A4): T; } export interface IFunction5<A1, A2, A3, A4, A5, T> { (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5): T; } export interface IFunction6<A1, A2, A3, A4, A5, A6, T> { (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6): T; } export interface IFunction7<A1, A2, A3, A4, A5, A6, A7, T> { (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7): T; } export interface IFunction8<A1, A2, A3, A4, A5, A6, A7, A8, T> { (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7, a8: A8): T; } export interface IAction0 extends IFunction0<void> { } export interface IAction1<A1> extends IFunction1<A1, void> { } export interface IAction2<A1, A2> extends IFunction2<A1, A2, void> { } export interface IAction3<A1, A2, A3> extends IFunction3<A1, A2, A3, void> { } export interface IAction4<A1, A2, A3, A4> extends IFunction4<A1, A2, A3, A4, void> { } export interface IAction5<A1, A2, A3, A4, A5> extends IFunction5<A1, A2, A3, A4, A5, void> { } export interface IAction6<A1, A2, A3, A4, A5, A6> extends IFunction6<A1, A2, A3, A4, A5, A6, void> { } export interface IAction7<A1, A2, A3, A4, A5, A6, A7> extends IFunction7<A1, A2, A3, A4, A5, A6, A7, void> { } export interface IAction8<A1, A2, A3, A4, A5, A6, A7, A8> extends IFunction8<A1, A2, A3, A4, A5, A6, A7, A8, void> { } export interface IAsyncFunction0<T> extends IFunction0<TPromise<T>> { } export interface IAsyncFunction1<A1, T> extends IFunction1<A1, TPromise<T>> { } export interface IAsyncFunction2<A1, A2, T> extends IFunction2<A1, A2, TPromise<T>> { } export interface IAsyncFunction3<A1, A2, A3, T> extends IFunction3<A1, A2, A3, TPromise<T>> { } export interface IAsyncFunction4<A1, A2, A3, A4, T> extends IFunction4<A1, A2, A3, A4, TPromise<T>> { } export interface IAsyncFunction5<A1, A2, A3, A4, A5, T> extends IFunction5<A1, A2, A3, A4, A5, TPromise<T>> { } export interface IAsyncFunction6<A1, A2, A3, A4, A5, A6, T> extends IFunction6<A1, A2, A3, A4, A5, A6, TPromise<T>> { } export interface IAsyncFunction7<A1, A2, A3, A4, A5, A6, A7, T> extends IFunction7<A1, A2, A3, A4, A5, A6, A7, TPromise<T>> { } export interface IAsyncFunction8<A1, A2, A3, A4, A5, A6, A7, A8, T> extends IFunction8<A1, A2, A3, A4, A5, A6, A7, A8, TPromise<T>> { }
src/vs/base/common/types.ts
0
https://github.com/microsoft/vscode/commit/8435ddcf464fd995936ff6f877ff4744dc3ca2b6
[ 0.000176389396074228, 0.00017062679398804903, 0.00016053279978223145, 0.00017114165530074388, 0.0000036207995890435996 ]
{ "id": 9, "code_window": [ "\t\tconst newDocument = parser.parseFromString(html, 'text/html');\n", "\t\tconst styleElement = Integration.defaultStyle(this._iFrameElement.parentElement, this._storageService.get(Preferences.THEME, StorageScope.GLOBAL, DEFAULT_THEME_ID));\n", "\t\tif (newDocument.head.hasChildNodes()) {\n", "\t\t\tnewDocument.head.insertBefore(styleElement, newDocument.head.firstChild);\n", "\t\t} else {\n", "\t\t\tnewDocument.head.appendChild(styleElement)\n", "\t\t}\n", "\n", "\t\tif (newDocument.head.innerHTML !== iFrameDocument.head.innerHTML) {\n", "\t\t\tiFrameDocument.head.innerHTML = newDocument.head.innerHTML;\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tnewDocument.head.appendChild(styleElement);\n" ], "file_path": "src/vs/workbench/parts/html/browser/htmlPreviewPart.ts", "type": "replace", "edit_start_line_idx": 185 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import 'vs/css!./media/binarydiffeditor'; import {TPromise} from 'vs/base/common/winjs.base'; import nls = require('vs/nls'); import URI from 'vs/base/common/uri'; import {Sash, ISashEvent, IVerticalSashLayoutProvider} from 'vs/base/browser/ui/sash/sash'; import {Dimension, Builder, $} from 'vs/base/browser/builder'; import {ResourceViewer} from 'vs/base/browser/ui/resourceviewer/resourceViewer'; import {IScrollableElement} from 'vs/base/browser/ui/scrollbar/scrollableElement'; import {ScrollableElement} from 'vs/base/browser/ui/scrollbar/scrollableElementImpl'; import {BaseEditor} from 'vs/workbench/browser/parts/editor/baseEditor'; import {EditorInput, EditorOptions} from 'vs/workbench/common/editor'; import {BinaryEditorModel} from 'vs/workbench/common/editor/binaryEditorModel'; import {DiffEditorModel} from 'vs/workbench/common/editor/diffEditorModel'; import {IWorkbenchEditorService} from 'vs/workbench/services/editor/common/editorService'; import {ITelemetryService} from 'vs/platform/telemetry/common/telemetry'; /** * An implementation of editor for diffing binary files like images or videos. */ export class BinaryResourceDiffEditor extends BaseEditor implements IVerticalSashLayoutProvider { public static ID = 'workbench.editors.binaryResourceDiffEditor'; private static MIN_CONTAINER_WIDTH = 100; private leftBinaryContainer: Builder; private leftScrollbar: IScrollableElement; private rightBinaryContainer: Builder; private rightScrollbar: IScrollableElement; private sash: Sash; private dimension: Dimension; private leftContainerWidth: number; private startLeftContainerWidth: number; constructor( @ITelemetryService telemetryService: ITelemetryService, @IWorkbenchEditorService private editorService: IWorkbenchEditorService ) { super(BinaryResourceDiffEditor.ID, telemetryService); } public getTitle(): string { return this.getInput() ? this.getInput().getName() : nls.localize('binaryDiffEditor', "Binary Diff Viewer"); } public createEditor(parent: Builder): void { // Left Container for Binary let leftBinaryContainerElement = document.createElement('div'); leftBinaryContainerElement.className = 'binary-container'; this.leftBinaryContainer = $(leftBinaryContainerElement); // Left Custom Scrollbars this.leftScrollbar = new ScrollableElement(leftBinaryContainerElement, { horizontal: 'hidden', vertical: 'hidden' }); parent.getHTMLElement().appendChild(this.leftScrollbar.getDomNode()); $(this.leftScrollbar.getDomNode()).addClass('binarydiff-left'); // Sash this.sash = new Sash(parent.getHTMLElement(), this); this.sash.addListener('start', () => this.onSashDragStart()); this.sash.addListener('change', (e: ISashEvent) => this.onSashDrag(e)); this.sash.addListener('end', () => this.onSashDragEnd()); // Right Container for Binary let rightBinaryContainerElement = document.createElement('div'); rightBinaryContainerElement.className = 'binary-container'; this.rightBinaryContainer = $(rightBinaryContainerElement); // Right Custom Scrollbars this.rightScrollbar = new ScrollableElement(rightBinaryContainerElement, { horizontal: 'hidden', vertical: 'hidden' }); parent.getHTMLElement().appendChild(this.rightScrollbar.getDomNode()); $(this.rightScrollbar.getDomNode()).addClass('binarydiff-right'); } public setInput(input: EditorInput, options: EditorOptions): TPromise<void> { let oldInput = this.getInput(); super.setInput(input, options); // Detect options let forceOpen = options && options.forceOpen; // Same Input if (!forceOpen && input.matches(oldInput)) { return TPromise.as<void>(null); } // Different Input (Reload) return this.editorService.resolveEditorModel(input, true /* Reload */).then((resolvedModel: DiffEditorModel) => { // Assert model instance if (!(resolvedModel.originalModel instanceof BinaryEditorModel) || !(resolvedModel.modifiedModel instanceof BinaryEditorModel)) { return TPromise.wrapError<void>(nls.localize('cannotDiffTextToBinary', "Comparing binary files to non binary files is currently not supported")); } // Assert that the current input is still the one we expect. This prevents a race condition when loading a diff takes long and another input was set meanwhile if (!this.getInput() || this.getInput() !== input) { return null; } // Render original let original = <BinaryEditorModel>resolvedModel.originalModel; this.renderInput(original.getName(), original.getResource(), true); // Render modified let modified = <BinaryEditorModel>resolvedModel.modifiedModel; this.renderInput(modified.getName(), modified.getResource(), false); }); } private renderInput(name: string, resource: URI, isOriginal: boolean): void { // Reset Sash to default 50/50 ratio if needed if (this.leftContainerWidth && this.dimension && this.leftContainerWidth !== this.dimension.width / 2) { this.leftContainerWidth = this.dimension.width / 2; this.layoutContainers(); this.sash.layout(); } // Pass to ResourceViewer let container = isOriginal ? this.leftBinaryContainer : this.rightBinaryContainer; let scrollbar = isOriginal ? this.leftScrollbar : this.rightScrollbar; ResourceViewer.show(name, resource, container, scrollbar); } public clearInput(): void { // Empty HTML Container $(this.leftBinaryContainer).empty(); $(this.rightBinaryContainer).empty(); super.clearInput(); } public layout(dimension: Dimension): void { let oldDimension = this.dimension; this.dimension = dimension; // Calculate left hand container width based on sash move or fallback to 50% by default if (!this.leftContainerWidth || !oldDimension) { this.leftContainerWidth = this.dimension.width / 2; } else { let sashRatio = this.leftContainerWidth / oldDimension.width; this.leftContainerWidth = this.dimension.width * sashRatio; } // Sash positioning this.sash.layout(); // Pass on to Binary Containers and Scrollbars this.layoutContainers(); } private layoutContainers(): void { // Size left container this.leftBinaryContainer.size(this.leftContainerWidth, this.dimension.height); this.leftScrollbar.onElementDimensions(); this.leftScrollbar.onElementInternalDimensions(); // Size right container this.rightBinaryContainer.size(this.dimension.width - this.leftContainerWidth, this.dimension.height); this.rightScrollbar.onElementDimensions(); this.rightScrollbar.onElementInternalDimensions(); } private onSashDragStart(): void { this.startLeftContainerWidth = this.leftContainerWidth; } private onSashDrag(e: ISashEvent): void { // Update Widths and keep in bounds of MIN_CONTAINER_WIDTH for both sides let newLeftContainerWidth = this.startLeftContainerWidth + e.currentX - e.startX; this.leftContainerWidth = Math.max(BinaryResourceDiffEditor.MIN_CONTAINER_WIDTH, newLeftContainerWidth); if (this.dimension.width - this.leftContainerWidth < BinaryResourceDiffEditor.MIN_CONTAINER_WIDTH) { this.leftContainerWidth = this.dimension.width - BinaryResourceDiffEditor.MIN_CONTAINER_WIDTH; } // Pass on to Binary Containers and Scrollbars this.layoutContainers(); } private onSashDragEnd(): void { this.sash.layout(); } public getVerticalSashTop(sash: Sash): number { return 0; } public getVerticalSashLeft(sash: Sash): number { return this.leftContainerWidth; } public getVerticalSashHeight(sash: Sash): number { return this.dimension.height; } public focus(): void { this.rightBinaryContainer.domFocus(); } public dispose(): void { // Sash this.sash.dispose(); // Dispose Scrollbar this.leftScrollbar.dispose(); this.rightScrollbar.dispose(); // Destroy Container this.leftBinaryContainer.destroy(); this.rightBinaryContainer.destroy(); super.dispose(); } }
src/vs/workbench/browser/parts/editor/binaryDiffEditor.ts
1
https://github.com/microsoft/vscode/commit/8435ddcf464fd995936ff6f877ff4744dc3ca2b6
[ 0.0001759643928380683, 0.0001713417877908796, 0.00016542436787858605, 0.0001714874670142308, 0.0000028749354896717705 ]
{ "id": 9, "code_window": [ "\t\tconst newDocument = parser.parseFromString(html, 'text/html');\n", "\t\tconst styleElement = Integration.defaultStyle(this._iFrameElement.parentElement, this._storageService.get(Preferences.THEME, StorageScope.GLOBAL, DEFAULT_THEME_ID));\n", "\t\tif (newDocument.head.hasChildNodes()) {\n", "\t\t\tnewDocument.head.insertBefore(styleElement, newDocument.head.firstChild);\n", "\t\t} else {\n", "\t\t\tnewDocument.head.appendChild(styleElement)\n", "\t\t}\n", "\n", "\t\tif (newDocument.head.innerHTML !== iFrameDocument.head.innerHTML) {\n", "\t\t\tiFrameDocument.head.innerHTML = newDocument.head.innerHTML;\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tnewDocument.head.appendChild(styleElement);\n" ], "file_path": "src/vs/workbench/parts/html/browser/htmlPreviewPart.ts", "type": "replace", "edit_start_line_idx": 185 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import URI from './utils/uri'; import Parser = require('./jsonParser'); import SchemaService = require('./jsonSchemaService'); import JsonSchema = require('./json-toolbox/jsonSchema'); import nls = require('./utils/nls'); import {IJSONWorkerContribution} from './jsonContributions'; import {CompletionItem, CompletionItemKind, CompletionList, CompletionOptions, ITextDocument, TextDocumentIdentifier, TextDocumentPosition, Range, TextEdit} from 'vscode-languageserver'; export interface ISuggestionsCollector { add(suggestion: CompletionItem): void; error(message:string): void; setAsIncomplete(): void; } export class JSONCompletion { private schemaService: SchemaService.IJSONSchemaService; private contributions: IJSONWorkerContribution[]; constructor(schemaService: SchemaService.IJSONSchemaService, contributions: IJSONWorkerContribution[] = []) { this.schemaService = schemaService; this.contributions = contributions; } public doSuggest(document: ITextDocument, textDocumentPosition: TextDocumentPosition, doc: Parser.JSONDocument): Thenable<CompletionList> { let offset = document.offsetAt(textDocumentPosition.position); let node = doc.getNodeFromOffsetEndInclusive(offset); let currentWord = this.getCurrentWord(document, offset); let overwriteRange = null; let result: CompletionList = { items: [], isIncomplete: false } if (node && (node.type === 'string' || node.type === 'number' || node.type === 'boolean' || node.type === 'null')) { overwriteRange = Range.create(document.positionAt(node.start), document.positionAt(node.end)); } else { overwriteRange = Range.create(document.positionAt(offset - currentWord.length), textDocumentPosition.position); } let proposed: { [key: string]: boolean } = {}; let collector: ISuggestionsCollector = { add: (suggestion: CompletionItem) => { if (!proposed[suggestion.label]) { proposed[suggestion.label] = true; if (overwriteRange) { suggestion.textEdit = TextEdit.replace(overwriteRange, suggestion.insertText); } result.items.push(suggestion); } }, setAsIncomplete: () => { result.isIncomplete = true; }, error: (message: string) => { console.log(message); } }; return this.schemaService.getSchemaForResource(textDocumentPosition.uri, doc).then((schema) => { let collectionPromises: Thenable<any>[] = []; let addValue = true; let currentKey = ''; let currentProperty: Parser.PropertyASTNode = null; if (node) { if (node.type === 'string') { let stringNode = <Parser.StringASTNode>node; if (stringNode.isKey) { addValue = !(node.parent && ((<Parser.PropertyASTNode>node.parent).value)); currentProperty = node.parent ? <Parser.PropertyASTNode>node.parent : null; currentKey = document.getText().substring(node.start + 1, node.end - 1); if (node.parent) { node = node.parent.parent; } } } } // proposals for properties if (node && node.type === 'object') { // don't suggest keys when the cursor is just before the opening curly brace if (node.start === offset) { return result; } // don't suggest properties that are already present let properties = (<Parser.ObjectASTNode>node).properties; properties.forEach(p => { if (!currentProperty || currentProperty !== p) { proposed[p.key.value] = true; } }); let isLast = properties.length === 0 || offset >= properties[properties.length - 1].start; if (schema) { // property proposals with schema this.getPropertySuggestions(schema, doc, node, addValue, isLast, collector); } else { // property proposals without schema this.getSchemaLessPropertySuggestions(doc, node, currentKey, currentWord, isLast, collector); } let location = node.getNodeLocation(); this.contributions.forEach((contribution) => { let collectPromise = contribution.collectPropertySuggestions(textDocumentPosition.uri, location, currentWord, addValue, isLast, collector); if (collectPromise) { collectionPromises.push(collectPromise); } }); } // proposals for values if (node && (node.type === 'string' || node.type === 'number' || node.type === 'boolean' || node.type === 'null')) { node = node.parent; } if (schema) { // value proposals with schema this.getValueSuggestions(schema, doc, node, offset, collector); } else { // value proposals without schema this.getSchemaLessValueSuggestions(doc, node, offset, document, collector); } if (!node) { this.contributions.forEach((contribution) => { let collectPromise = contribution.collectDefaultSuggestions(textDocumentPosition.uri, collector); if (collectPromise) { collectionPromises.push(collectPromise); } }); } else { if ((node.type === 'property') && offset > (<Parser.PropertyASTNode> node).colonOffset) { let parentKey = (<Parser.PropertyASTNode>node).key.value; let valueNode = (<Parser.PropertyASTNode> node).value; if (!valueNode || offset <= valueNode.end) { let location = node.parent.getNodeLocation(); this.contributions.forEach((contribution) => { let collectPromise = contribution.collectValueSuggestions(textDocumentPosition.uri, location, parentKey, collector); if (collectPromise) { collectionPromises.push(collectPromise); } }); } } } return Promise.all(collectionPromises).then(() => result ); }); } private getPropertySuggestions(schema: SchemaService.ResolvedSchema, doc: Parser.JSONDocument, node: Parser.ASTNode, addValue: boolean, isLast: boolean, collector: ISuggestionsCollector): void { let matchingSchemas: Parser.IApplicableSchema[] = []; doc.validate(schema.schema, matchingSchemas, node.start); matchingSchemas.forEach((s) => { if (s.node === node && !s.inverted) { let schemaProperties = s.schema.properties; if (schemaProperties) { Object.keys(schemaProperties).forEach((key: string) => { let propertySchema = schemaProperties[key]; collector.add({ kind: CompletionItemKind.Property, label: key, insertText: this.getSnippetForProperty(key, propertySchema, addValue, isLast), documentation: propertySchema.description || '' }); }); } } }); } private getSchemaLessPropertySuggestions(doc: Parser.JSONDocument, node: Parser.ASTNode, currentKey: string, currentWord: string, isLast: boolean, collector: ISuggestionsCollector): void { let collectSuggestionsForSimilarObject = (obj: Parser.ObjectASTNode) => { obj.properties.forEach((p) => { let key = p.key.value; collector.add({ kind: CompletionItemKind.Property, label: key, insertText: this.getSnippetForSimilarProperty(key, p.value), documentation: '' }); }); }; if (node.parent) { if (node.parent.type === 'property') { // if the object is a property value, check the tree for other objects that hang under a property of the same name let parentKey = (<Parser.PropertyASTNode>node.parent).key.value; doc.visit((n) => { if (n.type === 'property' && (<Parser.PropertyASTNode>n).key.value === parentKey && (<Parser.PropertyASTNode>n).value && (<Parser.PropertyASTNode>n).value.type === 'object') { collectSuggestionsForSimilarObject(<Parser.ObjectASTNode>(<Parser.PropertyASTNode>n).value); } return true; }); } else if (node.parent.type === 'array') { // if the object is in an array, use all other array elements as similar objects (<Parser.ArrayASTNode>node.parent).items.forEach((n) => { if (n.type === 'object' && n !== node) { collectSuggestionsForSimilarObject(<Parser.ObjectASTNode>n); } }); } } if (!currentKey && currentWord.length > 0) { collector.add({ kind: CompletionItemKind.Property, label: JSON.stringify(currentWord), insertText: this.getSnippetForProperty(currentWord, null, true, isLast), documentation: '' }); } } private getSchemaLessValueSuggestions(doc: Parser.JSONDocument, node: Parser.ASTNode, offset: number, document: ITextDocument, collector: ISuggestionsCollector): void { let collectSuggestionsForValues = (value: Parser.ASTNode) => { if (!value.contains(offset)) { let content = this.getMatchingSnippet(value, document); collector.add({ kind: this.getSuggestionKind(value.type), label: content, insertText: content, documentation: '' }); } if (value.type === 'boolean') { this.addBooleanSuggestion(!value.getValue(), collector); } }; if (!node) { collector.add({ kind: this.getSuggestionKind('object'), label: 'Empty object', insertText: '{\n\t{{}}\n}', documentation: '' }); collector.add({ kind: this.getSuggestionKind('array'), label: 'Empty array', insertText: '[\n\t{{}}\n]', documentation: '' }); } else { if (node.type === 'property' && offset > (<Parser.PropertyASTNode>node).colonOffset) { let valueNode = (<Parser.PropertyASTNode>node).value; if (valueNode && offset > valueNode.end) { return; } // suggest values at the same key let parentKey = (<Parser.PropertyASTNode>node).key.value; doc.visit((n) => { if (n.type === 'property' && (<Parser.PropertyASTNode>n).key.value === parentKey && (<Parser.PropertyASTNode>n).value) { collectSuggestionsForValues((<Parser.PropertyASTNode>n).value); } return true; }); } if (node.type === 'array') { if (node.parent && node.parent.type === 'property') { // suggest items of an array at the same key let parentKey = (<Parser.PropertyASTNode>node.parent).key.value; doc.visit((n) => { if (n.type === 'property' && (<Parser.PropertyASTNode>n).key.value === parentKey && (<Parser.PropertyASTNode>n).value && (<Parser.PropertyASTNode>n).value.type === 'array') { ((<Parser.ArrayASTNode>(<Parser.PropertyASTNode>n).value).items).forEach((n) => { collectSuggestionsForValues(<Parser.ObjectASTNode>n); }); } return true; }); } else { // suggest items in the same array (<Parser.ArrayASTNode>node).items.forEach((n) => { collectSuggestionsForValues(<Parser.ObjectASTNode>n); }); } } } } private getValueSuggestions(schema: SchemaService.ResolvedSchema, doc: Parser.JSONDocument, node: Parser.ASTNode, offset: number, collector: ISuggestionsCollector): void { if (!node) { this.addDefaultSuggestion(schema.schema, collector); } else { let parentKey: string = null; if (node && (node.type === 'property') && offset > (<Parser.PropertyASTNode>node).colonOffset) { let valueNode = (<Parser.PropertyASTNode>node).value; if (valueNode && offset > valueNode.end) { return; // we are past the value node } parentKey = (<Parser.PropertyASTNode>node).key.value; node = node.parent; } if (node && (parentKey !== null || node.type === 'array')) { let matchingSchemas: Parser.IApplicableSchema[] = []; doc.validate(schema.schema, matchingSchemas, node.start); matchingSchemas.forEach((s) => { if (s.node === node && !s.inverted && s.schema) { if (s.schema.items) { this.addDefaultSuggestion(s.schema.items, collector); this.addEnumSuggestion(s.schema.items, collector); } if (s.schema.properties) { let propertySchema = s.schema.properties[parentKey]; if (propertySchema) { this.addDefaultSuggestion(propertySchema, collector); this.addEnumSuggestion(propertySchema, collector); } } } }); } } } private addBooleanSuggestion(value: boolean, collector: ISuggestionsCollector): void { collector.add({ kind: this.getSuggestionKind('boolean'), label: value ? 'true' : 'false', insertText: this.getTextForValue(value), documentation: '' }); } private addEnumSuggestion(schema: JsonSchema.IJSONSchema, collector: ISuggestionsCollector): void { if (Array.isArray(schema.enum)) { schema.enum.forEach((enm) => collector.add({ kind: this.getSuggestionKind(schema.type), label: this.getLabelForValue(enm), insertText: this.getTextForValue(enm), documentation: '' })); } else if (schema.type === 'boolean') { this.addBooleanSuggestion(true, collector); this.addBooleanSuggestion(false, collector); } if (Array.isArray(schema.allOf)) { schema.allOf.forEach((s) => this.addEnumSuggestion(s, collector)); } if (Array.isArray(schema.anyOf)) { schema.anyOf.forEach((s) => this.addEnumSuggestion(s, collector)); } if (Array.isArray(schema.oneOf)) { schema.oneOf.forEach((s) => this.addEnumSuggestion(s, collector)); } } private addDefaultSuggestion(schema: JsonSchema.IJSONSchema, collector: ISuggestionsCollector): void { if (schema.default) { collector.add({ kind: this.getSuggestionKind(schema.type), label: this.getLabelForValue(schema.default), insertText: this.getTextForValue(schema.default), detail: nls.localize('json.suggest.default', 'Default value'), }); } if (Array.isArray(schema.allOf)) { schema.allOf.forEach((s) => this.addDefaultSuggestion(s, collector)); } if (Array.isArray(schema.anyOf)) { schema.anyOf.forEach((s) => this.addDefaultSuggestion(s, collector)); } if (Array.isArray(schema.oneOf)) { schema.oneOf.forEach((s) => this.addDefaultSuggestion(s, collector)); } } private getLabelForValue(value: any): string { let label = JSON.stringify(value); label = label.replace('{{', '').replace('}}', ''); if (label.length > 57) { return label.substr(0, 57).trim() + '...'; } return label; } private getTextForValue(value: any): string { return JSON.stringify(value, null, '\t'); } private getSnippetForValue(value: any): string { let snippet = JSON.stringify(value, null, '\t'); switch (typeof value) { case 'object': if (value === null) { return '{{null}}'; } return snippet; case 'string': return '"{{' + snippet.substr(1, snippet.length - 2) + '}}"'; case 'number': case 'boolean': return '{{' + snippet + '}}'; } return snippet; } private getSuggestionKind(type: any): CompletionItemKind { if (Array.isArray(type)) { let array = <any[]>type; type = array.length > 0 ? array[0] : null; } if (!type) { return CompletionItemKind.Text; } switch (type) { case 'string': return CompletionItemKind.Text; case 'object': return CompletionItemKind.Module; case 'property': return CompletionItemKind.Property; default: return CompletionItemKind.Value } } private getMatchingSnippet(node: Parser.ASTNode, document: ITextDocument): string { switch (node.type) { case 'array': return '[]'; case 'object': return '{}'; default: let content = document.getText().substr(node.start, node.end - node.start); return content; } } private getSnippetForProperty(key: string, propertySchema: JsonSchema.IJSONSchema, addValue: boolean, isLast: boolean): string { let result = '"' + key + '"'; if (!addValue) { return result; } result += ': '; if (propertySchema) { let defaultVal = propertySchema.default; if (typeof defaultVal !== 'undefined') { result = result + this.getSnippetForValue(defaultVal); } else if (propertySchema.enum && propertySchema.enum.length > 0) { result = result + this.getSnippetForValue(propertySchema.enum[0]); } else { switch (propertySchema.type) { case 'boolean': result += '{{false}}'; break; case 'string': result += '"{{}}"'; break; case 'object': result += '{\n\t{{}}\n}'; break; case 'array': result += '[\n\t{{}}\n]'; break; case 'number': result += '{{0}}'; break; case 'null': result += '{{null}}'; break; default: return result; } } } else { result += '{{0}}'; } if (!isLast) { result += ','; } return result; } private getSnippetForSimilarProperty(key: string, templateValue: Parser.ASTNode): string { return '"' + key + '"'; } private getCurrentWord(document: ITextDocument, offset: number) { var i = offset - 1; var text = document.getText(); while (i >= 0 && ' \t\n\r\v":{[,'.indexOf(text.charAt(i)) === -1) { i--; } return text.substring(i+1, offset); } }
extensions/json/server/src/jsonCompletion.ts
0
https://github.com/microsoft/vscode/commit/8435ddcf464fd995936ff6f877ff4744dc3ca2b6
[ 0.00017686279898043722, 0.0001704312744550407, 0.00016184212290681899, 0.00017106726591009647, 0.000003583635816539754 ]
{ "id": 9, "code_window": [ "\t\tconst newDocument = parser.parseFromString(html, 'text/html');\n", "\t\tconst styleElement = Integration.defaultStyle(this._iFrameElement.parentElement, this._storageService.get(Preferences.THEME, StorageScope.GLOBAL, DEFAULT_THEME_ID));\n", "\t\tif (newDocument.head.hasChildNodes()) {\n", "\t\t\tnewDocument.head.insertBefore(styleElement, newDocument.head.firstChild);\n", "\t\t} else {\n", "\t\t\tnewDocument.head.appendChild(styleElement)\n", "\t\t}\n", "\n", "\t\tif (newDocument.head.innerHTML !== iFrameDocument.head.innerHTML) {\n", "\t\t\tiFrameDocument.head.innerHTML = newDocument.head.innerHTML;\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tnewDocument.head.appendChild(styleElement);\n" ], "file_path": "src/vs/workbench/parts/html/browser/htmlPreviewPart.ts", "type": "replace", "edit_start_line_idx": 185 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import 'vs/editor/standalone-languages/all'; import './standaloneSchemas'; import Colorizer = require('vs/editor/browser/standalone/colorizer'); import standaloneCodeEditor = require('vs/editor/browser/standalone/standaloneCodeEditor'); import EditorCommon = require('vs/editor/common/editorCommon'); import EditorBrowser = require('vs/editor/browser/editorBrowser'); import {ILanguageDef} from 'vs/editor/standalone-languages/types'; import {IJSONSchema} from 'vs/base/common/jsonSchema'; var global:any = self; if (!global.Monaco) { global.Monaco = {}; } var Monaco = global.Monaco; if (!Monaco.Editor) { Monaco.Editor = {}; } Monaco.Editor.setupServices = standaloneCodeEditor.setupServices; Monaco.Editor.getAPI = standaloneCodeEditor.getAPI; Monaco.Editor.create = standaloneCodeEditor.create; Monaco.Editor.createModel = standaloneCodeEditor.createModel; Monaco.Editor.createDiffEditor = standaloneCodeEditor.createDiffEditor; Monaco.Editor.configureMode = standaloneCodeEditor.configureMode; Monaco.Editor.registerWorkerParticipant = standaloneCodeEditor.registerWorkerParticipant; Monaco.Editor.getOrCreateMode = standaloneCodeEditor.getOrCreateMode; Monaco.Editor.createCustomMode = standaloneCodeEditor.createCustomMode; Monaco.Editor.colorize = standaloneCodeEditor.colorize; Monaco.Editor.colorizeElement = standaloneCodeEditor.colorizeElement; Monaco.Editor.colorizeLine = Colorizer.colorizeLine; Monaco.Editor.colorizeModelLine = Colorizer.colorizeModelLine; // -- export common constants Monaco.Editor.SelectionDirection = EditorCommon.SelectionDirection; Monaco.Editor.WrappingIndent = EditorCommon.WrappingIndent; Monaco.Editor.wrappingIndentFromString = EditorCommon.wrappingIndentFromString; Monaco.Editor.OverviewRulerLane = EditorCommon.OverviewRulerLane; Monaco.Editor.EndOfLinePreference = EditorCommon.EndOfLinePreference; Monaco.Editor.EndOfLineSequence = EditorCommon.EndOfLineSequence; Monaco.Editor.LineTokensBinaryEncoding = EditorCommon.LineTokensBinaryEncoding; Monaco.Editor.TrackedRangeStickiness = EditorCommon.TrackedRangeStickiness; Monaco.Editor.VerticalRevealType = EditorCommon.VerticalRevealType; Monaco.Editor.MouseTargetType = EditorCommon.MouseTargetType; Monaco.Editor.KEYBINDING_CONTEXT_EDITOR_TEXT_FOCUS = EditorCommon.KEYBINDING_CONTEXT_EDITOR_TEXT_FOCUS; Monaco.Editor.KEYBINDING_CONTEXT_EDITOR_FOCUS = EditorCommon.KEYBINDING_CONTEXT_EDITOR_FOCUS; Monaco.Editor.KEYBINDING_CONTEXT_EDITOR_TAB_MOVES_FOCUS = EditorCommon.KEYBINDING_CONTEXT_EDITOR_TAB_MOVES_FOCUS; Monaco.Editor.KEYBINDING_CONTEXT_EDITOR_HAS_MULTIPLE_SELECTIONS = EditorCommon.KEYBINDING_CONTEXT_EDITOR_HAS_MULTIPLE_SELECTIONS; Monaco.Editor.KEYBINDING_CONTEXT_EDITOR_HAS_NON_EMPTY_SELECTION = EditorCommon.KEYBINDING_CONTEXT_EDITOR_HAS_NON_EMPTY_SELECTION; Monaco.Editor.KEYBINDING_CONTEXT_EDITOR_LANGUAGE_ID = EditorCommon.KEYBINDING_CONTEXT_EDITOR_LANGUAGE_ID; Monaco.Editor.ViewEventNames = EditorCommon.ViewEventNames; Monaco.Editor.CodeEditorStateFlag = EditorCommon.CodeEditorStateFlag; Monaco.Editor.EditorType = EditorCommon.EditorType; Monaco.Editor.ClassName = EditorCommon.ClassName; Monaco.Editor.EventType = EditorCommon.EventType; Monaco.Editor.Handler = EditorCommon.Handler; // -- export browser constants Monaco.Editor.ClassNames = EditorBrowser.ClassNames; Monaco.Editor.ContentWidgetPositionPreference = EditorBrowser.ContentWidgetPositionPreference; Monaco.Editor.OverlayWidgetPositionPreference = EditorBrowser.OverlayWidgetPositionPreference; // Register all built-in standalone languages let MonacoEditorLanguages: ILanguageDef[] = this.MonacoEditorLanguages || []; MonacoEditorLanguages.forEach((language) => { standaloneCodeEditor.registerStandaloneLanguage(language, language.defModule); }); // Register all built-in standalone JSON schemas let MonacoEditorSchemas: { [url:string]: IJSONSchema } = this.MonacoEditorSchemas || {}; for (var uri in MonacoEditorSchemas) { standaloneCodeEditor.registerStandaloneSchema(uri, MonacoEditorSchemas[uri]); }
src/vs/editor/browser/standalone/standaloneEditor.ts
0
https://github.com/microsoft/vscode/commit/8435ddcf464fd995936ff6f877ff4744dc3ca2b6
[ 0.0002587836643215269, 0.00018453110533300787, 0.00017103251593653113, 0.00017525158182252198, 0.00002811545527947601 ]
{ "id": 9, "code_window": [ "\t\tconst newDocument = parser.parseFromString(html, 'text/html');\n", "\t\tconst styleElement = Integration.defaultStyle(this._iFrameElement.parentElement, this._storageService.get(Preferences.THEME, StorageScope.GLOBAL, DEFAULT_THEME_ID));\n", "\t\tif (newDocument.head.hasChildNodes()) {\n", "\t\t\tnewDocument.head.insertBefore(styleElement, newDocument.head.firstChild);\n", "\t\t} else {\n", "\t\t\tnewDocument.head.appendChild(styleElement)\n", "\t\t}\n", "\n", "\t\tif (newDocument.head.innerHTML !== iFrameDocument.head.innerHTML) {\n", "\t\t\tiFrameDocument.head.innerHTML = newDocument.head.innerHTML;\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tnewDocument.head.appendChild(styleElement);\n" ], "file_path": "src/vs/workbench/parts/html/browser/htmlPreviewPart.ts", "type": "replace", "edit_start_line_idx": 185 }
{ "comments": { "lineComment": "//", // "#" "blockComment": [ "/*", "*/" ] }, "brackets": [ ["{", "}"], ["[", "]"], ["(", ")"] ] }
extensions/php/php.configuration.json
0
https://github.com/microsoft/vscode/commit/8435ddcf464fd995936ff6f877ff4744dc3ca2b6
[ 0.00017375043535139412, 0.00017254726844839752, 0.00017134411609731615, 0.00017254726844839752, 0.0000012031596270389855 ]
{ "id": 10, "code_window": [ "\t\t'::-webkit-scrollbar-thumb:active {',\n", "\t\t'\tbackground-color: rgba(85, 85, 85, 0.8);',\n", "\t\t'}'\n", "\t].join('\\n')\n", "\n", "\texport function defaultStyle(element: HTMLElement, themeId: string): HTMLStyleElement {\n", "\t\tconst styles = window.getComputedStyle(element);\n", "\t\tconst styleElement = document.createElement('style');\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t].join('\\n');\n" ], "file_path": "src/vs/workbench/parts/html/browser/htmlPreviewPart.ts", "type": "replace", "edit_start_line_idx": 298 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ .monaco-shell { height: 100%; width: 100%; color: #6C6C6C; margin: 0; padding: 0; overflow: hidden; font-family: "Segoe WPC", "Segoe UI", "SFUIText-Light", "HelveticaNeue-Light", sans-serif, "Droid Sans Fallback"; font-size: 11px; -webkit-user-select: none; -ms-user-select: none; -khtml-user-select: none; -moz-user-select: -moz-none; -o-user-select: none; user-select: none; } @-webkit-keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } } @-moz-keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } } @-ms-keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } } @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } } .monaco-shell img { border: 0; } .monaco-shell label { cursor: pointer; } .monaco-shell a { text-decoration: none; } .monaco-shell a.plain { color: inherit; text-decoration: none; } .monaco-shell a.plain:hover, .monaco-shell a.plain.hover { color: inherit; text-decoration: none; } /* START Keyboard Focus Indication Styles */ .monaco-shell.vs [tabindex="0"]:focus, .monaco-shell.vs .synthetic-focus, .monaco-shell.vs select:focus, .monaco-shell.vs input[type="button"]:focus, .monaco-shell.vs input[type="submit"]:focus, .monaco-shell.vs input[type="text"]:focus, .monaco-shell.vs textarea:focus, .monaco-shell.vs input[type="checkbox"]:focus { outline: 1px solid rgba(0, 122, 204, 0.4); outline-offset: -1px; opacity: 1 !important; } .monaco-shell.vs-dark [tabindex="0"]:focus, .monaco-shell.vs-dark .synthetic-focus, .monaco-shell.vs-dark select:focus, .monaco-shell.vs-dark input[type="button"]:focus, .monaco-shell.vs-dark input[type="submit"]:focus, .monaco-shell.vs-dark input[type="text"]:focus, .monaco-shell.vs-dark textarea:focus, .monaco-shell.vs-dark input[type="checkbox"]:focus { outline: 1px solid rgba(14, 99, 156, 0.6); outline-offset: -1px; opacity: 1 !important; } .monaco-shell.hc-black [tabindex="0"]:focus, .monaco-shell.hc-black .synthetic-focus, .monaco-shell.hc-black select:focus, .monaco-shell.hc-black input[type="button"]:focus, .monaco-shell.hc-black input[type="submit"]:focus, .monaco-shell.hc-black input[type="text"]:focus, .monaco-shell.hc-black textarea:focus, .monaco-shell.hc-black input[type="checkbox"]:focus { outline: 2px solid #DF740C; outline-offset: -2px; } .monaco-shell.vs .monaco-tree.focused .monaco-tree-row.focused [tabindex="0"]:focus { outline: 1px solid #007ACC; /* higher contrast color for focusable elements in a row that shows focus feedback */ } .monaco-shell.vs-dark .monaco-tree.focused .monaco-tree-row.focused [tabindex="0"]:focus { outline: 1px solid #007ACC; /* higher contrast color for focusable elements in a row that shows focus feedback */ } .monaco-shell .monaco-tree.focused.no-item-focus:focus:before { position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: 5; /* make sure we are on top of the tree items */ content: ""; pointer-events: none; /* enable click through */ } .monaco-shell.vs .monaco-tree.focused.no-item-focus:focus:before { outline: 1px solid rgba(0, 122, 204, 0.4); /* we still need to handle the empty tree or no focus item case */ outline-offset: -1px; } .monaco-shell.vs-dark .monaco-tree.focused.no-item-focus:focus:before { outline: 1px solid rgba(14, 99, 156, 0.6); /* we still need to handle the empty tree or no focus item case */ outline-offset: -1px; } .monaco-shell.hc-black .monaco-tree.focused.no-item-focus:focus:before { outline: 2px solid #DF740C; /* we still need to handle the empty tree or no focus item case */ outline-offset: -2px; } .monaco-shell .synthetic-focus :focus { outline: 0 !important; /* elements within widgets that draw synthetic-focus should never show focus */ } .monaco-shell .monaco-inputbox.info.synthetic-focus, .monaco-shell .monaco-inputbox.warning.synthetic-focus, .monaco-shell .monaco-inputbox.error.synthetic-focus, .monaco-shell .monaco-inputbox.info input[type="text"]:focus, .monaco-shell .monaco-inputbox.warning input[type="text"]:focus, .monaco-shell .monaco-inputbox.error input[type="text"]:focus { outline: 0 !important; /* outline is not going well with decoration */ } .monaco-shell .monaco-tree.focused:focus { outline: 0; /* tree indicates focus not via outline but through the focussed item */ } .monaco-shell [tabindex="0"]:active, .monaco-shell select:active, .monaco-shell input[type="button"]:active, .monaco-shell input[type="submit"]:active, .monaco-shell input[type="checkbox"]:active, .monaco-shell .monaco-tree.focused.no-item-focus:active:before { outline: 0 !important; /* fixes some flashing outlines from showing up when clicking */ } .monaco-shell .activitybar [tabindex="0"]:focus { outline: 0; /* activity bar indicates focus custom */ } /* END Keyboard Focus Indication Styles */ .monaco-shell a.prominent { text-decoration: underline; } .monaco-shell a.strong { font-weight: bold; } a:active { color: inherit; background-color: inherit; } .monaco-shell input { font-family: "Segoe UI", "SFUIText-Light", "HelveticaNeue-Light", sans-serif, "Droid Sans Fallback"; color: inherit; } .monaco-shell select { font-family: "Segoe UI","SFUIText-Light", "HelveticaNeue-Light", sans-serif, "Droid Sans Fallback"; } .monaco-shell .pointer { cursor: pointer; } .monaco-shell .context-view .tooltip { background-color: white; border: 1px solid #ccc; } .monaco-shell .context-view.bottom.right .tooltip:before { border-width: 6px; border-bottom: 6px solid #ccc; } .monaco-shell .context-view.bottom.right .tooltip:after { border-width: 5px; border-bottom: 5px solid white; } .monaco-shell .context-view .monaco-menu .actions-container { min-width: 160px; } .monaco-shell .monaco-menu .action-label.check { font-weight: bold; } .monaco-shell .monaco-menu .action-label.uncheck { font-weight: normal; } /* Notifications */ .monaco-shell .monaco-notification-container { position: absolute; width: 100%; height: 400px; top: calc(50% - 200px); top: -moz-calc(50% - 200px); top: -webkit-calc(50% - 200px); top: -ms-calc(50% - 200px); top: -o-calc(50% - 200px); background-color: #0E6198; color: white; border-top: 2px solid transparent; border-bottom: 2px solid transparent; } .monaco-shell .monaco-notification-container a { color: inherit; opacity: 0.6; text-decoration: underline; } .monaco-shell .monaco-notification-container .buttons { margin-top: 2em; } .monaco-shell .monaco-notification-container button { color: inherit; text-decoration: none; display: inline-block; padding: 6px 16px; margin-right: 12px; font-family: 'Segoe UI Semibold', "Segoe UI", "SFUIText-Light", "HelveticaNeue-Light", sans-serif, "Droid Sans Fallback"; font-weight: 400; font-size: 12px; min-width: 65px; border: 2px solid #fff; background-color: transparent; -moz-box-sizing: border-box; box-sizing: border-box; cursor: pointer; } .monaco-shell .monaco-notification-container button.default { background-color: rgba(255, 255, 255, 0.2); } .monaco-shell .monaco-notification-container button:disabled { opacity: 0.4; } .monaco-shell .monaco-notification-container button:not(:disabled):hover { color: inherit; background-color: rgba(255, 255, 255, 0.1); } .monaco-shell .monaco-notification-container button.default:not(:disabled)hover { background-color: rgba(255, 255, 255, 0.3); } .monaco-shell .monaco-notification-container > .notification { max-width: 800px; height: 100%; margin: 0 auto; padding: 0 16px; overflow-y: auto; overflow-x: hidden; font-family: "Segoe WPC", "Segoe UI", "SFUIText-Light", "HelveticaNeue-Light", sans-serif, "Droid Sans Fallback"; font-size: 14px; } .monaco-shell .monaco-notification-container > .notification > .notification-title { font-family: "Segoe UI Light", "Segoe UI", "SFUIText-Light", "HelveticaNeue-Light", "Helvetica Neue", sans-serif, "Droid Sans Fallback"; font-weight: 300; font-size: 2.5em; } .monaco-shell input:disabled { background-color: #E1E1E1; } /** * Dark Theme */ .monaco-shell.vs-dark { color: #BBB; background-color: #1E1E1E; } .monaco-shell.vs-dark .monaco-action-bar.vertical .action-label.separator { border-bottom-color: #666; } .monaco-shell.vs-dark .context-view .tooltip { background-color: #1E1E1E; border-color: #707070; } .monaco-shell.vs-dark .context-view.bottom.right .tooltip:before { border-bottom: 6px solid #707070; } .monaco-shell.vs-dark .context-view.bottom.right .tooltip:after { border-bottom: 5px solid #1E1E1E; } .monaco-shell.vs-dark input:disabled { background-color: #333; } /** * High Contrast Theme */ .monaco-shell.hc-black { color: #fff; background-color: #000; } .monaco-shell.hc-black .monaco-modal-view.visible .monaco-modal-view-background { opacity: 0.6; } .monaco-shell.hc-black .monaco-notification-container { background-color: #0C141F; color: white; border-top: 2px solid #6FC3DF; border-bottom: 2px solid #6FC3DF; } .monaco-shell.hc-black .monaco-notification-container input { background-color: #000; } .monaco-shell.hc-black .context-view .tooltip { background-color: black; } .monaco-shell.hc-black .context-view .tooltip:before { border-width: 0 !important; } .monaco-shell.hc-black .context-view .tooltip:after { border-width: 0 !important; }
src/vs/workbench/electron-browser/media/shell.css
1
https://github.com/microsoft/vscode/commit/8435ddcf464fd995936ff6f877ff4744dc3ca2b6
[ 0.00017586123431101441, 0.0001701514993328601, 0.0001663438306422904, 0.00017016111814882606, 0.0000021379839836299652 ]
{ "id": 10, "code_window": [ "\t\t'::-webkit-scrollbar-thumb:active {',\n", "\t\t'\tbackground-color: rgba(85, 85, 85, 0.8);',\n", "\t\t'}'\n", "\t].join('\\n')\n", "\n", "\texport function defaultStyle(element: HTMLElement, themeId: string): HTMLStyleElement {\n", "\t\tconst styles = window.getComputedStyle(element);\n", "\t\tconst styleElement = document.createElement('style');\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t].join('\\n');\n" ], "file_path": "src/vs/workbench/parts/html/browser/htmlPreviewPart.ts", "type": "replace", "edit_start_line_idx": 298 }
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 -1 16 16" enable-background="new 0 -1 16 16"><path fill="#C5C5C5" d="M1 1v12h14v-12h-14zm1 3h4.999v8h-4.999v-8zm12 8h-5.001v-8h5.001v8z"/></svg>
src/vs/workbench/parts/files/browser/media/SplitEditor_inverse.svg
0
https://github.com/microsoft/vscode/commit/8435ddcf464fd995936ff6f877ff4744dc3ca2b6
[ 0.0001708817289909348, 0.0001708817289909348, 0.0001708817289909348, 0.0001708817289909348, 0 ]
{ "id": 10, "code_window": [ "\t\t'::-webkit-scrollbar-thumb:active {',\n", "\t\t'\tbackground-color: rgba(85, 85, 85, 0.8);',\n", "\t\t'}'\n", "\t].join('\\n')\n", "\n", "\texport function defaultStyle(element: HTMLElement, themeId: string): HTMLStyleElement {\n", "\t\tconst styles = window.getComputedStyle(element);\n", "\t\tconst styleElement = document.createElement('style');\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t].join('\\n');\n" ], "file_path": "src/vs/workbench/parts/html/browser/htmlPreviewPart.ts", "type": "replace", "edit_start_line_idx": 298 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import net = require('net'); import { IDisposable } from 'vs/base/common/lifecycle'; import { Server as IPCServer, Client as IPCClient, IServiceCtor, IServiceMap, IMessagePassingProtocol } from 'vs/base/common/service'; import { TPromise } from 'vs/base/common/winjs.base'; function bufferIndexOf(buffer: Buffer, value: number, start = 0) { while (start < buffer.length && buffer[start] !== value) { start++; } return start; } class Protocol implements IMessagePassingProtocol { private static Boundary = new Buffer([0]); private buffer: Buffer; constructor(private socket: net.Socket) { this.buffer = null; } public send(message: any): void { this.socket.write(JSON.stringify(message)); this.socket.write(Protocol.Boundary); } public onMessage(callback: (message: any) => void): void { this.socket.on('data', (data: Buffer) => { let lastIndex = 0; let index = 0; while ((index = bufferIndexOf(data, 0, lastIndex)) < data.length) { const dataToParse = data.slice(lastIndex, index); if (this.buffer) { callback(JSON.parse(Buffer.concat([this.buffer, dataToParse]).toString('utf8'))); this.buffer = null; } else { callback(JSON.parse(dataToParse.toString('utf8'))); } lastIndex = index + 1; } if (index - lastIndex > 0) { const dataToBuffer = data.slice(lastIndex, index); if (this.buffer) { this.buffer = Buffer.concat([this.buffer, dataToBuffer]); } else { this.buffer = dataToBuffer; } } }); } } export class Server implements IDisposable { private services: IServiceMap; constructor(private server: net.Server) { this.services = Object.create(null); this.server.on('connection', (socket: net.Socket) => { const ipcServer = new IPCServer(new Protocol(socket)); Object.keys(this.services) .forEach(name => ipcServer.registerService(name, this.services[name])); socket.once('close', () => ipcServer.dispose()); }); } registerService<TService>(serviceName: string, service: TService) { this.services[serviceName] = service; } dispose(): void { this.services = null; this.server.close(); this.server = null; } } export class Client implements IDisposable { private ipcClient: IPCClient; constructor(private socket: net.Socket) { this.ipcClient = new IPCClient(new Protocol(socket)); } getService<TService>(serviceName: string, serviceCtor: IServiceCtor<TService>): TService { return this.ipcClient.getService(serviceName, serviceCtor); } dispose(): void { this.socket.end(); this.socket = null; this.ipcClient = null; } } export function serve(port: number): TPromise<Server>; export function serve(namedPipe: string): TPromise<Server>; export function serve(hook: any): TPromise<Server> { return new TPromise<Server>((c, e) => { const server = net.createServer(); server.on('error', e); server.listen(hook, () => { server.removeListener('error', e); c(new Server(server)); }); }); } export function connect(port: number): TPromise<Client>; export function connect(namedPipe: string): TPromise<Client>; export function connect(hook: any): TPromise<Client> { return new TPromise<Client>((c, e) => { const socket = net.createConnection(hook, () => { socket.removeListener('error', e); c(new Client(socket)); }); socket.once('error', e); }); }
src/vs/base/node/service.net.ts
0
https://github.com/microsoft/vscode/commit/8435ddcf464fd995936ff6f877ff4744dc3ca2b6
[ 0.00017731060506775975, 0.00017077951633837074, 0.00016617974324617535, 0.00017029885202646255, 0.0000030256710488174576 ]
{ "id": 10, "code_window": [ "\t\t'::-webkit-scrollbar-thumb:active {',\n", "\t\t'\tbackground-color: rgba(85, 85, 85, 0.8);',\n", "\t\t'}'\n", "\t].join('\\n')\n", "\n", "\texport function defaultStyle(element: HTMLElement, themeId: string): HTMLStyleElement {\n", "\t\tconst styles = window.getComputedStyle(element);\n", "\t\tconst styleElement = document.createElement('style');\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t].join('\\n');\n" ], "file_path": "src/vs/workbench/parts/html/browser/htmlPreviewPart.ts", "type": "replace", "edit_start_line_idx": 298 }
<svg width="16" height="16" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><g fill="none" fill-rule="evenodd"><g fill="#9CCE9C"><g><path d="M10.188 3H5.375C2.96 3 1 5.24 1 8s1.96 5 4.375 5h5.25L16 8l-5.375-5h-.438z"/></g></g></g></svg>
src/vs/workbench/parts/debug/browser/media/stackframe-arrow-dark.svg
0
https://github.com/microsoft/vscode/commit/8435ddcf464fd995936ff6f877ff4744dc3ca2b6
[ 0.00017148468759842217, 0.00017148468759842217, 0.00017148468759842217, 0.00017148468759842217, 0 ]
{ "id": 0, "code_window": [ " for (var i = 0; i < options.targets.length; i++) {\n", " target = options.targets[i];\n", " if (target.hide) {return;}\n", "\n", " var esQuery = angular.toJson(this.queryBuilder.build(target));\n", " esQuery = esQuery.replace(\"$lucene_query\", target.query || '*');\n", "\n", " payload += header + '\\n' + esQuery + '\\n';\n", " sentTargets.push(target);\n", " }\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " var luceneQuery = angular.toJson(target.query || '*');\n", " // remove inner quotes\n", " luceneQuery = luceneQuery.substr(1, luceneQuery.length - 2);\n", " esQuery = esQuery.replace(\"$lucene_query\", luceneQuery);\n" ], "file_path": "public/app/plugins/datasource/elasticsearch/datasource.js", "type": "replace", "edit_start_line_idx": 161 }
///<amd-dependency path="../datasource" /> ///<amd-dependency path="test/specs/helpers" name="helpers" /> import {describe, beforeEach, it, sinon, expect, angularMocks} from 'test/lib/common'; import moment = require('moment'); import angular = require('angular'); declare var helpers: any; describe('ElasticDatasource', function() { var ctx = new helpers.ServiceTestContext(); beforeEach(angularMocks.module('grafana.services')); beforeEach(ctx.providePhase(['templateSrv', 'backendSrv'])); beforeEach(ctx.createService('ElasticDatasource')); beforeEach(function() { ctx.ds = new ctx.service({jsonData: {}}); }); describe('When testing datasource with index pattern', function() { beforeEach(function() { ctx.ds = new ctx.service({ url: 'http://es.com', index: '[asd-]YYYY.MM.DD', jsonData: { interval: 'Daily' } }); }); it('should translate index pattern to current day', function() { var requestOptions; ctx.backendSrv.datasourceRequest = function(options) { requestOptions = options; return ctx.$q.when({}); }; ctx.ds.testDatasource(); ctx.$rootScope.$apply(); var today = moment().format("YYYY.MM.DD"); expect(requestOptions.url).to.be("http://es.com/asd-" + today + '/_stats'); }); }); describe('When issueing metric query with interval pattern', function() { beforeEach(function() { ctx.ds = new ctx.service({ url: 'http://es.com', index: '[asd-]YYYY.MM.DD', jsonData: { interval: 'Daily' } }); }); it('should translate index pattern to current day', function() { var requestOptions; ctx.backendSrv.datasourceRequest = function(options) { requestOptions = options; return ctx.$q.when({data: {responses: []}}); }; ctx.ds.query({ range: { from: moment([2015, 4, 30, 10]), to: moment([2015, 5, 1, 10]) }, targets: [{ bucketAggs: [], metrics: [] }] }); ctx.$rootScope.$apply(); var parts = requestOptions.data.split('\n'); var header = angular.fromJson(parts[0]); expect(header.index).to.eql(['asd-2015.05.30', 'asd-2015.05.31', 'asd-2015.06.01']); }); }); });
public/app/plugins/datasource/elasticsearch/specs/datasource_specs.ts
1
https://github.com/grafana/grafana/commit/ae93f2b936cda93b8141a6ff61adb18037aca4ab
[ 0.0011635608971118927, 0.00029465719126164913, 0.0001639929978409782, 0.00017271691467612982, 0.00032843847293406725 ]
{ "id": 0, "code_window": [ " for (var i = 0; i < options.targets.length; i++) {\n", " target = options.targets[i];\n", " if (target.hide) {return;}\n", "\n", " var esQuery = angular.toJson(this.queryBuilder.build(target));\n", " esQuery = esQuery.replace(\"$lucene_query\", target.query || '*');\n", "\n", " payload += header + '\\n' + esQuery + '\\n';\n", " sentTargets.push(target);\n", " }\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " var luceneQuery = angular.toJson(target.query || '*');\n", " // remove inner quotes\n", " luceneQuery = luceneQuery.substr(1, luceneQuery.length - 2);\n", " esQuery = esQuery.replace(\"$lucene_query\", luceneQuery);\n" ], "file_path": "public/app/plugins/datasource/elasticsearch/datasource.js", "type": "replace", "edit_start_line_idx": 161 }
To build the docs locally, you need to have docker installed. The docs are built using a custom [docker](https://www.docker.com/) image and [mkdocs](http://www.mkdocs.org/). Build the `grafana/docs-base:latest` image: ``` $ git clone https://github.com/grafana/docs-base $ cd docs-base $ make docs-build ``` To build the docs: ``` $ cd docs $ make docs ``` Open [localhost:8180](http://localhost:8180) to view the docs.
docs/README.md
0
https://github.com/grafana/grafana/commit/ae93f2b936cda93b8141a6ff61adb18037aca4ab
[ 0.00017117591050919145, 0.00017007699352689087, 0.00016897806199267507, 0.00017007699352689087, 0.0000010989242582581937 ]
{ "id": 0, "code_window": [ " for (var i = 0; i < options.targets.length; i++) {\n", " target = options.targets[i];\n", " if (target.hide) {return;}\n", "\n", " var esQuery = angular.toJson(this.queryBuilder.build(target));\n", " esQuery = esQuery.replace(\"$lucene_query\", target.query || '*');\n", "\n", " payload += header + '\\n' + esQuery + '\\n';\n", " sentTargets.push(target);\n", " }\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " var luceneQuery = angular.toJson(target.query || '*');\n", " // remove inner quotes\n", " luceneQuery = luceneQuery.substr(1, luceneQuery.length - 2);\n", " esQuery = esQuery.replace(\"$lucene_query\", luceneQuery);\n" ], "file_path": "public/app/plugins/datasource/elasticsearch/datasource.js", "type": "replace", "edit_start_line_idx": 161 }
define([ "../Data" ], function( Data ) { return new Data(); });
public/vendor/jquery/src/data/var/data_priv.js
0
https://github.com/grafana/grafana/commit/ae93f2b936cda93b8141a6ff61adb18037aca4ab
[ 0.00016807288920972496, 0.00016807288920972496, 0.00016807288920972496, 0.00016807288920972496, 0 ]
{ "id": 0, "code_window": [ " for (var i = 0; i < options.targets.length; i++) {\n", " target = options.targets[i];\n", " if (target.hide) {return;}\n", "\n", " var esQuery = angular.toJson(this.queryBuilder.build(target));\n", " esQuery = esQuery.replace(\"$lucene_query\", target.query || '*');\n", "\n", " payload += header + '\\n' + esQuery + '\\n';\n", " sentTargets.push(target);\n", " }\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " var luceneQuery = angular.toJson(target.query || '*');\n", " // remove inner quotes\n", " luceneQuery = luceneQuery.substr(1, luceneQuery.length - 2);\n", " esQuery = esQuery.replace(\"$lucene_query\", luceneQuery);\n" ], "file_path": "public/app/plugins/datasource/elasticsearch/datasource.js", "type": "replace", "edit_start_line_idx": 161 }
[target] path = github.com/go-xorm/xorm
Godeps/_workspace/src/github.com/go-xorm/xorm/.gopmfile
0
https://github.com/grafana/grafana/commit/ae93f2b936cda93b8141a6ff61adb18037aca4ab
[ 0.0012639944907277822, 0.0012639944907277822, 0.0012639944907277822, 0.0012639944907277822, 0 ]
{ "id": 1, "code_window": [ " });\n", "\n", " describe('When issueing metric query with interval pattern', function() {\n", " beforeEach(function() {\n", " ctx.ds = new ctx.service({\n", " url: 'http://es.com',\n", " index: '[asd-]YYYY.MM.DD',\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " var requestOptions, parts, header;\n", "\n" ], "file_path": "public/app/plugins/datasource/elasticsearch/specs/datasource_specs.ts", "type": "add", "edit_start_line_idx": 44 }
///<amd-dependency path="../datasource" /> ///<amd-dependency path="test/specs/helpers" name="helpers" /> import {describe, beforeEach, it, sinon, expect, angularMocks} from 'test/lib/common'; import moment = require('moment'); import angular = require('angular'); declare var helpers: any; describe('ElasticDatasource', function() { var ctx = new helpers.ServiceTestContext(); beforeEach(angularMocks.module('grafana.services')); beforeEach(ctx.providePhase(['templateSrv', 'backendSrv'])); beforeEach(ctx.createService('ElasticDatasource')); beforeEach(function() { ctx.ds = new ctx.service({jsonData: {}}); }); describe('When testing datasource with index pattern', function() { beforeEach(function() { ctx.ds = new ctx.service({ url: 'http://es.com', index: '[asd-]YYYY.MM.DD', jsonData: { interval: 'Daily' } }); }); it('should translate index pattern to current day', function() { var requestOptions; ctx.backendSrv.datasourceRequest = function(options) { requestOptions = options; return ctx.$q.when({}); }; ctx.ds.testDatasource(); ctx.$rootScope.$apply(); var today = moment().format("YYYY.MM.DD"); expect(requestOptions.url).to.be("http://es.com/asd-" + today + '/_stats'); }); }); describe('When issueing metric query with interval pattern', function() { beforeEach(function() { ctx.ds = new ctx.service({ url: 'http://es.com', index: '[asd-]YYYY.MM.DD', jsonData: { interval: 'Daily' } }); }); it('should translate index pattern to current day', function() { var requestOptions; ctx.backendSrv.datasourceRequest = function(options) { requestOptions = options; return ctx.$q.when({data: {responses: []}}); }; ctx.ds.query({ range: { from: moment([2015, 4, 30, 10]), to: moment([2015, 5, 1, 10]) }, targets: [{ bucketAggs: [], metrics: [] }] }); ctx.$rootScope.$apply(); var parts = requestOptions.data.split('\n'); var header = angular.fromJson(parts[0]); expect(header.index).to.eql(['asd-2015.05.30', 'asd-2015.05.31', 'asd-2015.06.01']); }); }); });
public/app/plugins/datasource/elasticsearch/specs/datasource_specs.ts
1
https://github.com/grafana/grafana/commit/ae93f2b936cda93b8141a6ff61adb18037aca4ab
[ 0.9974372386932373, 0.13588939607143402, 0.00016593036707490683, 0.00926942192018032, 0.32593590021133423 ]
{ "id": 1, "code_window": [ " });\n", "\n", " describe('When issueing metric query with interval pattern', function() {\n", " beforeEach(function() {\n", " ctx.ds = new ctx.service({\n", " url: 'http://es.com',\n", " index: '[asd-]YYYY.MM.DD',\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " var requestOptions, parts, header;\n", "\n" ], "file_path": "public/app/plugins/datasource/elasticsearch/specs/datasource_specs.ts", "type": "add", "edit_start_line_idx": 44 }
package ldap_test import ( "crypto/tls" "fmt" "log" "github.com/go-ldap/ldap" ) // ExampleConn_Bind demonstrats how to bind a connection to an ldap user // allowing access to restricted attrabutes that user has access to func ExampleConn_Bind() { l, err := ldap.Dial("tcp", fmt.Sprintf("%s:%d", "ldap.example.com", 389)) if err != nil { log.Fatal(err) } defer l.Close() err = l.Bind("cn=read-only-admin,dc=example,dc=com", "password") if err != nil { log.Fatal(err) } } // ExampleConn_Search demonstrates how to use the search interface func ExampleConn_Search() { l, err := ldap.Dial("tcp", fmt.Sprintf("%s:%d", "ldap.example.com", 389)) if err != nil { log.Fatal(err) } defer l.Close() searchRequest := ldap.NewSearchRequest( "dc=example,dc=com", // The base dn to search ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false, "(&(objectClass=organizationalPerson))", // The filter to apply []string{"dn", "cn"}, // A list attributes to retrieve nil, ) sr, err := l.Search(searchRequest) if err != nil { log.Fatal(err) } for _, entry := range sr.Entries { fmt.Printf("%s: %v\n", entry.DN, entry.GetAttributeValue("cn")) } } // ExampleStartTLS demonstrates how to start a TLS connection func ExampleConn_StartTLS() { l, err := ldap.Dial("tcp", fmt.Sprintf("%s:%d", "ldap.example.com", 389)) if err != nil { log.Fatal(err) } defer l.Close() // Reconnect with TLS err = l.StartTLS(&tls.Config{InsecureSkipVerify: true}) if err != nil { log.Fatal(err) } // Opertations via l are now encrypted } // ExampleConn_Compare demonstrates how to comapre an attribute with a value func ExampleConn_Compare() { l, err := ldap.Dial("tcp", fmt.Sprintf("%s:%d", "ldap.example.com", 389)) if err != nil { log.Fatal(err) } defer l.Close() matched, err := l.Compare("cn=user,dc=example,dc=com", "uid", "someuserid") if err != nil { log.Fatal(err) } fmt.Println(matched) } func ExampleConn_PasswordModify_admin() { l, err := ldap.Dial("tcp", fmt.Sprintf("%s:%d", "ldap.example.com", 389)) if err != nil { log.Fatal(err) } defer l.Close() err = l.Bind("cn=admin,dc=example,dc=com", "password") if err != nil { log.Fatal(err) } passwordModifyRequest := ldap.NewPasswordModifyRequest("cn=user,dc=example,dc=com", "", "NewPassword") _, err = l.PasswordModify(passwordModifyRequest) if err != nil { log.Fatalf("Password could not be changed: %s", err.Error()) } } func ExampleConn_PasswordModify_generatedPassword() { l, err := ldap.Dial("tcp", fmt.Sprintf("%s:%d", "ldap.example.com", 389)) if err != nil { log.Fatal(err) } defer l.Close() err = l.Bind("cn=user,dc=example,dc=com", "password") if err != nil { log.Fatal(err) } passwordModifyRequest := ldap.NewPasswordModifyRequest("", "OldPassword", "") passwordModifyResponse, err := l.PasswordModify(passwordModifyRequest) if err != nil { log.Fatalf("Password could not be changed: %s", err.Error()) } generatedPassword := passwordModifyResponse.GeneratedPassword log.Printf("Generated password: %s\n", generatedPassword) } func ExampleConn_PasswordModify_setNewPassword() { l, err := ldap.Dial("tcp", fmt.Sprintf("%s:%d", "ldap.example.com", 389)) if err != nil { log.Fatal(err) } defer l.Close() err = l.Bind("cn=user,dc=example,dc=com", "password") if err != nil { log.Fatal(err) } passwordModifyRequest := ldap.NewPasswordModifyRequest("", "OldPassword", "NewPassword") _, err = l.PasswordModify(passwordModifyRequest) if err != nil { log.Fatalf("Password could not be changed: %s", err.Error()) } } func ExampleConn_Modify() { l, err := ldap.Dial("tcp", fmt.Sprintf("%s:%d", "ldap.example.com", 389)) if err != nil { log.Fatal(err) } defer l.Close() // Add a description, and replace the mail attributes modify := ldap.NewModifyRequest("cn=user,dc=example,dc=com") modify.Add("description", []string{"An example user"}) modify.Replace("mail", []string{"[email protected]"}) err = l.Modify(modify) if err != nil { log.Fatal(err) } } // Example User Authentication shows how a typical application can verify a login attempt func Example_userAuthentication() { // The username and password we want to check username := "someuser" password := "userpassword" bindusername := "readonly" bindpassword := "password" l, err := ldap.Dial("tcp", fmt.Sprintf("%s:%d", "ldap.example.com", 389)) if err != nil { log.Fatal(err) } defer l.Close() // Reconnect with TLS err = l.StartTLS(&tls.Config{InsecureSkipVerify: true}) if err != nil { log.Fatal(err) } // First bind with a read only user err = l.Bind(bindusername, bindpassword) if err != nil { log.Fatal(err) } // Search for the given username searchRequest := ldap.NewSearchRequest( "dc=example,dc=com", ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false, fmt.Sprintf("(&(objectClass=organizationalPerson)&(uid=%s))", username), []string{"dn"}, nil, ) sr, err := l.Search(searchRequest) if err != nil { log.Fatal(err) } if len(sr.Entries) != 1 { log.Fatal("User does not exist or too many entries returned") } userdn := sr.Entries[0].DN // Bind as the user to verify their password err = l.Bind(userdn, password) if err != nil { log.Fatal(err) } // Rebind as the read only user for any futher queries err = l.Bind(bindusername, bindpassword) if err != nil { log.Fatal(err) } } func Example_beherappolicy() { l, err := ldap.Dial("tcp", fmt.Sprintf("%s:%d", "ldap.example.com", 389)) if err != nil { log.Fatal(err) } defer l.Close() controls := []ldap.Control{} controls = append(controls, ldap.NewControlBeheraPasswordPolicy()) bindRequest := ldap.NewSimpleBindRequest("cn=admin,dc=example,dc=com", "password", controls) r, err := l.SimpleBind(bindRequest) ppolicyControl := ldap.FindControl(r.Controls, ldap.ControlTypeBeheraPasswordPolicy) var ppolicy *ldap.ControlBeheraPasswordPolicy if ppolicyControl != nil { ppolicy = ppolicyControl.(*ldap.ControlBeheraPasswordPolicy) } else { log.Printf("ppolicyControl response not avaliable.\n") } if err != nil { errStr := "ERROR: Cannot bind: " + err.Error() if ppolicy != nil && ppolicy.Error >= 0 { errStr += ":" + ppolicy.ErrorString } log.Print(errStr) } else { logStr := "Login Ok" if ppolicy != nil { if ppolicy.Expire >= 0 { logStr += fmt.Sprintf(". Password expires in %d seconds\n", ppolicy.Expire) } else if ppolicy.Grace >= 0 { logStr += fmt.Sprintf(". Password expired, %d grace logins remain\n", ppolicy.Grace) } } log.Print(logStr) } } func Example_vchuppolicy() { l, err := ldap.Dial("tcp", fmt.Sprintf("%s:%d", "ldap.example.com", 389)) if err != nil { log.Fatal(err) } defer l.Close() l.Debug = true bindRequest := ldap.NewSimpleBindRequest("cn=admin,dc=example,dc=com", "password", nil) r, err := l.SimpleBind(bindRequest) passwordMustChangeControl := ldap.FindControl(r.Controls, ldap.ControlTypeVChuPasswordMustChange) var passwordMustChange *ldap.ControlVChuPasswordMustChange if passwordMustChangeControl != nil { passwordMustChange = passwordMustChangeControl.(*ldap.ControlVChuPasswordMustChange) } if passwordMustChange != nil && passwordMustChange.MustChange { log.Printf("Password Must be changed.\n") } passwordWarningControl := ldap.FindControl(r.Controls, ldap.ControlTypeVChuPasswordWarning) var passwordWarning *ldap.ControlVChuPasswordWarning if passwordWarningControl != nil { passwordWarning = passwordWarningControl.(*ldap.ControlVChuPasswordWarning) } else { log.Printf("ppolicyControl response not available.\n") } if err != nil { log.Print("ERROR: Cannot bind: " + err.Error()) } else { logStr := "Login Ok" if passwordWarning != nil { if passwordWarning.Expire >= 0 { logStr += fmt.Sprintf(". Password expires in %d seconds\n", passwordWarning.Expire) } } log.Print(logStr) } }
Godeps/_workspace/src/github.com/go-ldap/ldap/example_test.go
0
https://github.com/grafana/grafana/commit/ae93f2b936cda93b8141a6ff61adb18037aca4ab
[ 0.0004062497755512595, 0.00018695826292969286, 0.0001675637176958844, 0.00017338551697321236, 0.00004706079562311061 ]
{ "id": 1, "code_window": [ " });\n", "\n", " describe('When issueing metric query with interval pattern', function() {\n", " beforeEach(function() {\n", " ctx.ds = new ctx.service({\n", " url: 'http://es.com',\n", " index: '[asd-]YYYY.MM.DD',\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " var requestOptions, parts, header;\n", "\n" ], "file_path": "public/app/plugins/datasource/elasticsearch/specs/datasource_specs.ts", "type": "add", "edit_start_line_idx": 44 }
<topnav icon="fa fa-fw fa-user" title="Global Users" subnav="true"> <ul class="nav"> <li class="active"><a href="admin/users">List</a></li> <li><a href="admin/users/create">Create user</a></li> </ul> </topnav> <div class="page-container"> <div class="page"> <h2> Users </h2> <table class="grafana-options-table"> <tr> <th style="text-align:left">Id</th> <th>Name</th> <th>Login</th> <th>Email</th> <th style="white-space: nowrap">Grafana Admin</th> <th></th> </tr> <tr ng-repeat="user in users"> <td>{{user.id}}</td> <td>{{user.name}}</td> <td>{{user.login}}</td> <td>{{user.email}}</td> <td>{{user.isAdmin}}</td> <td style="width: 1%"> <a href="admin/users/edit/{{user.id}}" class="btn btn-inverse btn-small"> <i class="fa fa-edit"></i> Edit </a> &nbsp;&nbsp; <a ng-click="deleteUser(user)" class="btn btn-danger btn-small"> <i class="fa fa-remove"></i> </a> </td> </tr> </table> </div> </div>
public/app/features/admin/partials/users.html
0
https://github.com/grafana/grafana/commit/ae93f2b936cda93b8141a6ff61adb18037aca4ab
[ 0.00017718150047585368, 0.00017433814355172217, 0.00017171997751574963, 0.00017413438763469458, 0.0000018781113340082811 ]
{ "id": 1, "code_window": [ " });\n", "\n", " describe('When issueing metric query with interval pattern', function() {\n", " beforeEach(function() {\n", " ctx.ds = new ctx.service({\n", " url: 'http://es.com',\n", " index: '[asd-]YYYY.MM.DD',\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " var requestOptions, parts, header;\n", "\n" ], "file_path": "public/app/plugins/datasource/elasticsearch/specs/datasource_specs.ts", "type": "add", "edit_start_line_idx": 44 }
module.exports = function(config) { 'use strict'; return { dev: { configFile: 'karma.conf.js', singleRun: false, }, debug: { configFile: 'karma.conf.js', singleRun: false, browsers: ['Chrome'] }, test: { configFile: 'karma.conf.js', }, coveralls: { configFile: 'karma.conf.js', reporters: ['dots','coverage','coveralls'], preprocessors: { 'public/app/**/*.js': ['coverage'] }, coverageReporter: { type: 'lcov', dir: 'coverage/' } } }; };
tasks/options/karma.js
0
https://github.com/grafana/grafana/commit/ae93f2b936cda93b8141a6ff61adb18037aca4ab
[ 0.0001761762541718781, 0.00017375971947330981, 0.00017011846648529172, 0.00017498443776275963, 0.0000026203242668998428 ]
{ "id": 2, "code_window": [ " index: '[asd-]YYYY.MM.DD',\n", " jsonData: { interval: 'Daily' }\n", " });\n", " });\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep" ], "after_edit": [], "file_path": "public/app/plugins/datasource/elasticsearch/specs/datasource_specs.ts", "type": "replace", "edit_start_line_idx": 50 }
///<amd-dependency path="../index_pattern" name="IndexPattern"/> ///<amd-dependency path="test/specs/helpers" name="helpers" /> import {describe, beforeEach, it, sinon, expect} from 'test/lib/common'; import moment = require('moment'); declare var IndexPattern: any; describe('IndexPattern', function() { describe.only('when getting index for today', function() { it('should return correct index name', function() { var pattern = new IndexPattern('[asd-]YYYY.MM.DD', 'Daily'); var expected = 'asd-' + moment().format('YYYY.MM.DD'); expect(pattern.getIndexForToday()).to.be(expected); }); }); describe('when getting index list for time range', function() { describe('no interval', function() { it('should return correct index', function() { var pattern = new IndexPattern('my-metrics'); var from = new Date(2015, 4, 30, 1, 2, 3); var to = new Date(2015, 5, 1, 12, 5 , 6); expect(pattern.getIndexList(from, to)).to.eql('my-metrics'); }); }); describe('daily', function() { it('should return correct index list', function() { var pattern = new IndexPattern('[asd-]YYYY.MM.DD', 'Daily'); var from = new Date(1432940523000); var to = new Date(1433153106000); var expected = [ 'asd-2015.05.29', 'asd-2015.05.30', 'asd-2015.05.31', 'asd-2015.06.01', ]; expect(pattern.getIndexList(from, to)).to.eql(expected); }); }); }); });
public/app/plugins/datasource/elasticsearch/specs/index_pattern_specs.ts
1
https://github.com/grafana/grafana/commit/ae93f2b936cda93b8141a6ff61adb18037aca4ab
[ 0.00106672546826303, 0.00039426758303306997, 0.00016743132437113672, 0.0002026358706643805, 0.0003301497781649232 ]
{ "id": 2, "code_window": [ " index: '[asd-]YYYY.MM.DD',\n", " jsonData: { interval: 'Daily' }\n", " });\n", " });\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep" ], "after_edit": [], "file_path": "public/app/plugins/datasource/elasticsearch/specs/datasource_specs.ts", "type": "replace", "edit_start_line_idx": 50 }
define([ 'angular', 'lodash', 'kbn', ], function (angular) { 'use strict'; var module = angular.module('grafana.services'); module.factory('SqlDatasource', function() { function SqlDatasource() { } return SqlDatasource; }); });
public/app/plugins/datasource/sql/datasource.js
0
https://github.com/grafana/grafana/commit/ae93f2b936cda93b8141a6ff61adb18037aca4ab
[ 0.00018044319585897028, 0.00017427571583539248, 0.0001648398902034387, 0.00017754407599568367, 0.000006776301688660169 ]
{ "id": 2, "code_window": [ " index: '[asd-]YYYY.MM.DD',\n", " jsonData: { interval: 'Daily' }\n", " });\n", " });\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep" ], "after_edit": [], "file_path": "public/app/plugins/datasource/elasticsearch/specs/datasource_specs.ts", "type": "replace", "edit_start_line_idx": 50 }
package convey import "testing" func TestFocusOnlyAtTopLevel(t *testing.T) { output := prepare() FocusConvey("hi", t, func() { output += "done" }) expectEqual(t, "done", output) } func TestFocus(t *testing.T) { output := prepare() FocusConvey("hi", t, func() { output += "1" Convey("bye", func() { output += "2" }) }) expectEqual(t, "1", output) } func TestNestedFocus(t *testing.T) { output := prepare() FocusConvey("hi", t, func() { output += "1" Convey("This shouldn't run", func() { output += "boink!" }) FocusConvey("This should run", func() { output += "2" FocusConvey("The should run too", func() { output += "3" }) Convey("The should NOT run", func() { output += "blah blah blah!" }) }) }) expectEqual(t, "123", output) } func TestForgotTopLevelFocus(t *testing.T) { output := prepare() Convey("1", t, func() { output += "1" FocusConvey("This will be run because the top-level lacks Focus", func() { output += "2" }) Convey("3", func() { output += "3" }) }) expectEqual(t, "1213", output) }
Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/focused_execution_test.go
0
https://github.com/grafana/grafana/commit/ae93f2b936cda93b8141a6ff61adb18037aca4ab
[ 0.0003793986397795379, 0.00019819129374809563, 0.00016572086315136403, 0.00017381118959747255, 0.00006854776438558474 ]
{ "id": 2, "code_window": [ " index: '[asd-]YYYY.MM.DD',\n", " jsonData: { interval: 'Daily' }\n", " });\n", " });\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep" ], "after_edit": [], "file_path": "public/app/plugins/datasource/elasticsearch/specs/datasource_specs.ts", "type": "replace", "edit_start_line_idx": 50 }
package hstore import ( "database/sql" _ "github.com/lib/pq" "os" "testing" ) type Fatalistic interface { Fatal(args ...interface{}) } func openTestConn(t Fatalistic) *sql.DB { datname := os.Getenv("PGDATABASE") sslmode := os.Getenv("PGSSLMODE") if datname == "" { os.Setenv("PGDATABASE", "pqgotest") } if sslmode == "" { os.Setenv("PGSSLMODE", "disable") } conn, err := sql.Open("postgres", "") if err != nil { t.Fatal(err) } return conn } func TestHstore(t *testing.T) { db := openTestConn(t) defer db.Close() // quitely create hstore if it doesn't exist _, err := db.Exec("CREATE EXTENSION IF NOT EXISTS hstore") if err != nil { t.Skipf("Skipping hstore tests - hstore extension create failed: %s", err.Error()) } hs := Hstore{} // test for null-valued hstores err = db.QueryRow("SELECT NULL::hstore").Scan(&hs) if err != nil { t.Fatal(err) } if hs.Map != nil { t.Fatalf("expected null map") } err = db.QueryRow("SELECT $1::hstore", hs).Scan(&hs) if err != nil { t.Fatalf("re-query null map failed: %s", err.Error()) } if hs.Map != nil { t.Fatalf("expected null map") } // test for empty hstores err = db.QueryRow("SELECT ''::hstore").Scan(&hs) if err != nil { t.Fatal(err) } if hs.Map == nil { t.Fatalf("expected empty map, got null map") } if len(hs.Map) != 0 { t.Fatalf("expected empty map, got len(map)=%d", len(hs.Map)) } err = db.QueryRow("SELECT $1::hstore", hs).Scan(&hs) if err != nil { t.Fatalf("re-query empty map failed: %s", err.Error()) } if hs.Map == nil { t.Fatalf("expected empty map, got null map") } if len(hs.Map) != 0 { t.Fatalf("expected empty map, got len(map)=%d", len(hs.Map)) } // a few example maps to test out hsOnePair := Hstore{ Map: map[string]sql.NullString{ "key1": {"value1", true}, }, } hsThreePairs := Hstore{ Map: map[string]sql.NullString{ "key1": {"value1", true}, "key2": {"value2", true}, "key3": {"value3", true}, }, } hsSmorgasbord := Hstore{ Map: map[string]sql.NullString{ "nullstring": {"NULL", true}, "actuallynull": {"", false}, "NULL": {"NULL string key", true}, "withbracket": {"value>42", true}, "withequal": {"value=42", true}, `"withquotes1"`: {`this "should" be fine`, true}, `"withquotes"2"`: {`this "should\" also be fine`, true}, "embedded1": {"value1=>x1", true}, "embedded2": {`"value2"=>x2`, true}, "withnewlines": {"\n\nvalue\t=>2", true}, "<<all sorts of crazy>>": {`this, "should,\" also, => be fine`, true}, }, } // test encoding in query params, then decoding during Scan testBidirectional := func(h Hstore) { err = db.QueryRow("SELECT $1::hstore", h).Scan(&hs) if err != nil { t.Fatalf("re-query %d-pair map failed: %s", len(h.Map), err.Error()) } if hs.Map == nil { t.Fatalf("expected %d-pair map, got null map", len(h.Map)) } if len(hs.Map) != len(h.Map) { t.Fatalf("expected %d-pair map, got len(map)=%d", len(h.Map), len(hs.Map)) } for key, val := range hs.Map { otherval, found := h.Map[key] if !found { t.Fatalf(" key '%v' not found in %d-pair map", key, len(h.Map)) } if otherval.Valid != val.Valid { t.Fatalf(" value %v <> %v in %d-pair map", otherval, val, len(h.Map)) } if otherval.String != val.String { t.Fatalf(" value '%v' <> '%v' in %d-pair map", otherval.String, val.String, len(h.Map)) } } } testBidirectional(hsOnePair) testBidirectional(hsThreePairs) testBidirectional(hsSmorgasbord) }
Godeps/_workspace/src/github.com/lib/pq/hstore/hstore_test.go
0
https://github.com/grafana/grafana/commit/ae93f2b936cda93b8141a6ff61adb18037aca4ab
[ 0.0001830437540775165, 0.0001717575651127845, 0.00016552803572267294, 0.00017153668159153312, 0.000004000859917141497 ]
{ "id": 3, "code_window": [ "\n", " it('should translate index pattern to current day', function() {\n", " var requestOptions;\n", " ctx.backendSrv.datasourceRequest = function(options) {\n", " requestOptions = options;\n", " return ctx.$q.when({data: {responses: []}});\n" ], "labels": [ "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "public/app/plugins/datasource/elasticsearch/specs/datasource_specs.ts", "type": "replace", "edit_start_line_idx": 52 }
///<amd-dependency path="../index_pattern" name="IndexPattern"/> ///<amd-dependency path="test/specs/helpers" name="helpers" /> import {describe, beforeEach, it, sinon, expect} from 'test/lib/common'; import moment = require('moment'); declare var IndexPattern: any; describe('IndexPattern', function() { describe.only('when getting index for today', function() { it('should return correct index name', function() { var pattern = new IndexPattern('[asd-]YYYY.MM.DD', 'Daily'); var expected = 'asd-' + moment().format('YYYY.MM.DD'); expect(pattern.getIndexForToday()).to.be(expected); }); }); describe('when getting index list for time range', function() { describe('no interval', function() { it('should return correct index', function() { var pattern = new IndexPattern('my-metrics'); var from = new Date(2015, 4, 30, 1, 2, 3); var to = new Date(2015, 5, 1, 12, 5 , 6); expect(pattern.getIndexList(from, to)).to.eql('my-metrics'); }); }); describe('daily', function() { it('should return correct index list', function() { var pattern = new IndexPattern('[asd-]YYYY.MM.DD', 'Daily'); var from = new Date(1432940523000); var to = new Date(1433153106000); var expected = [ 'asd-2015.05.29', 'asd-2015.05.30', 'asd-2015.05.31', 'asd-2015.06.01', ]; expect(pattern.getIndexList(from, to)).to.eql(expected); }); }); }); });
public/app/plugins/datasource/elasticsearch/specs/index_pattern_specs.ts
1
https://github.com/grafana/grafana/commit/ae93f2b936cda93b8141a6ff61adb18037aca4ab
[ 0.00022368747158907354, 0.0001783740590326488, 0.00016634160419926047, 0.0001695921819191426, 0.000020470974050113 ]
{ "id": 3, "code_window": [ "\n", " it('should translate index pattern to current day', function() {\n", " var requestOptions;\n", " ctx.backendSrv.datasourceRequest = function(options) {\n", " requestOptions = options;\n", " return ctx.$q.when({data: {responses: []}});\n" ], "labels": [ "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "public/app/plugins/datasource/elasticsearch/specs/datasource_specs.ts", "type": "replace", "edit_start_line_idx": 52 }
package sqlite3_test import ( "database/sql" "fmt" "math/rand" "regexp" "strconv" "sync" "testing" "time" ) type Dialect int const ( SQLITE Dialect = iota POSTGRESQL MYSQL ) type DB struct { *testing.T *sql.DB dialect Dialect once sync.Once } var db *DB // the following tables will be created and dropped during the test var testTables = []string{"foo", "bar", "t", "bench"} var tests = []testing.InternalTest{ {"TestBlobs", TestBlobs}, {"TestManyQueryRow", TestManyQueryRow}, {"TestTxQuery", TestTxQuery}, {"TestPreparedStmt", TestPreparedStmt}, } var benchmarks = []testing.InternalBenchmark{ {"BenchmarkExec", BenchmarkExec}, {"BenchmarkQuery", BenchmarkQuery}, {"BenchmarkParams", BenchmarkParams}, {"BenchmarkStmt", BenchmarkStmt}, {"BenchmarkRows", BenchmarkRows}, {"BenchmarkStmtRows", BenchmarkStmtRows}, } // RunTests runs the SQL test suite func RunTests(t *testing.T, d *sql.DB, dialect Dialect) { db = &DB{t, d, dialect, sync.Once{}} testing.RunTests(func(string, string) (bool, error) { return true, nil }, tests) if !testing.Short() { for _, b := range benchmarks { fmt.Printf("%-20s", b.Name) r := testing.Benchmark(b.F) fmt.Printf("%10d %10.0f req/s\n", r.N, float64(r.N)/r.T.Seconds()) } } db.tearDown() } func (db *DB) mustExec(sql string, args ...interface{}) sql.Result { res, err := db.Exec(sql, args...) if err != nil { db.Fatalf("Error running %q: %v", sql, err) } return res } func (db *DB) tearDown() { for _, tbl := range testTables { switch db.dialect { case SQLITE: db.mustExec("drop table if exists " + tbl) case MYSQL, POSTGRESQL: db.mustExec("drop table if exists " + tbl) default: db.Fatal("unkown dialect") } } } // q replaces ? parameters if needed func (db *DB) q(sql string) string { switch db.dialect { case POSTGRESQL: // repace with $1, $2, .. qrx := regexp.MustCompile(`\?`) n := 0 return qrx.ReplaceAllStringFunc(sql, func(string) string { n++ return "$" + strconv.Itoa(n) }) } return sql } func (db *DB) blobType(size int) string { switch db.dialect { case SQLITE: return fmt.Sprintf("blob[%d]", size) case POSTGRESQL: return "bytea" case MYSQL: return fmt.Sprintf("VARBINARY(%d)", size) } panic("unkown dialect") } func (db *DB) serialPK() string { switch db.dialect { case SQLITE: return "integer primary key autoincrement" case POSTGRESQL: return "serial primary key" case MYSQL: return "integer primary key auto_increment" } panic("unkown dialect") } func (db *DB) now() string { switch db.dialect { case SQLITE: return "datetime('now')" case POSTGRESQL: return "now()" case MYSQL: return "now()" } panic("unkown dialect") } func makeBench() { if _, err := db.Exec("create table bench (n varchar(32), i integer, d double, s varchar(32), t datetime)"); err != nil { panic(err) } st, err := db.Prepare("insert into bench values (?, ?, ?, ?, ?)") if err != nil { panic(err) } defer st.Close() for i := 0; i < 100; i++ { if _, err = st.Exec(nil, i, float64(i), fmt.Sprintf("%d", i), time.Now()); err != nil { panic(err) } } } func TestResult(t *testing.T) { db.tearDown() db.mustExec("create temporary table test (id " + db.serialPK() + ", name varchar(10))") for i := 1; i < 3; i++ { r := db.mustExec(db.q("insert into test (name) values (?)"), fmt.Sprintf("row %d", i)) n, err := r.RowsAffected() if err != nil { t.Fatal(err) } if n != 1 { t.Errorf("got %v, want %v", n, 1) } n, err = r.LastInsertId() if err != nil { t.Fatal(err) } if n != int64(i) { t.Errorf("got %v, want %v", n, i) } } if _, err := db.Exec("error!"); err == nil { t.Fatalf("expected error") } } func TestBlobs(t *testing.T) { db.tearDown() var blob = []byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15} db.mustExec("create table foo (id integer primary key, bar " + db.blobType(16) + ")") db.mustExec(db.q("insert into foo (id, bar) values(?,?)"), 0, blob) want := fmt.Sprintf("%x", blob) b := make([]byte, 16) err := db.QueryRow(db.q("select bar from foo where id = ?"), 0).Scan(&b) got := fmt.Sprintf("%x", b) if err != nil { t.Errorf("[]byte scan: %v", err) } else if got != want { t.Errorf("for []byte, got %q; want %q", got, want) } err = db.QueryRow(db.q("select bar from foo where id = ?"), 0).Scan(&got) want = string(blob) if err != nil { t.Errorf("string scan: %v", err) } else if got != want { t.Errorf("for string, got %q; want %q", got, want) } } func TestManyQueryRow(t *testing.T) { if testing.Short() { t.Log("skipping in short mode") return } db.tearDown() db.mustExec("create table foo (id integer primary key, name varchar(50))") db.mustExec(db.q("insert into foo (id, name) values(?,?)"), 1, "bob") var name string for i := 0; i < 10000; i++ { err := db.QueryRow(db.q("select name from foo where id = ?"), 1).Scan(&name) if err != nil || name != "bob" { t.Fatalf("on query %d: err=%v, name=%q", i, err, name) } } } func TestTxQuery(t *testing.T) { db.tearDown() tx, err := db.Begin() if err != nil { t.Fatal(err) } defer tx.Rollback() _, err = tx.Exec("create table foo (id integer primary key, name varchar(50))") if err != nil { t.Fatal(err) } _, err = tx.Exec(db.q("insert into foo (id, name) values(?,?)"), 1, "bob") if err != nil { t.Fatal(err) } r, err := tx.Query(db.q("select name from foo where id = ?"), 1) if err != nil { t.Fatal(err) } defer r.Close() if !r.Next() { if r.Err() != nil { t.Fatal(err) } t.Fatal("expected one rows") } var name string err = r.Scan(&name) if err != nil { t.Fatal(err) } } func TestPreparedStmt(t *testing.T) { db.tearDown() db.mustExec("CREATE TABLE t (count INT)") sel, err := db.Prepare("SELECT count FROM t ORDER BY count DESC") if err != nil { t.Fatalf("prepare 1: %v", err) } ins, err := db.Prepare(db.q("INSERT INTO t (count) VALUES (?)")) if err != nil { t.Fatalf("prepare 2: %v", err) } for n := 1; n <= 3; n++ { if _, err := ins.Exec(n); err != nil { t.Fatalf("insert(%d) = %v", n, err) } } const nRuns = 10 ch := make(chan bool) for i := 0; i < nRuns; i++ { go func() { defer func() { ch <- true }() for j := 0; j < 10; j++ { count := 0 if err := sel.QueryRow().Scan(&count); err != nil && err != sql.ErrNoRows { t.Errorf("Query: %v", err) return } if _, err := ins.Exec(rand.Intn(100)); err != nil { t.Errorf("Insert: %v", err) return } } }() } for i := 0; i < nRuns; i++ { <-ch } } // Benchmarks need to use panic() since b.Error errors are lost when // running via testing.Benchmark() I would like to run these via go // test -bench but calling Benchmark() from a benchmark test // currently hangs go. func BenchmarkExec(b *testing.B) { for i := 0; i < b.N; i++ { if _, err := db.Exec("select 1"); err != nil { panic(err) } } } func BenchmarkQuery(b *testing.B) { for i := 0; i < b.N; i++ { var n sql.NullString var i int var f float64 var s string // var t time.Time if err := db.QueryRow("select null, 1, 1.1, 'foo'").Scan(&n, &i, &f, &s); err != nil { panic(err) } } } func BenchmarkParams(b *testing.B) { for i := 0; i < b.N; i++ { var n sql.NullString var i int var f float64 var s string // var t time.Time if err := db.QueryRow("select ?, ?, ?, ?", nil, 1, 1.1, "foo").Scan(&n, &i, &f, &s); err != nil { panic(err) } } } func BenchmarkStmt(b *testing.B) { st, err := db.Prepare("select ?, ?, ?, ?") if err != nil { panic(err) } defer st.Close() for n := 0; n < b.N; n++ { var n sql.NullString var i int var f float64 var s string // var t time.Time if err := st.QueryRow(nil, 1, 1.1, "foo").Scan(&n, &i, &f, &s); err != nil { panic(err) } } } func BenchmarkRows(b *testing.B) { db.once.Do(makeBench) for n := 0; n < b.N; n++ { var n sql.NullString var i int var f float64 var s string var t time.Time r, err := db.Query("select * from bench") if err != nil { panic(err) } for r.Next() { if err = r.Scan(&n, &i, &f, &s, &t); err != nil { panic(err) } } if err = r.Err(); err != nil { panic(err) } } } func BenchmarkStmtRows(b *testing.B) { db.once.Do(makeBench) st, err := db.Prepare("select * from bench") if err != nil { panic(err) } defer st.Close() for n := 0; n < b.N; n++ { var n sql.NullString var i int var f float64 var s string var t time.Time r, err := st.Query() if err != nil { panic(err) } for r.Next() { if err = r.Scan(&n, &i, &f, &s, &t); err != nil { panic(err) } } if err = r.Err(); err != nil { panic(err) } } }
Godeps/_workspace/src/github.com/mattn/go-sqlite3/sqlite3_test/sqltest.go
0
https://github.com/grafana/grafana/commit/ae93f2b936cda93b8141a6ff61adb18037aca4ab
[ 0.0017791689606383443, 0.00025412958348169923, 0.00016475975280627608, 0.00017203933384735137, 0.00031074334401637316 ]
{ "id": 3, "code_window": [ "\n", " it('should translate index pattern to current day', function() {\n", " var requestOptions;\n", " ctx.backendSrv.datasourceRequest = function(options) {\n", " requestOptions = options;\n", " return ctx.$q.when({data: {responses: []}});\n" ], "labels": [ "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "public/app/plugins/datasource/elasticsearch/specs/datasource_specs.ts", "type": "replace", "edit_start_line_idx": 52 }
package api import ( "testing" ) func TestHttpApi(t *testing.T) { // Convey("Given the grafana api", t, func() { // ConveyApiScenario("Can sign up", func(c apiTestContext) { // c.PostJson() // So(c.Resp, ShouldEqualJsonApiResponse, "User created and logged in") // }) // // m := macaron.New() // m.Use(middleware.GetContextHandler()) // m.Use(middleware.Sessioner(&session.Options{})) // Register(m) // // var context *middleware.Context // m.Get("/", func(c *middleware.Context) { // context = c // }) // // resp := httptest.NewRecorder() // req, err := http.NewRequest("GET", "/", nil) // So(err, ShouldBeNil) // // m.ServeHTTP(resp, req) // // Convey("should red 200", func() { // So(resp.Code, ShouldEqual, 200) // }) // }) }
pkg/api/api_test.go
0
https://github.com/grafana/grafana/commit/ae93f2b936cda93b8141a6ff61adb18037aca4ab
[ 0.00017245295748580247, 0.00016939089982770383, 0.00016599254740867764, 0.00016955906176008284, 0.000002388376515227719 ]
{ "id": 3, "code_window": [ "\n", " it('should translate index pattern to current day', function() {\n", " var requestOptions;\n", " ctx.backendSrv.datasourceRequest = function(options) {\n", " requestOptions = options;\n", " return ctx.$q.when({data: {responses: []}});\n" ], "labels": [ "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "public/app/plugins/datasource/elasticsearch/specs/datasource_specs.ts", "type": "replace", "edit_start_line_idx": 52 }
<div class="editor-row"> <div class="section"> <h5>General options</h5> <div class="tight-form last"> <ul class="tight-form-list"> <li class="tight-form-item"> Title </li> <li> <input type="text" class="input-xlarge tight-form-input" ng-model='panel.title'></input> </li> <li class="tight-form-item"> Span </li> <li> <select class="input-mini tight-form-input" ng-model="panel.span" ng-options="f for f in [0,1,2,3,4,5,6,7,8,9,10,11,12]"></select> </li> <li class="tight-form-item"> Height </li> <li> <input type="text" class="input-small tight-form-input" ng-model='panel.height'></input> </li> <li class="tight-form-item"> <label class="checkbox-label" for="panel.transparent">Transparent</label> <input class="cr1" id="panel.transparent" type="checkbox" ng-model="panel.transparent" ng-checked="panel.transparent"> <label for="panel.transparent" class="cr1"></label> </li> </ul> <div class="clearfix"></div> </div> </div> <div class="section"> <h5>Templating options</h5> <div class="tight-form last"> <ul class="tight-form-list"> <li class="tight-form-item"> Repeat Panel </li> <li> <select class="input-small tight-form-input last" ng-model="panel.repeat" ng-options="f.name as f.name for f in dashboard.templating.list"> <option value=""></option> </select> </li> <li class="tight-form-item"> Min span </li> <li> <select class="input-small tight-form-input last" ng-model="panel.minSpan" ng-options="f for f in [1,2,3,4,5,6,7,8,9,10,11,12]"> <option value=""></option> </select> </li> </ul> <div class="clearfix"></div> </div> </div> </div> <panel-links-editor panel="panel"></panel-links-editor>
public/app/partials/panelgeneral.html
0
https://github.com/grafana/grafana/commit/ae93f2b936cda93b8141a6ff61adb18037aca4ab
[ 0.00017356763419229537, 0.00017168714839499444, 0.0001656829408602789, 0.0001722659362712875, 0.000002544081780797569 ]
{ "id": 4, "code_window": [ " ctx.ds.query({\n", " range: {\n", " from: moment([2015, 4, 30, 10]),\n", " to: moment([2015, 5, 1, 10])\n", " },\n", " targets: [{ bucketAggs: [], metrics: [] }]\n", " });\n", "\n", " ctx.$rootScope.$apply();\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " targets: [{ bucketAggs: [], metrics: [], query: 'escape\\\\:test' }]\n" ], "file_path": "public/app/plugins/datasource/elasticsearch/specs/datasource_specs.ts", "type": "replace", "edit_start_line_idx": 64 }
///<amd-dependency path="../datasource" /> ///<amd-dependency path="test/specs/helpers" name="helpers" /> import {describe, beforeEach, it, sinon, expect, angularMocks} from 'test/lib/common'; import moment = require('moment'); import angular = require('angular'); declare var helpers: any; describe('ElasticDatasource', function() { var ctx = new helpers.ServiceTestContext(); beforeEach(angularMocks.module('grafana.services')); beforeEach(ctx.providePhase(['templateSrv', 'backendSrv'])); beforeEach(ctx.createService('ElasticDatasource')); beforeEach(function() { ctx.ds = new ctx.service({jsonData: {}}); }); describe('When testing datasource with index pattern', function() { beforeEach(function() { ctx.ds = new ctx.service({ url: 'http://es.com', index: '[asd-]YYYY.MM.DD', jsonData: { interval: 'Daily' } }); }); it('should translate index pattern to current day', function() { var requestOptions; ctx.backendSrv.datasourceRequest = function(options) { requestOptions = options; return ctx.$q.when({}); }; ctx.ds.testDatasource(); ctx.$rootScope.$apply(); var today = moment().format("YYYY.MM.DD"); expect(requestOptions.url).to.be("http://es.com/asd-" + today + '/_stats'); }); }); describe('When issueing metric query with interval pattern', function() { beforeEach(function() { ctx.ds = new ctx.service({ url: 'http://es.com', index: '[asd-]YYYY.MM.DD', jsonData: { interval: 'Daily' } }); }); it('should translate index pattern to current day', function() { var requestOptions; ctx.backendSrv.datasourceRequest = function(options) { requestOptions = options; return ctx.$q.when({data: {responses: []}}); }; ctx.ds.query({ range: { from: moment([2015, 4, 30, 10]), to: moment([2015, 5, 1, 10]) }, targets: [{ bucketAggs: [], metrics: [] }] }); ctx.$rootScope.$apply(); var parts = requestOptions.data.split('\n'); var header = angular.fromJson(parts[0]); expect(header.index).to.eql(['asd-2015.05.30', 'asd-2015.05.31', 'asd-2015.06.01']); }); }); });
public/app/plugins/datasource/elasticsearch/specs/datasource_specs.ts
1
https://github.com/grafana/grafana/commit/ae93f2b936cda93b8141a6ff61adb18037aca4ab
[ 0.37785282731056213, 0.05110926553606987, 0.00016525379032827914, 0.0061556752771139145, 0.12353629618883133 ]
{ "id": 4, "code_window": [ " ctx.ds.query({\n", " range: {\n", " from: moment([2015, 4, 30, 10]),\n", " to: moment([2015, 5, 1, 10])\n", " },\n", " targets: [{ bucketAggs: [], metrics: [] }]\n", " });\n", "\n", " ctx.$rootScope.$apply();\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " targets: [{ bucketAggs: [], metrics: [], query: 'escape\\\\:test' }]\n" ], "file_path": "public/app/plugins/datasource/elasticsearch/specs/datasource_specs.ts", "type": "replace", "edit_start_line_idx": 64 }
<div class="editor-row"> <div class="section"> <h5>Chart Options</h5> <editor-opt-bool text="Bars" model="panel.bars" change="render()"></editor-opt-bool> <editor-opt-bool text="Lines" model="panel.lines" change="render()"></editor-opt-bool> <editor-opt-bool text="Points" model="panel.points" change="render()"></editor-opt-bool> </div> <div class="section"> <h5>Line options</h5> <div class="editor-option" ng-show="panel.lines"> <label class="small">Line Fill</label> <select class="input-mini" ng-model="panel.fill" ng-options="f for f in [0,1,2,3,4,5,6,7,8,9,10]" ng-change="render()"></select> </div> <div class="editor-option" ng-show="panel.lines"> <label class="small">Line Width</label> <select class="input-mini" ng-model="panel.linewidth" ng-options="f for f in [0,1,2,3,4,5,6,7,8,9,10]" ng-change="render()"></select> </div> <div class="editor-option" ng-show="panel.points"> <label class="small">Point Radius</label> <select class="input-mini" ng-model="panel.pointradius" ng-options="f for f in [1,2,3,4,5,6,7,8,9,10]" ng-change="render()"></select> </div> <div class="editor-option"> <label class="small">Null point mode<tip>Define how null values should be drawn</tip></label> <select class="input-medium" ng-model="panel.nullPointMode" ng-options="f for f in ['connected', 'null', 'null as zero']" ng-change="render()"></select> </div> <editor-opt-bool text="Staircase line" model="panel.steppedLine" change="render()"></editor-opt-bool> </div> <div class="section"> <h5>Multiple Series</h5> <editor-opt-bool text="Stack" model="panel.stack" change="render()"></editor-opt-bool> <editor-opt-bool text="Percent" model="panel.percentage" change="render()" tip="Stack as a percentage of total"></editor-opt-bool> </div> <div class="section"> <h5>Rendering</h5> <div class="editor-option"> <label class="small">Flot <tip>client side</tip></label> <input type="radio" class="input-small" ng-model="panel.renderer" value="flot" ng-change="get_data()" /> </div> <div class="editor-option"> <label class="small">Graphite PNG <tip>server side</tip></label> <input type="radio" class="input-small" ng-model="panel.renderer" value="png" ng-change="get_data()" /> </div> </div> <div class="section"> <h5>Tooltip</h5> <editor-opt-bool text="All series" model="panel.tooltip.shared" change="render()" tip="Show all series on same tooltip and a x croshair to help follow all series"> </editor-opt-bool> <div class="editor-option" ng-show="panel.stack"> <label class="small">Stacked Values <tip>How should the values in stacked charts to be calculated?</tip></label> <select class="input-small" ng-model="panel.tooltip.value_type" ng-options="f for f in ['cumulative','individual']" ng-change="render()"></select> </div> </div> </div> <div class="editor-row"> <div class="section"> <h5>Series specific overrides <tip>Regex match example: /server[0-3]/i </tip></h5> <div> <div class="tight-form" ng-repeat="override in panel.seriesOverrides" ng-controller="SeriesOverridesCtrl"> <ul class="tight-form-list"> <li class="tight-form-item"> <i class="fa fa-remove pointer" ng-click="removeSeriesOverride(override)"></i> </li> <li class="tight-form-item"> alias or regex </li> <li> <input type="text" ng-model="override.alias" bs-typeahead="getSeriesNames" ng-blur="render()" data-min-length=0 data-items=100 class="input-medium tight-form-input" > </li> <li class="tight-form-item" ng-repeat="option in currentOverrides"> <i class="pointer fa fa-remove" ng-click="removeOverride(option)"></i> <span ng-show="option.propertyName === 'color'"> Color: <i class="fa fa-circle" ng-style="{color:option.value}"></i> </span> <span ng-show="option.propertyName !== 'color'"> {{option.name}}: {{option.value}} </span> </li> <li class="dropdown" dropdown-typeahead="overrideMenu" dropdown-typeahead-on-select="setOverride($item, $subItem)"> </li> </ul> <div class="clearfix"></div> </div> </div> <button class="btn btn-inverse" style="margin-top: 20px" ng-click="addSeriesOverride()"> Add series specific option </button> </div> </div>
public/app/panels/graph/styleEditor.html
0
https://github.com/grafana/grafana/commit/ae93f2b936cda93b8141a6ff61adb18037aca4ab
[ 0.0001725648035062477, 0.00016922921349760145, 0.00016533324378542602, 0.00016970289289020002, 0.0000018931760905616102 ]
{ "id": 4, "code_window": [ " ctx.ds.query({\n", " range: {\n", " from: moment([2015, 4, 30, 10]),\n", " to: moment([2015, 5, 1, 10])\n", " },\n", " targets: [{ bucketAggs: [], metrics: [] }]\n", " });\n", "\n", " ctx.$rootScope.$apply();\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " targets: [{ bucketAggs: [], metrics: [], query: 'escape\\\\:test' }]\n" ], "file_path": "public/app/plugins/datasource/elasticsearch/specs/datasource_specs.ts", "type": "replace", "edit_start_line_idx": 64 }
define(function() { return function( elem ) { // Support: IE<=11+, Firefox<=30+ (#15098, #14150) // IE throws on elements created in popups // FF meanwhile throws on frame elements through "defaultView.getComputedStyle" if ( elem.ownerDocument.defaultView.opener ) { return elem.ownerDocument.defaultView.getComputedStyle( elem, null ); } return window.getComputedStyle( elem, null ); }; });
public/vendor/jquery/src/css/var/getStyles.js
0
https://github.com/grafana/grafana/commit/ae93f2b936cda93b8141a6ff61adb18037aca4ab
[ 0.0001698915148153901, 0.0001684014277998358, 0.00016691135533619672, 0.0001684014277998358, 0.0000014900797395966947 ]
{ "id": 4, "code_window": [ " ctx.ds.query({\n", " range: {\n", " from: moment([2015, 4, 30, 10]),\n", " to: moment([2015, 5, 1, 10])\n", " },\n", " targets: [{ bucketAggs: [], metrics: [] }]\n", " });\n", "\n", " ctx.$rootScope.$apply();\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " targets: [{ bucketAggs: [], metrics: [], query: 'escape\\\\:test' }]\n" ], "file_path": "public/app/plugins/datasource/elasticsearch/specs/datasource_specs.ts", "type": "replace", "edit_start_line_idx": 64 }
// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package bufio implements buffered I/O. It wraps an io.Reader or io.Writer // object, creating another object (Reader or Writer) that also implements // the interface but provides buffering and some help for textual I/O. package bufio import ( "bytes" "errors" "io" "unicode/utf8" ) const ( defaultBufSize = 4096 ) var ( ErrInvalidUnreadByte = errors.New("bufio: invalid use of UnreadByte") ErrInvalidUnreadRune = errors.New("bufio: invalid use of UnreadRune") ErrBufferFull = errors.New("bufio: buffer full") ErrNegativeCount = errors.New("bufio: negative count") ) // Buffered input. // Reader implements buffering for an io.Reader object. type Reader struct { buf []byte rd io.Reader r, w int err error lastByte int lastRuneSize int } const minReadBufferSize = 16 const maxConsecutiveEmptyReads = 100 // NewReaderSize returns a new Reader whose buffer has at least the specified // size. If the argument io.Reader is already a Reader with large enough // size, it returns the underlying Reader. func NewReaderSize(rd io.Reader, size int) *Reader { // Is it already a Reader? b, ok := rd.(*Reader) if ok && len(b.buf) >= size { return b } if size < minReadBufferSize { size = minReadBufferSize } r := new(Reader) r.reset(make([]byte, size), rd) return r } // NewReader returns a new Reader whose buffer has the default size. func NewReader(rd io.Reader) *Reader { return NewReaderSize(rd, defaultBufSize) } // Reset discards any buffered data, resets all state, and switches // the buffered reader to read from r. func (b *Reader) Reset(r io.Reader) { b.reset(b.buf, r) } func (b *Reader) reset(buf []byte, r io.Reader) { *b = Reader{ buf: buf, rd: r, lastByte: -1, lastRuneSize: -1, } } var errNegativeRead = errors.New("bufio: reader returned negative count from Read") // fill reads a new chunk into the buffer. func (b *Reader) fill() { // Slide existing data to beginning. if b.r > 0 { copy(b.buf, b.buf[b.r:b.w]) b.w -= b.r b.r = 0 } if b.w >= len(b.buf) { panic("bufio: tried to fill full buffer") } // Read new data: try a limited number of times. for i := maxConsecutiveEmptyReads; i > 0; i-- { n, err := b.rd.Read(b.buf[b.w:]) if n < 0 { panic(errNegativeRead) } b.w += n if err != nil { b.err = err return } if n > 0 { return } } b.err = io.ErrNoProgress } func (b *Reader) readErr() error { err := b.err b.err = nil return err } // Peek returns the next n bytes without advancing the reader. The bytes stop // being valid at the next read call. If Peek returns fewer than n bytes, it // also returns an error explaining why the read is short. The error is // ErrBufferFull if n is larger than b's buffer size. func (b *Reader) Peek(n int) ([]byte, error) { if n < 0 { return nil, ErrNegativeCount } if n > len(b.buf) { return nil, ErrBufferFull } // 0 <= n <= len(b.buf) for b.w-b.r < n && b.err == nil { b.fill() // b.w-b.r < len(b.buf) => buffer is not full } m := b.w - b.r if m > n { m = n } var err error if m < n { err = b.readErr() if err == nil { err = ErrBufferFull } } return b.buf[b.r : b.r+m], err } // Read reads data into p. // It returns the number of bytes read into p. // It calls Read at most once on the underlying Reader, // hence n may be less than len(p). // At EOF, the count will be zero and err will be io.EOF. func (b *Reader) Read(p []byte) (n int, err error) { n = len(p) if n == 0 { return 0, b.readErr() } if b.r == b.w { if b.err != nil { return 0, b.readErr() } if len(p) >= len(b.buf) { // Large read, empty buffer. // Read directly into p to avoid copy. n, b.err = b.rd.Read(p) if n < 0 { panic(errNegativeRead) } if n > 0 { b.lastByte = int(p[n-1]) b.lastRuneSize = -1 } return n, b.readErr() } b.fill() // buffer is empty if b.w == b.r { return 0, b.readErr() } } if n > b.w-b.r { n = b.w - b.r } copy(p[0:n], b.buf[b.r:]) b.r += n b.lastByte = int(b.buf[b.r-1]) b.lastRuneSize = -1 return n, nil } // ReadByte reads and returns a single byte. // If no byte is available, returns an error. func (b *Reader) ReadByte() (c byte, err error) { b.lastRuneSize = -1 for b.r == b.w { if b.err != nil { return 0, b.readErr() } b.fill() // buffer is empty } c = b.buf[b.r] b.r++ b.lastByte = int(c) return c, nil } // UnreadByte unreads the last byte. Only the most recently read byte can be unread. func (b *Reader) UnreadByte() error { if b.lastByte < 0 || b.r == 0 && b.w > 0 { return ErrInvalidUnreadByte } // b.r > 0 || b.w == 0 if b.r > 0 { b.r-- } else { // b.r == 0 && b.w == 0 b.w = 1 } b.buf[b.r] = byte(b.lastByte) b.lastByte = -1 b.lastRuneSize = -1 return nil } // ReadRune reads a single UTF-8 encoded Unicode character and returns the // rune and its size in bytes. If the encoded rune is invalid, it consumes one byte // and returns unicode.ReplacementChar (U+FFFD) with a size of 1. func (b *Reader) ReadRune() (r rune, size int, err error) { for b.r+utf8.UTFMax > b.w && !utf8.FullRune(b.buf[b.r:b.w]) && b.err == nil && b.w-b.r < len(b.buf) { b.fill() // b.w-b.r < len(buf) => buffer is not full } b.lastRuneSize = -1 if b.r == b.w { return 0, 0, b.readErr() } r, size = rune(b.buf[b.r]), 1 if r >= 0x80 { r, size = utf8.DecodeRune(b.buf[b.r:b.w]) } b.r += size b.lastByte = int(b.buf[b.r-1]) b.lastRuneSize = size return r, size, nil } // UnreadRune unreads the last rune. If the most recent read operation on // the buffer was not a ReadRune, UnreadRune returns an error. (In this // regard it is stricter than UnreadByte, which will unread the last byte // from any read operation.) func (b *Reader) UnreadRune() error { if b.lastRuneSize < 0 || b.r < b.lastRuneSize { return ErrInvalidUnreadRune } b.r -= b.lastRuneSize b.lastByte = -1 b.lastRuneSize = -1 return nil } // Buffered returns the number of bytes that can be read from the current buffer. func (b *Reader) Buffered() int { return b.w - b.r } // ReadSlice reads until the first occurrence of delim in the input, // returning a slice pointing at the bytes in the buffer. // The bytes stop being valid at the next read. // If ReadSlice encounters an error before finding a delimiter, // it returns all the data in the buffer and the error itself (often io.EOF). // ReadSlice fails with error ErrBufferFull if the buffer fills without a delim. // Because the data returned from ReadSlice will be overwritten // by the next I/O operation, most clients should use // ReadBytes or ReadString instead. // ReadSlice returns err != nil if and only if line does not end in delim. func (b *Reader) ReadSlice(delim byte) (line []byte, err error) { for { // Search buffer. if i := bytes.IndexByte(b.buf[b.r:b.w], delim); i >= 0 { line = b.buf[b.r : b.r+i+1] b.r += i + 1 break } // Pending error? if b.err != nil { line = b.buf[b.r:b.w] b.r = b.w err = b.readErr() break } // Buffer full? if n := b.Buffered(); n >= len(b.buf) { b.r = b.w line = b.buf err = ErrBufferFull break } b.fill() // buffer is not full } // Handle last byte, if any. if i := len(line) - 1; i >= 0 { b.lastByte = int(line[i]) } return } // ReadN tries to read exactly n bytes. // The bytes stop being valid at the next read call. // If ReadN encounters an error before reading n bytes, // it returns all the data in the buffer and the error itself (often io.EOF). // ReadN fails with error ErrBufferFull if the buffer fills // without reading N bytes. // Because the data returned from ReadN will be overwritten // by the next I/O operation, most clients should use // ReadBytes or ReadString instead. func (b *Reader) ReadN(n int) ([]byte, error) { for b.Buffered() < n { if b.err != nil { buf := b.buf[b.r:b.w] b.r = b.w return buf, b.readErr() } // Buffer is full? if b.Buffered() >= len(b.buf) { b.r = b.w return b.buf, ErrBufferFull } b.fill() } buf := b.buf[b.r : b.r+n] b.r += n return buf, nil } // ReadLine is a low-level line-reading primitive. Most callers should use // ReadBytes('\n') or ReadString('\n') instead or use a Scanner. // // ReadLine tries to return a single line, not including the end-of-line bytes. // If the line was too long for the buffer then isPrefix is set and the // beginning of the line is returned. The rest of the line will be returned // from future calls. isPrefix will be false when returning the last fragment // of the line. The returned buffer is only valid until the next call to // ReadLine. ReadLine either returns a non-nil line or it returns an error, // never both. // // The text returned from ReadLine does not include the line end ("\r\n" or "\n"). // No indication or error is given if the input ends without a final line end. // Calling UnreadByte after ReadLine will always unread the last byte read // (possibly a character belonging to the line end) even if that byte is not // part of the line returned by ReadLine. func (b *Reader) ReadLine() (line []byte, isPrefix bool, err error) { line, err = b.ReadSlice('\n') if err == ErrBufferFull { // Handle the case where "\r\n" straddles the buffer. if len(line) > 0 && line[len(line)-1] == '\r' { // Put the '\r' back on buf and drop it from line. // Let the next call to ReadLine check for "\r\n". if b.r == 0 { // should be unreachable panic("bufio: tried to rewind past start of buffer") } b.r-- line = line[:len(line)-1] } return line, true, nil } if len(line) == 0 { if err != nil { line = nil } return } err = nil if line[len(line)-1] == '\n' { drop := 1 if len(line) > 1 && line[len(line)-2] == '\r' { drop = 2 } line = line[:len(line)-drop] } return } // ReadBytes reads until the first occurrence of delim in the input, // returning a slice containing the data up to and including the delimiter. // If ReadBytes encounters an error before finding a delimiter, // it returns the data read before the error and the error itself (often io.EOF). // ReadBytes returns err != nil if and only if the returned data does not end in // delim. // For simple uses, a Scanner may be more convenient. func (b *Reader) ReadBytes(delim byte) (line []byte, err error) { // Use ReadSlice to look for array, // accumulating full buffers. var frag []byte var full [][]byte err = nil for { var e error frag, e = b.ReadSlice(delim) if e == nil { // got final fragment break } if e != ErrBufferFull { // unexpected error err = e break } // Make a copy of the buffer. buf := make([]byte, len(frag)) copy(buf, frag) full = append(full, buf) } // Allocate new buffer to hold the full pieces and the fragment. n := 0 for i := range full { n += len(full[i]) } n += len(frag) // Copy full pieces and fragment in. buf := make([]byte, n) n = 0 for i := range full { n += copy(buf[n:], full[i]) } copy(buf[n:], frag) return buf, err } // ReadString reads until the first occurrence of delim in the input, // returning a string containing the data up to and including the delimiter. // If ReadString encounters an error before finding a delimiter, // it returns the data read before the error and the error itself (often io.EOF). // ReadString returns err != nil if and only if the returned data does not end in // delim. // For simple uses, a Scanner may be more convenient. func (b *Reader) ReadString(delim byte) (line string, err error) { bytes, err := b.ReadBytes(delim) line = string(bytes) return line, err } // WriteTo implements io.WriterTo. func (b *Reader) WriteTo(w io.Writer) (n int64, err error) { n, err = b.writeBuf(w) if err != nil { return } if r, ok := b.rd.(io.WriterTo); ok { m, err := r.WriteTo(w) n += m return n, err } if w, ok := w.(io.ReaderFrom); ok { m, err := w.ReadFrom(b.rd) n += m return n, err } if b.w-b.r < len(b.buf) { b.fill() // buffer not full } for b.r < b.w { // b.r < b.w => buffer is not empty m, err := b.writeBuf(w) n += m if err != nil { return n, err } b.fill() // buffer is empty } if b.err == io.EOF { b.err = nil } return n, b.readErr() } // writeBuf writes the Reader's buffer to the writer. func (b *Reader) writeBuf(w io.Writer) (int64, error) { n, err := w.Write(b.buf[b.r:b.w]) if n < b.r-b.w { panic(errors.New("bufio: writer did not write all data")) } b.r += n return int64(n), err } // buffered output // Writer implements buffering for an io.Writer object. // If an error occurs writing to a Writer, no more data will be // accepted and all subsequent writes will return the error. // After all data has been written, the client should call the // Flush method to guarantee all data has been forwarded to // the underlying io.Writer. type Writer struct { err error buf []byte n int wr io.Writer } // NewWriterSize returns a new Writer whose buffer has at least the specified // size. If the argument io.Writer is already a Writer with large enough // size, it returns the underlying Writer. func NewWriterSize(w io.Writer, size int) *Writer { // Is it already a Writer? b, ok := w.(*Writer) if ok && len(b.buf) >= size { return b } if size <= 0 { size = defaultBufSize } return &Writer{ buf: make([]byte, size), wr: w, } } // NewWriter returns a new Writer whose buffer has the default size. func NewWriter(w io.Writer) *Writer { return NewWriterSize(w, defaultBufSize) } // Reset discards any unflushed buffered data, clears any error, and // resets b to write its output to w. func (b *Writer) Reset(w io.Writer) { b.err = nil b.n = 0 b.wr = w } // Flush writes any buffered data to the underlying io.Writer. func (b *Writer) Flush() error { err := b.flush() return err } func (b *Writer) flush() error { if b.err != nil { return b.err } if b.n == 0 { return nil } n, err := b.wr.Write(b.buf[0:b.n]) if n < b.n && err == nil { err = io.ErrShortWrite } if err != nil { if n > 0 && n < b.n { copy(b.buf[0:b.n-n], b.buf[n:b.n]) } b.n -= n b.err = err return err } b.n = 0 return nil } // Available returns how many bytes are unused in the buffer. func (b *Writer) Available() int { return len(b.buf) - b.n } // Buffered returns the number of bytes that have been written into the current buffer. func (b *Writer) Buffered() int { return b.n } // Write writes the contents of p into the buffer. // It returns the number of bytes written. // If nn < len(p), it also returns an error explaining // why the write is short. func (b *Writer) Write(p []byte) (nn int, err error) { for len(p) > b.Available() && b.err == nil { var n int if b.Buffered() == 0 { // Large write, empty buffer. // Write directly from p to avoid copy. n, b.err = b.wr.Write(p) } else { n = copy(b.buf[b.n:], p) b.n += n b.flush() } nn += n p = p[n:] } if b.err != nil { return nn, b.err } n := copy(b.buf[b.n:], p) b.n += n nn += n return nn, nil } // WriteByte writes a single byte. func (b *Writer) WriteByte(c byte) error { if b.err != nil { return b.err } if b.Available() <= 0 && b.flush() != nil { return b.err } b.buf[b.n] = c b.n++ return nil } // WriteRune writes a single Unicode code point, returning // the number of bytes written and any error. func (b *Writer) WriteRune(r rune) (size int, err error) { if r < utf8.RuneSelf { err = b.WriteByte(byte(r)) if err != nil { return 0, err } return 1, nil } if b.err != nil { return 0, b.err } n := b.Available() if n < utf8.UTFMax { if b.flush(); b.err != nil { return 0, b.err } n = b.Available() if n < utf8.UTFMax { // Can only happen if buffer is silly small. return b.WriteString(string(r)) } } size = utf8.EncodeRune(b.buf[b.n:], r) b.n += size return size, nil } // WriteString writes a string. // It returns the number of bytes written. // If the count is less than len(s), it also returns an error explaining // why the write is short. func (b *Writer) WriteString(s string) (int, error) { nn := 0 for len(s) > b.Available() && b.err == nil { n := copy(b.buf[b.n:], s) b.n += n nn += n s = s[n:] b.flush() } if b.err != nil { return nn, b.err } n := copy(b.buf[b.n:], s) b.n += n nn += n return nn, nil } // ReadFrom implements io.ReaderFrom. func (b *Writer) ReadFrom(r io.Reader) (n int64, err error) { if b.Buffered() == 0 { if w, ok := b.wr.(io.ReaderFrom); ok { return w.ReadFrom(r) } } var m int for { if b.Available() == 0 { if err1 := b.flush(); err1 != nil { return n, err1 } } nr := 0 for nr < maxConsecutiveEmptyReads { m, err = r.Read(b.buf[b.n:]) if m != 0 || err != nil { break } nr++ } if nr == maxConsecutiveEmptyReads { return n, io.ErrNoProgress } b.n += m n += int64(m) if err != nil { break } } if err == io.EOF { // If we filled the buffer exactly, flush pre-emptively. if b.Available() == 0 { err = b.flush() } else { err = nil } } return n, err } // buffered input and output // ReadWriter stores pointers to a Reader and a Writer. // It implements io.ReadWriter. type ReadWriter struct { *Reader *Writer } // NewReadWriter allocates a new ReadWriter that dispatches to r and w. func NewReadWriter(r *Reader, w *Writer) *ReadWriter { return &ReadWriter{r, w} }
Godeps/_workspace/src/gopkg.in/bufio.v1/bufio.go
0
https://github.com/grafana/grafana/commit/ae93f2b936cda93b8141a6ff61adb18037aca4ab
[ 0.00029010442085564137, 0.00017433473840355873, 0.00016144201799761504, 0.00017103333084378392, 0.00001886837708298117 ]
{ "id": 5, "code_window": [ " });\n", "\n", " ctx.$rootScope.$apply();\n", " var parts = requestOptions.data.split('\\n');\n", " var header = angular.fromJson(parts[0]);\n", " expect(header.index).to.eql(['asd-2015.05.30', 'asd-2015.05.31', 'asd-2015.06.01']);\n", " });\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep" ], "after_edit": [ "\n", " parts = requestOptions.data.split('\\n');\n", " header = angular.fromJson(parts[0]);\n", " });\n", "\n", " it('should translate index pattern to current day', function() {\n" ], "file_path": "public/app/plugins/datasource/elasticsearch/specs/datasource_specs.ts", "type": "replace", "edit_start_line_idx": 68 }
///<amd-dependency path="../index_pattern" name="IndexPattern"/> ///<amd-dependency path="test/specs/helpers" name="helpers" /> import {describe, beforeEach, it, sinon, expect} from 'test/lib/common'; import moment = require('moment'); declare var IndexPattern: any; describe('IndexPattern', function() { describe.only('when getting index for today', function() { it('should return correct index name', function() { var pattern = new IndexPattern('[asd-]YYYY.MM.DD', 'Daily'); var expected = 'asd-' + moment().format('YYYY.MM.DD'); expect(pattern.getIndexForToday()).to.be(expected); }); }); describe('when getting index list for time range', function() { describe('no interval', function() { it('should return correct index', function() { var pattern = new IndexPattern('my-metrics'); var from = new Date(2015, 4, 30, 1, 2, 3); var to = new Date(2015, 5, 1, 12, 5 , 6); expect(pattern.getIndexList(from, to)).to.eql('my-metrics'); }); }); describe('daily', function() { it('should return correct index list', function() { var pattern = new IndexPattern('[asd-]YYYY.MM.DD', 'Daily'); var from = new Date(1432940523000); var to = new Date(1433153106000); var expected = [ 'asd-2015.05.29', 'asd-2015.05.30', 'asd-2015.05.31', 'asd-2015.06.01', ]; expect(pattern.getIndexList(from, to)).to.eql(expected); }); }); }); });
public/app/plugins/datasource/elasticsearch/specs/index_pattern_specs.ts
1
https://github.com/grafana/grafana/commit/ae93f2b936cda93b8141a6ff61adb18037aca4ab
[ 0.0010460912017151713, 0.0003714537888299674, 0.00016440023318864405, 0.0001756456622388214, 0.000324169232044369 ]
{ "id": 5, "code_window": [ " });\n", "\n", " ctx.$rootScope.$apply();\n", " var parts = requestOptions.data.split('\\n');\n", " var header = angular.fromJson(parts[0]);\n", " expect(header.index).to.eql(['asd-2015.05.30', 'asd-2015.05.31', 'asd-2015.06.01']);\n", " });\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep" ], "after_edit": [ "\n", " parts = requestOptions.data.split('\\n');\n", " header = angular.fromJson(parts[0]);\n", " });\n", "\n", " it('should translate index pattern to current day', function() {\n" ], "file_path": "public/app/plugins/datasource/elasticsearch/specs/datasource_specs.ts", "type": "replace", "edit_start_line_idx": 68 }
module.exports = function(config) { return { dev: { options: { port: 5601, hostname: '*', base: config.srcDir, keepalive: true } }, dist: { options: { port: 5605, hostname: '*', base: config.destDir, keepalive: true } }, } };
tasks/options/connect.js
0
https://github.com/grafana/grafana/commit/ae93f2b936cda93b8141a6ff61adb18037aca4ab
[ 0.00017655512783676386, 0.00017465573910158128, 0.0001729672512738034, 0.00017444483819417655, 0.0000014723165122632054 ]
{ "id": 5, "code_window": [ " });\n", "\n", " ctx.$rootScope.$apply();\n", " var parts = requestOptions.data.split('\\n');\n", " var header = angular.fromJson(parts[0]);\n", " expect(header.index).to.eql(['asd-2015.05.30', 'asd-2015.05.31', 'asd-2015.06.01']);\n", " });\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep" ], "after_edit": [ "\n", " parts = requestOptions.data.split('\\n');\n", " header = angular.fromJson(parts[0]);\n", " });\n", "\n", " it('should translate index pattern to current day', function() {\n" ], "file_path": "public/app/plugins/datasource/elasticsearch/specs/datasource_specs.ts", "type": "replace", "edit_start_line_idx": 68 }
Certificate: Data: Version: 3 (0x2) Serial Number: 2 (0x2) Signature Algorithm: sha256WithRSAEncryption Issuer: C=US, ST=Nevada, L=Las Vegas, O=github.com/lib/pq, CN=pq CA Validity Not Before: Oct 11 15:10:11 2014 GMT Not After : Oct 8 15:10:11 2024 GMT Subject: C=US, ST=Nevada, L=Las Vegas, O=github.com/lib/pq, CN=pqgosslcert Subject Public Key Info: Public Key Algorithm: rsaEncryption RSA Public Key: (1024 bit) Modulus (1024 bit): 00:e3:8c:06:9a:70:54:51:d1:34:34:83:39:cd:a2: 59:0f:05:ed:8d:d8:0e:34:d0:92:f4:09:4d:ee:8c: 78:55:49:24:f8:3c:e0:34:58:02:b2:e7:94:58:c1: e8:e5:bb:d1:af:f6:54:c1:40:b1:90:70:79:0d:35: 54:9c:8f:16:e9:c2:f0:92:e6:64:49:38:c1:76:f8: 47:66:c4:5b:4a:b6:a9:43:ce:c8:be:6c:4d:2b:94: 97:3c:55:bc:d1:d0:6e:b7:53:ae:89:5c:4b:6b:86: 40:be:c1:ae:1e:64:ce:9c:ae:87:0a:69:e5:c8:21: 12:be:ae:1d:f6:45:df:16:a7 Exponent: 65537 (0x10001) X509v3 extensions: X509v3 Subject Key Identifier: 9B:25:31:63:A2:D8:06:FF:CB:E3:E9:96:FF:0D:BA:DC:12:7D:04:CF X509v3 Authority Key Identifier: keyid:52:93:ED:1E:76:0A:9F:65:4F:DE:19:66:C1:D5:22:40:35:CB:A0:72 X509v3 Basic Constraints: CA:FALSE X509v3 Key Usage: Digital Signature, Non Repudiation, Key Encipherment Signature Algorithm: sha256WithRSAEncryption 3e:f5:f8:0b:4e:11:bd:00:86:1f:ce:dc:97:02:98:91:11:f5: 65:f6:f2:8a:b2:3e:47:92:05:69:28:c9:e9:b4:f7:cf:93:d1: 2d:81:5d:00:3c:23:be:da:70:ea:59:e1:2c:d3:25:49:ae:a6: 95:54:c1:10:df:23:e3:fe:d6:e4:76:c7:6b:73:ad:1b:34:7c: e2:56:cc:c0:37:ae:c5:7a:11:20:6c:3d:05:0e:99:cd:22:6c: cf:59:a1:da:28:d4:65:ba:7d:2f:2b:3d:69:6d:a6:c1:ae:57: bf:56:64:13:79:f8:48:46:65:eb:81:67:28:0b:7b:de:47:10: b3:80:3c:31:d1:58:94:01:51:4a:c7:c8:1a:01:a8:af:c4:cd: bb:84:a5:d9:8b:b4:b9:a1:64:3e:95:d9:90:1d:d5:3f:67:cc: 3b:ba:f5:b4:d1:33:77:ee:c2:d2:3e:7e:c5:66:6e:b7:35:4c: 60:57:b0:b8:be:36:c8:f3:d3:95:8c:28:4a:c9:f7:27:a4:0d: e5:96:99:eb:f5:c8:bd:f3:84:6d:ef:02:f9:8a:36:7d:6b:5f: 36:68:37:41:d9:74:ae:c6:78:2e:44:86:a1:ad:43:ca:fb:b5: 3e:ba:10:23:09:02:ac:62:d1:d0:83:c8:95:b9:e3:5e:30:ff: 5b:2b:38:fa -----BEGIN CERTIFICATE----- MIIDEzCCAfugAwIBAgIBAjANBgkqhkiG9w0BAQsFADBeMQswCQYDVQQGEwJVUzEP MA0GA1UECBMGTmV2YWRhMRIwEAYDVQQHEwlMYXMgVmVnYXMxGjAYBgNVBAoTEWdp dGh1Yi5jb20vbGliL3BxMQ4wDAYDVQQDEwVwcSBDQTAeFw0xNDEwMTExNTEwMTFa Fw0yNDEwMDgxNTEwMTFaMGQxCzAJBgNVBAYTAlVTMQ8wDQYDVQQIEwZOZXZhZGEx EjAQBgNVBAcTCUxhcyBWZWdhczEaMBgGA1UEChMRZ2l0aHViLmNvbS9saWIvcHEx FDASBgNVBAMTC3BxZ29zc2xjZXJ0MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKB gQDjjAaacFRR0TQ0gznNolkPBe2N2A400JL0CU3ujHhVSST4POA0WAKy55RYwejl u9Gv9lTBQLGQcHkNNVScjxbpwvCS5mRJOMF2+EdmxFtKtqlDzsi+bE0rlJc8VbzR 0G63U66JXEtrhkC+wa4eZM6crocKaeXIIRK+rh32Rd8WpwIDAQABo1owWDAdBgNV HQ4EFgQUmyUxY6LYBv/L4+mW/w263BJ9BM8wHwYDVR0jBBgwFoAUUpPtHnYKn2VP 3hlmwdUiQDXLoHIwCQYDVR0TBAIwADALBgNVHQ8EBAMCBeAwDQYJKoZIhvcNAQEL BQADggEBAD71+AtOEb0Ahh/O3JcCmJER9WX28oqyPkeSBWkoyem098+T0S2BXQA8 I77acOpZ4SzTJUmuppVUwRDfI+P+1uR2x2tzrRs0fOJWzMA3rsV6ESBsPQUOmc0i bM9Zodoo1GW6fS8rPWltpsGuV79WZBN5+EhGZeuBZygLe95HELOAPDHRWJQBUUrH yBoBqK/EzbuEpdmLtLmhZD6V2ZAd1T9nzDu69bTRM3fuwtI+fsVmbrc1TGBXsLi+ Nsjz05WMKErJ9yekDeWWmev1yL3zhG3vAvmKNn1rXzZoN0HZdK7GeC5EhqGtQ8r7 tT66ECMJAqxi0dCDyJW5414w/1srOPo= -----END CERTIFICATE-----
Godeps/_workspace/src/github.com/lib/pq/certs/postgresql.crt
0
https://github.com/grafana/grafana/commit/ae93f2b936cda93b8141a6ff61adb18037aca4ab
[ 0.0001958221400855109, 0.0001767040666891262, 0.0001697478728601709, 0.00017213588580489159, 0.000008661641913931817 ]
{ "id": 5, "code_window": [ " });\n", "\n", " ctx.$rootScope.$apply();\n", " var parts = requestOptions.data.split('\\n');\n", " var header = angular.fromJson(parts[0]);\n", " expect(header.index).to.eql(['asd-2015.05.30', 'asd-2015.05.31', 'asd-2015.06.01']);\n", " });\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep" ], "after_edit": [ "\n", " parts = requestOptions.data.split('\\n');\n", " header = angular.fromJson(parts[0]);\n", " });\n", "\n", " it('should translate index pattern to current day', function() {\n" ], "file_path": "public/app/plugins/datasource/elasticsearch/specs/datasource_specs.ts", "type": "replace", "edit_start_line_idx": 68 }
package sqlstore import ( "testing" . "github.com/smartystreets/goconvey/convey" m "github.com/grafana/grafana/pkg/models" ) func TestDashboardSnapshotDBAccess(t *testing.T) { Convey("Testing DashboardSnapshot data access", t, func() { InitTestDB(t) Convey("Given saved snaphot", func() { cmd := m.CreateDashboardSnapshotCommand{ Key: "hej", Dashboard: map[string]interface{}{ "hello": "mupp", }, } err := CreateDashboardSnapshot(&cmd) So(err, ShouldBeNil) Convey("Should be able to get snaphot by key", func() { query := m.GetDashboardSnapshotQuery{Key: "hej"} err = GetDashboardSnapshot(&query) So(err, ShouldBeNil) So(query.Result, ShouldNotBeNil) So(query.Result.Dashboard["hello"], ShouldEqual, "mupp") }) }) }) }
pkg/services/sqlstore/dashboard_snapshot_test.go
0
https://github.com/grafana/grafana/commit/ae93f2b936cda93b8141a6ff61adb18037aca4ab
[ 0.00017355968884658068, 0.00017171577201224864, 0.00016684786533005536, 0.00017322777421213686, 0.0000028161869067844236 ]
{ "id": 6, "code_window": [ " expect(header.index).to.eql(['asd-2015.05.30', 'asd-2015.05.31', 'asd-2015.06.01']);\n", " });\n", " });\n", "});" ], "labels": [ "keep", "add", "keep", "keep" ], "after_edit": [ "\n", " it('should json escape lucene query', function() {\n", " var body = angular.fromJson(parts[1]);\n", " expect(body.query.filtered.query.query_string.query).to.be('escape\\\\:test');\n", " });\n" ], "file_path": "public/app/plugins/datasource/elasticsearch/specs/datasource_specs.ts", "type": "add", "edit_start_line_idx": 72 }
///<amd-dependency path="../index_pattern" name="IndexPattern"/> ///<amd-dependency path="test/specs/helpers" name="helpers" /> import {describe, beforeEach, it, sinon, expect} from 'test/lib/common'; import moment = require('moment'); declare var IndexPattern: any; describe('IndexPattern', function() { describe.only('when getting index for today', function() { it('should return correct index name', function() { var pattern = new IndexPattern('[asd-]YYYY.MM.DD', 'Daily'); var expected = 'asd-' + moment().format('YYYY.MM.DD'); expect(pattern.getIndexForToday()).to.be(expected); }); }); describe('when getting index list for time range', function() { describe('no interval', function() { it('should return correct index', function() { var pattern = new IndexPattern('my-metrics'); var from = new Date(2015, 4, 30, 1, 2, 3); var to = new Date(2015, 5, 1, 12, 5 , 6); expect(pattern.getIndexList(from, to)).to.eql('my-metrics'); }); }); describe('daily', function() { it('should return correct index list', function() { var pattern = new IndexPattern('[asd-]YYYY.MM.DD', 'Daily'); var from = new Date(1432940523000); var to = new Date(1433153106000); var expected = [ 'asd-2015.05.29', 'asd-2015.05.30', 'asd-2015.05.31', 'asd-2015.06.01', ]; expect(pattern.getIndexList(from, to)).to.eql(expected); }); }); }); });
public/app/plugins/datasource/elasticsearch/specs/index_pattern_specs.ts
1
https://github.com/grafana/grafana/commit/ae93f2b936cda93b8141a6ff61adb18037aca4ab
[ 0.0011077510425820947, 0.00039463466964662075, 0.00016697168757673353, 0.00017435454356018454, 0.0003511445829644799 ]
{ "id": 6, "code_window": [ " expect(header.index).to.eql(['asd-2015.05.30', 'asd-2015.05.31', 'asd-2015.06.01']);\n", " });\n", " });\n", "});" ], "labels": [ "keep", "add", "keep", "keep" ], "after_edit": [ "\n", " it('should json escape lucene query', function() {\n", " var body = angular.fromJson(parts[1]);\n", " expect(body.query.filtered.query.query_string.query).to.be('escape\\\\:test');\n", " });\n" ], "file_path": "public/app/plugins/datasource/elasticsearch/specs/datasource_specs.ts", "type": "add", "edit_start_line_idx": 72 }
{ "pluginType": "datasource", "name": "CloudWatch", "type": "cloudwatch", "serviceName": "CloudWatchDatasource", "module": "app/plugins/datasource/cloudwatch/datasource", "partials": { "config": "app/plugins/datasource/cloudwatch/partials/config.html", "query": "app/plugins/datasource/cloudwatch/partials/query.editor.html" }, "metrics": true }
public/app/plugins/datasource/cloudwatch/plugin.json
0
https://github.com/grafana/grafana/commit/ae93f2b936cda93b8141a6ff61adb18037aca4ab
[ 0.00017472784384153783, 0.00017160791321657598, 0.00016848799714352936, 0.00017160791321657598, 0.000003119923349004239 ]
{ "id": 6, "code_window": [ " expect(header.index).to.eql(['asd-2015.05.30', 'asd-2015.05.31', 'asd-2015.06.01']);\n", " });\n", " });\n", "});" ], "labels": [ "keep", "add", "keep", "keep" ], "after_edit": [ "\n", " it('should json escape lucene query', function() {\n", " var body = angular.fromJson(parts[1]);\n", " expect(body.query.filtered.query.query_string.query).to.be('escape\\\\:test');\n", " });\n" ], "file_path": "public/app/plugins/datasource/elasticsearch/specs/datasource_specs.ts", "type": "add", "edit_start_line_idx": 72 }
package sqlstore import ( "fmt" "os" "path" "path/filepath" "strings" "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/log" m "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/sqlstore/migrations" "github.com/grafana/grafana/pkg/services/sqlstore/migrator" "github.com/grafana/grafana/pkg/setting" _ "github.com/go-sql-driver/mysql" "github.com/go-xorm/xorm" _ "github.com/lib/pq" _ "github.com/mattn/go-sqlite3" ) var ( x *xorm.Engine dialect migrator.Dialect HasEngine bool DbCfg struct { Type, Host, Name, User, Pwd, Path, SslMode string } UseSQLite3 bool ) func EnsureAdminUser() { statsQuery := m.GetSystemStatsQuery{} if err := bus.Dispatch(&statsQuery); err != nil { log.Fatal(3, "Could not determine if admin user exists: %v", err) return } if statsQuery.Result.UserCount > 0 { return } cmd := m.CreateUserCommand{} cmd.Login = setting.AdminUser cmd.Email = setting.AdminUser + "@localhost" cmd.Password = setting.AdminPassword cmd.IsAdmin = true if err := bus.Dispatch(&cmd); err != nil { log.Error(3, "Failed to create default admin user", err) return } log.Info("Created default admin user: %v", setting.AdminUser) } func NewEngine() { x, err := getEngine() if err != nil { log.Fatal(3, "Sqlstore: Fail to connect to database: %v", err) } err = SetEngine(x, true) if err != nil { log.Fatal(3, "fail to initialize orm engine: %v", err) } } func SetEngine(engine *xorm.Engine, enableLog bool) (err error) { x = engine dialect = migrator.NewDialect(x.DriverName()) migrator := migrator.NewMigrator(x) migrator.LogLevel = log.INFO migrations.AddMigrations(migrator) if err := migrator.Start(); err != nil { return fmt.Errorf("Sqlstore::Migration failed err: %v\n", err) } if enableLog { logPath := path.Join(setting.LogsPath, "xorm.log") os.MkdirAll(path.Dir(logPath), os.ModePerm) f, err := os.Create(logPath) if err != nil { return fmt.Errorf("sqlstore.init(fail to create xorm.log): %v", err) } x.Logger = xorm.NewSimpleLogger(f) if setting.Env == setting.DEV { x.ShowSQL = false x.ShowInfo = false x.ShowDebug = false x.ShowErr = true x.ShowWarn = true } } return nil } func getEngine() (*xorm.Engine, error) { LoadConfig() cnnstr := "" switch DbCfg.Type { case "mysql": cnnstr = fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8", DbCfg.User, DbCfg.Pwd, DbCfg.Host, DbCfg.Name) case "postgres": var host, port = "127.0.0.1", "5432" fields := strings.Split(DbCfg.Host, ":") if len(fields) > 0 && len(strings.TrimSpace(fields[0])) > 0 { host = fields[0] } if len(fields) > 1 && len(strings.TrimSpace(fields[1])) > 0 { port = fields[1] } cnnstr = fmt.Sprintf("user=%s password=%s host=%s port=%s dbname=%s sslmode=%s", DbCfg.User, DbCfg.Pwd, host, port, DbCfg.Name, DbCfg.SslMode) case "sqlite3": if !filepath.IsAbs(DbCfg.Path) { DbCfg.Path = filepath.Join(setting.DataPath, DbCfg.Path) } os.MkdirAll(path.Dir(DbCfg.Path), os.ModePerm) cnnstr = "file:" + DbCfg.Path + "?cache=shared&mode=rwc&_loc=Local" default: return nil, fmt.Errorf("Unknown database type: %s", DbCfg.Type) } log.Info("Database: %v", DbCfg.Type) return xorm.NewEngine(DbCfg.Type, cnnstr) } func LoadConfig() { sec := setting.Cfg.Section("database") DbCfg.Type = sec.Key("type").String() if DbCfg.Type == "sqlite3" { UseSQLite3 = true } DbCfg.Host = sec.Key("host").String() DbCfg.Name = sec.Key("name").String() DbCfg.User = sec.Key("user").String() if len(DbCfg.Pwd) == 0 { DbCfg.Pwd = sec.Key("password").String() } DbCfg.SslMode = sec.Key("ssl_mode").String() DbCfg.Path = sec.Key("path").MustString("data/grafana.db") }
pkg/services/sqlstore/sqlstore.go
0
https://github.com/grafana/grafana/commit/ae93f2b936cda93b8141a6ff61adb18037aca4ab
[ 0.00019686640007421374, 0.0001726627815514803, 0.00016596232308074832, 0.00017233152175322175, 0.000007108759746188298 ]
{ "id": 6, "code_window": [ " expect(header.index).to.eql(['asd-2015.05.30', 'asd-2015.05.31', 'asd-2015.06.01']);\n", " });\n", " });\n", "});" ], "labels": [ "keep", "add", "keep", "keep" ], "after_edit": [ "\n", " it('should json escape lucene query', function() {\n", " var body = angular.fromJson(parts[1]);\n", " expect(body.query.filtered.query.query_string.query).to.be('escape\\\\:test');\n", " });\n" ], "file_path": "public/app/plugins/datasource/elasticsearch/specs/datasource_specs.ts", "type": "add", "edit_start_line_idx": 72 }
/* * Copyright (c) 2013 Dave Collins <[email protected]> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ package spew import ( "bytes" "fmt" "reflect" "strconv" "strings" ) // supportedFlags is a list of all the character flags supported by fmt package. const supportedFlags = "0-+# " // formatState implements the fmt.Formatter interface and contains information // about the state of a formatting operation. The NewFormatter function can // be used to get a new Formatter which can be used directly as arguments // in standard fmt package printing calls. type formatState struct { value interface{} fs fmt.State depth int pointers map[uintptr]int ignoreNextType bool cs *ConfigState } // buildDefaultFormat recreates the original format string without precision // and width information to pass in to fmt.Sprintf in the case of an // unrecognized type. Unless new types are added to the language, this // function won't ever be called. func (f *formatState) buildDefaultFormat() (format string) { buf := bytes.NewBuffer(percentBytes) for _, flag := range supportedFlags { if f.fs.Flag(int(flag)) { buf.WriteRune(flag) } } buf.WriteRune('v') format = buf.String() return format } // constructOrigFormat recreates the original format string including precision // and width information to pass along to the standard fmt package. This allows // automatic deferral of all format strings this package doesn't support. func (f *formatState) constructOrigFormat(verb rune) (format string) { buf := bytes.NewBuffer(percentBytes) for _, flag := range supportedFlags { if f.fs.Flag(int(flag)) { buf.WriteRune(flag) } } if width, ok := f.fs.Width(); ok { buf.WriteString(strconv.Itoa(width)) } if precision, ok := f.fs.Precision(); ok { buf.Write(precisionBytes) buf.WriteString(strconv.Itoa(precision)) } buf.WriteRune(verb) format = buf.String() return format } // unpackValue returns values inside of non-nil interfaces when possible and // ensures that types for values which have been unpacked from an interface // are displayed when the show types flag is also set. // This is useful for data types like structs, arrays, slices, and maps which // can contain varying types packed inside an interface. func (f *formatState) unpackValue(v reflect.Value) reflect.Value { if v.Kind() == reflect.Interface { f.ignoreNextType = false if !v.IsNil() { v = v.Elem() } } return v } // formatPtr handles formatting of pointers by indirecting them as necessary. func (f *formatState) formatPtr(v reflect.Value) { // Display nil if top level pointer is nil. showTypes := f.fs.Flag('#') if v.IsNil() && (!showTypes || f.ignoreNextType) { f.fs.Write(nilAngleBytes) return } // Remove pointers at or below the current depth from map used to detect // circular refs. for k, depth := range f.pointers { if depth >= f.depth { delete(f.pointers, k) } } // Keep list of all dereferenced pointers to possibly show later. pointerChain := make([]uintptr, 0) // Figure out how many levels of indirection there are by derferencing // pointers and unpacking interfaces down the chain while detecting circular // references. nilFound := false cycleFound := false indirects := 0 ve := v for ve.Kind() == reflect.Ptr { if ve.IsNil() { nilFound = true break } indirects++ addr := ve.Pointer() pointerChain = append(pointerChain, addr) if pd, ok := f.pointers[addr]; ok && pd < f.depth { cycleFound = true indirects-- break } f.pointers[addr] = f.depth ve = ve.Elem() if ve.Kind() == reflect.Interface { if ve.IsNil() { nilFound = true break } ve = ve.Elem() } } // Display type or indirection level depending on flags. if showTypes && !f.ignoreNextType { f.fs.Write(openParenBytes) f.fs.Write(bytes.Repeat(asteriskBytes, indirects)) f.fs.Write([]byte(ve.Type().String())) f.fs.Write(closeParenBytes) } else { if nilFound || cycleFound { indirects += strings.Count(ve.Type().String(), "*") } f.fs.Write(openAngleBytes) f.fs.Write([]byte(strings.Repeat("*", indirects))) f.fs.Write(closeAngleBytes) } // Display pointer information depending on flags. if f.fs.Flag('+') && (len(pointerChain) > 0) { f.fs.Write(openParenBytes) for i, addr := range pointerChain { if i > 0 { f.fs.Write(pointerChainBytes) } printHexPtr(f.fs, addr) } f.fs.Write(closeParenBytes) } // Display dereferenced value. switch { case nilFound == true: f.fs.Write(nilAngleBytes) case cycleFound == true: f.fs.Write(circularShortBytes) default: f.ignoreNextType = true f.format(ve) } } // format is the main workhorse for providing the Formatter interface. It // uses the passed reflect value to figure out what kind of object we are // dealing with and formats it appropriately. It is a recursive function, // however circular data structures are detected and handled properly. func (f *formatState) format(v reflect.Value) { // Handle invalid reflect values immediately. kind := v.Kind() if kind == reflect.Invalid { f.fs.Write(invalidAngleBytes) return } // Handle pointers specially. if kind == reflect.Ptr { f.formatPtr(v) return } // Print type information unless already handled elsewhere. if !f.ignoreNextType && f.fs.Flag('#') { f.fs.Write(openParenBytes) f.fs.Write([]byte(v.Type().String())) f.fs.Write(closeParenBytes) } f.ignoreNextType = false // Call Stringer/error interfaces if they exist and the handle methods // flag is enabled. if !f.cs.DisableMethods { if (kind != reflect.Invalid) && (kind != reflect.Interface) { if handled := handleMethods(f.cs, f.fs, v); handled { return } } } switch kind { case reflect.Invalid: // Do nothing. We should never get here since invalid has already // been handled above. case reflect.Bool: printBool(f.fs, v.Bool()) case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int: printInt(f.fs, v.Int(), 10) case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint: printUint(f.fs, v.Uint(), 10) case reflect.Float32: printFloat(f.fs, v.Float(), 32) case reflect.Float64: printFloat(f.fs, v.Float(), 64) case reflect.Complex64: printComplex(f.fs, v.Complex(), 32) case reflect.Complex128: printComplex(f.fs, v.Complex(), 64) case reflect.Slice: if v.IsNil() { f.fs.Write(nilAngleBytes) break } fallthrough case reflect.Array: f.fs.Write(openBracketBytes) f.depth++ if (f.cs.MaxDepth != 0) && (f.depth > f.cs.MaxDepth) { f.fs.Write(maxShortBytes) } else { numEntries := v.Len() for i := 0; i < numEntries; i++ { if i > 0 { f.fs.Write(spaceBytes) } f.ignoreNextType = true f.format(f.unpackValue(v.Index(i))) } } f.depth-- f.fs.Write(closeBracketBytes) case reflect.String: f.fs.Write([]byte(v.String())) case reflect.Interface: // The only time we should get here is for nil interfaces due to // unpackValue calls. if v.IsNil() { f.fs.Write(nilAngleBytes) } case reflect.Ptr: // Do nothing. We should never get here since pointers have already // been handled above. case reflect.Map: // nil maps should be indicated as different than empty maps if v.IsNil() { f.fs.Write(nilAngleBytes) break } f.fs.Write(openMapBytes) f.depth++ if (f.cs.MaxDepth != 0) && (f.depth > f.cs.MaxDepth) { f.fs.Write(maxShortBytes) } else { keys := v.MapKeys() if f.cs.SortKeys { sortValues(keys, f.cs) } for i, key := range keys { if i > 0 { f.fs.Write(spaceBytes) } f.ignoreNextType = true f.format(f.unpackValue(key)) f.fs.Write(colonBytes) f.ignoreNextType = true f.format(f.unpackValue(v.MapIndex(key))) } } f.depth-- f.fs.Write(closeMapBytes) case reflect.Struct: numFields := v.NumField() f.fs.Write(openBraceBytes) f.depth++ if (f.cs.MaxDepth != 0) && (f.depth > f.cs.MaxDepth) { f.fs.Write(maxShortBytes) } else { vt := v.Type() for i := 0; i < numFields; i++ { if i > 0 { f.fs.Write(spaceBytes) } vtf := vt.Field(i) if f.fs.Flag('+') || f.fs.Flag('#') { f.fs.Write([]byte(vtf.Name)) f.fs.Write(colonBytes) } f.format(f.unpackValue(v.Field(i))) } } f.depth-- f.fs.Write(closeBraceBytes) case reflect.Uintptr: printHexPtr(f.fs, uintptr(v.Uint())) case reflect.UnsafePointer, reflect.Chan, reflect.Func: printHexPtr(f.fs, v.Pointer()) // There were not any other types at the time this code was written, but // fall back to letting the default fmt package handle it if any get added. default: format := f.buildDefaultFormat() if v.CanInterface() { fmt.Fprintf(f.fs, format, v.Interface()) } else { fmt.Fprintf(f.fs, format, v.String()) } } } // Format satisfies the fmt.Formatter interface. See NewFormatter for usage // details. func (f *formatState) Format(fs fmt.State, verb rune) { f.fs = fs // Use standard formatting for verbs that are not v. if verb != 'v' { format := f.constructOrigFormat(verb) fmt.Fprintf(fs, format, f.value) return } if f.value == nil { if fs.Flag('#') { fs.Write(interfaceBytes) } fs.Write(nilAngleBytes) return } f.format(reflect.ValueOf(f.value)) } // newFormatter is a helper function to consolidate the logic from the various // public methods which take varying config states. func newFormatter(cs *ConfigState, v interface{}) fmt.Formatter { fs := &formatState{value: v, cs: cs} fs.pointers = make(map[uintptr]int) return fs } /* NewFormatter returns a custom formatter that satisfies the fmt.Formatter interface. As a result, it integrates cleanly with standard fmt package printing functions. The formatter is useful for inline printing of smaller data types similar to the standard %v format specifier. The custom formatter only responds to the %v (most compact), %+v (adds pointer addresses), %#v (adds types), or %#+v (adds types and pointer addresses) verb combinations. Any other verbs such as %x and %q will be sent to the the standard fmt package for formatting. In addition, the custom formatter ignores the width and precision arguments (however they will still work on the format specifiers not handled by the custom formatter). Typically this function shouldn't be called directly. It is much easier to make use of the custom formatter by calling one of the convenience functions such as Printf, Println, or Fprintf. */ func NewFormatter(v interface{}) fmt.Formatter { return newFormatter(&Config, v) }
Godeps/_workspace/src/github.com/davecgh/go-spew/spew/format.go
0
https://github.com/grafana/grafana/commit/ae93f2b936cda93b8141a6ff61adb18037aca4ab
[ 0.0005122493603266776, 0.00018250795255880803, 0.00016448112728539854, 0.00017264489724766463, 0.00005322485594660975 ]
{ "id": 7, "code_window": [ "\n", "declare var IndexPattern: any;\n", "\n", "describe('IndexPattern', function() {\n", "\n", " describe.only('when getting index for today', function() {\n", " it('should return correct index name', function() {\n", " var pattern = new IndexPattern('[asd-]YYYY.MM.DD', 'Daily');\n", " var expected = 'asd-' + moment().format('YYYY.MM.DD');\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " describe('when getting index for today', function() {\n" ], "file_path": "public/app/plugins/datasource/elasticsearch/specs/index_pattern_specs.ts", "type": "replace", "edit_start_line_idx": 10 }
///<amd-dependency path="../datasource" /> ///<amd-dependency path="test/specs/helpers" name="helpers" /> import {describe, beforeEach, it, sinon, expect, angularMocks} from 'test/lib/common'; import moment = require('moment'); import angular = require('angular'); declare var helpers: any; describe('ElasticDatasource', function() { var ctx = new helpers.ServiceTestContext(); beforeEach(angularMocks.module('grafana.services')); beforeEach(ctx.providePhase(['templateSrv', 'backendSrv'])); beforeEach(ctx.createService('ElasticDatasource')); beforeEach(function() { ctx.ds = new ctx.service({jsonData: {}}); }); describe('When testing datasource with index pattern', function() { beforeEach(function() { ctx.ds = new ctx.service({ url: 'http://es.com', index: '[asd-]YYYY.MM.DD', jsonData: { interval: 'Daily' } }); }); it('should translate index pattern to current day', function() { var requestOptions; ctx.backendSrv.datasourceRequest = function(options) { requestOptions = options; return ctx.$q.when({}); }; ctx.ds.testDatasource(); ctx.$rootScope.$apply(); var today = moment().format("YYYY.MM.DD"); expect(requestOptions.url).to.be("http://es.com/asd-" + today + '/_stats'); }); }); describe('When issueing metric query with interval pattern', function() { beforeEach(function() { ctx.ds = new ctx.service({ url: 'http://es.com', index: '[asd-]YYYY.MM.DD', jsonData: { interval: 'Daily' } }); }); it('should translate index pattern to current day', function() { var requestOptions; ctx.backendSrv.datasourceRequest = function(options) { requestOptions = options; return ctx.$q.when({data: {responses: []}}); }; ctx.ds.query({ range: { from: moment([2015, 4, 30, 10]), to: moment([2015, 5, 1, 10]) }, targets: [{ bucketAggs: [], metrics: [] }] }); ctx.$rootScope.$apply(); var parts = requestOptions.data.split('\n'); var header = angular.fromJson(parts[0]); expect(header.index).to.eql(['asd-2015.05.30', 'asd-2015.05.31', 'asd-2015.06.01']); }); }); });
public/app/plugins/datasource/elasticsearch/specs/datasource_specs.ts
1
https://github.com/grafana/grafana/commit/ae93f2b936cda93b8141a6ff61adb18037aca4ab
[ 0.003605916630476713, 0.00099688651971519, 0.00016478834731969982, 0.0005373490857891738, 0.0011076549999415874 ]
{ "id": 7, "code_window": [ "\n", "declare var IndexPattern: any;\n", "\n", "describe('IndexPattern', function() {\n", "\n", " describe.only('when getting index for today', function() {\n", " it('should return correct index name', function() {\n", " var pattern = new IndexPattern('[asd-]YYYY.MM.DD', 'Daily');\n", " var expected = 'asd-' + moment().format('YYYY.MM.DD');\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " describe('when getting index for today', function() {\n" ], "file_path": "public/app/plugins/datasource/elasticsearch/specs/index_pattern_specs.ts", "type": "replace", "edit_start_line_idx": 10 }
package queryutil import ( "encoding/base64" "fmt" "net/url" "reflect" "sort" "strconv" "strings" "time" ) // Parse parses an object i and fills a url.Values object. The isEC2 flag // indicates if this is the EC2 Query sub-protocol. func Parse(body url.Values, i interface{}, isEC2 bool) error { q := queryParser{isEC2: isEC2} return q.parseValue(body, reflect.ValueOf(i), "", "") } func elemOf(value reflect.Value) reflect.Value { for value.Kind() == reflect.Ptr { value = value.Elem() } return value } type queryParser struct { isEC2 bool } func (q *queryParser) parseValue(v url.Values, value reflect.Value, prefix string, tag reflect.StructTag) error { value = elemOf(value) // no need to handle zero values if !value.IsValid() { return nil } t := tag.Get("type") if t == "" { switch value.Kind() { case reflect.Struct: t = "structure" case reflect.Slice: t = "list" case reflect.Map: t = "map" } } switch t { case "structure": return q.parseStruct(v, value, prefix) case "list": return q.parseList(v, value, prefix, tag) case "map": return q.parseMap(v, value, prefix, tag) default: return q.parseScalar(v, value, prefix, tag) } } func (q *queryParser) parseStruct(v url.Values, value reflect.Value, prefix string) error { if !value.IsValid() { return nil } t := value.Type() for i := 0; i < value.NumField(); i++ { if c := t.Field(i).Name[0:1]; strings.ToLower(c) == c { continue // ignore unexported fields } value := elemOf(value.Field(i)) field := t.Field(i) var name string if q.isEC2 { name = field.Tag.Get("queryName") } if name == "" { if field.Tag.Get("flattened") != "" && field.Tag.Get("locationNameList") != "" { name = field.Tag.Get("locationNameList") } else if locName := field.Tag.Get("locationName"); locName != "" { name = locName } if name != "" && q.isEC2 { name = strings.ToUpper(name[0:1]) + name[1:] } } if name == "" { name = field.Name } if prefix != "" { name = prefix + "." + name } if err := q.parseValue(v, value, name, field.Tag); err != nil { return err } } return nil } func (q *queryParser) parseList(v url.Values, value reflect.Value, prefix string, tag reflect.StructTag) error { // If it's empty, generate an empty value if !value.IsNil() && value.Len() == 0 { v.Set(prefix, "") return nil } // check for unflattened list member if !q.isEC2 && tag.Get("flattened") == "" { prefix += ".member" } for i := 0; i < value.Len(); i++ { slicePrefix := prefix if slicePrefix == "" { slicePrefix = strconv.Itoa(i + 1) } else { slicePrefix = slicePrefix + "." + strconv.Itoa(i+1) } if err := q.parseValue(v, value.Index(i), slicePrefix, ""); err != nil { return err } } return nil } func (q *queryParser) parseMap(v url.Values, value reflect.Value, prefix string, tag reflect.StructTag) error { // If it's empty, generate an empty value if !value.IsNil() && value.Len() == 0 { v.Set(prefix, "") return nil } // check for unflattened list member if !q.isEC2 && tag.Get("flattened") == "" { prefix += ".entry" } // sort keys for improved serialization consistency. // this is not strictly necessary for protocol support. mapKeyValues := value.MapKeys() mapKeys := map[string]reflect.Value{} mapKeyNames := make([]string, len(mapKeyValues)) for i, mapKey := range mapKeyValues { name := mapKey.String() mapKeys[name] = mapKey mapKeyNames[i] = name } sort.Strings(mapKeyNames) for i, mapKeyName := range mapKeyNames { mapKey := mapKeys[mapKeyName] mapValue := value.MapIndex(mapKey) kname := tag.Get("locationNameKey") if kname == "" { kname = "key" } vname := tag.Get("locationNameValue") if vname == "" { vname = "value" } // serialize key var keyName string if prefix == "" { keyName = strconv.Itoa(i+1) + "." + kname } else { keyName = prefix + "." + strconv.Itoa(i+1) + "." + kname } if err := q.parseValue(v, mapKey, keyName, ""); err != nil { return err } // serialize value var valueName string if prefix == "" { valueName = strconv.Itoa(i+1) + "." + vname } else { valueName = prefix + "." + strconv.Itoa(i+1) + "." + vname } if err := q.parseValue(v, mapValue, valueName, ""); err != nil { return err } } return nil } func (q *queryParser) parseScalar(v url.Values, r reflect.Value, name string, tag reflect.StructTag) error { switch value := r.Interface().(type) { case string: v.Set(name, value) case []byte: if !r.IsNil() { v.Set(name, base64.StdEncoding.EncodeToString(value)) } case bool: v.Set(name, strconv.FormatBool(value)) case int64: v.Set(name, strconv.FormatInt(value, 10)) case int: v.Set(name, strconv.Itoa(value)) case float64: v.Set(name, strconv.FormatFloat(value, 'f', -1, 64)) case float32: v.Set(name, strconv.FormatFloat(float64(value), 'f', -1, 32)) case time.Time: const ISO8601UTC = "2006-01-02T15:04:05Z" v.Set(name, value.UTC().Format(ISO8601UTC)) default: return fmt.Errorf("unsupported value for param %s: %v (%s)", name, r.Interface(), r.Type().Name()) } return nil }
Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/query/queryutil/queryutil.go
0
https://github.com/grafana/grafana/commit/ae93f2b936cda93b8141a6ff61adb18037aca4ab
[ 0.00017800666682887822, 0.00017368944827467203, 0.00016438549209851772, 0.00017408592975698411, 0.0000033885992252180586 ]
{ "id": 7, "code_window": [ "\n", "declare var IndexPattern: any;\n", "\n", "describe('IndexPattern', function() {\n", "\n", " describe.only('when getting index for today', function() {\n", " it('should return correct index name', function() {\n", " var pattern = new IndexPattern('[asd-]YYYY.MM.DD', 'Daily');\n", " var expected = 'asd-' + moment().format('YYYY.MM.DD');\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " describe('when getting index for today', function() {\n" ], "file_path": "public/app/plugins/datasource/elasticsearch/specs/index_pattern_specs.ts", "type": "replace", "edit_start_line_idx": 10 }
define([ 'angular', './bucket_agg', './metric_agg', ], function (angular) { 'use strict'; var module = angular.module('grafana.directives'); module.directive('metricQueryEditorElasticsearch', function() { return {controller: 'ElasticQueryCtrl', templateUrl: 'app/plugins/datasource/elasticsearch/partials/query.editor.html'}; }); module.directive('metricQueryOptionsElasticsearch', function() { return {templateUrl: 'app/plugins/datasource/elasticsearch/partials/query.options.html'}; }); module.directive('annotationsQueryEditorElasticsearch', function() { return {templateUrl: 'app/plugins/datasource/elasticsearch/partials/annotations.editor.html'}; }); module.directive('elasticMetricAgg', function() { return { templateUrl: 'app/plugins/datasource/elasticsearch/partials/metricAgg.html', controller: 'ElasticMetricAggCtrl', restrict: 'E', scope: { target: "=", index: "=", onChange: "&", getFields: "&", } }; }); module.directive('elasticBucketAgg', function() { return { templateUrl: 'app/plugins/datasource/elasticsearch/partials/bucketAgg.html', controller: 'ElasticBucketAggCtrl', restrict: 'E', scope: { target: "=", index: "=", onChange: "&", getFields: "&", } }; }); });
public/app/plugins/datasource/elasticsearch/directives.js
0
https://github.com/grafana/grafana/commit/ae93f2b936cda93b8141a6ff61adb18037aca4ab
[ 0.000174739005160518, 0.00017160158313345164, 0.0001673476945143193, 0.0001722096058074385, 0.0000027607961783360224 ]
{ "id": 7, "code_window": [ "\n", "declare var IndexPattern: any;\n", "\n", "describe('IndexPattern', function() {\n", "\n", " describe.only('when getting index for today', function() {\n", " it('should return correct index name', function() {\n", " var pattern = new IndexPattern('[asd-]YYYY.MM.DD', 'Daily');\n", " var expected = 'asd-' + moment().format('YYYY.MM.DD');\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " describe('when getting index for today', function() {\n" ], "file_path": "public/app/plugins/datasource/elasticsearch/specs/index_pattern_specs.ts", "type": "replace", "edit_start_line_idx": 10 }
// // Popovers // -------------------------------------------------- .popover { position: absolute; top: 0; left: 0; z-index: @zindexPopover; display: none; max-width: 276px; padding: 1px; text-align: left; // Reset given new insertion method background-color: @popoverBackground; -webkit-background-clip: padding-box; -moz-background-clip: padding; background-clip: padding-box; border: 1px solid #ccc; border: 1px solid rgba(0,0,0,.2); .border-radius(6px); .box-shadow(0 5px 10px rgba(0,0,0,.2)); // Overrides for proper insertion white-space: normal; // Offset the popover to account for the popover arrow &.top { margin-top: -10px; } &.right { margin-left: 10px; } &.bottom { margin-top: 10px; } &.left { margin-left: -10px; } } .popover-title { margin: 0; // reset heading margin padding: 8px 14px; font-size: 14px; font-weight: normal; line-height: 18px; background-color: @popoverTitleBackground; border-bottom: 1px solid darken(@popoverTitleBackground, 5%); .border-radius(5px 5px 0 0); &:empty { display: none; } } .popover-content { padding: 9px 14px; } // Arrows // // .arrow is outer, .arrow:after is inner .popover .arrow, .popover .arrow:after { position: absolute; display: block; width: 0; height: 0; border-color: transparent; border-style: solid; } .popover .arrow { border-width: @popoverArrowOuterWidth; } .popover .arrow:after { border-width: @popoverArrowWidth; content: ""; } .popover { &.top .arrow { left: 50%; margin-left: -@popoverArrowOuterWidth; border-bottom-width: 0; border-top-color: #999; // IE8 fallback border-top-color: @popoverArrowOuterColor; bottom: -@popoverArrowOuterWidth; &:after { bottom: 1px; margin-left: -@popoverArrowWidth; border-bottom-width: 0; border-top-color: @popoverArrowColor; } } &.right .arrow { top: 50%; left: -@popoverArrowOuterWidth; margin-top: -@popoverArrowOuterWidth; border-left-width: 0; border-right-color: #999; // IE8 fallback border-right-color: @popoverArrowOuterColor; &:after { left: 1px; bottom: -@popoverArrowWidth; border-left-width: 0; border-right-color: @popoverArrowColor; } } &.bottom .arrow { left: 50%; margin-left: -@popoverArrowOuterWidth; border-top-width: 0; border-bottom-color: #999; // IE8 fallback border-bottom-color: @popoverArrowOuterColor; top: -@popoverArrowOuterWidth; &:after { top: 1px; margin-left: -@popoverArrowWidth; border-top-width: 0; border-bottom-color: @popoverArrowColor; } } &.left .arrow { top: 50%; right: -@popoverArrowOuterWidth; margin-top: -@popoverArrowOuterWidth; border-right-width: 0; border-left-color: #999; // IE8 fallback border-left-color: @popoverArrowOuterColor; &:after { right: 1px; border-right-width: 0; border-left-color: @popoverArrowColor; bottom: -@popoverArrowWidth; } } }
public/vendor/bootstrap/less/popovers.less
0
https://github.com/grafana/grafana/commit/ae93f2b936cda93b8141a6ff61adb18037aca4ab
[ 0.0001784876367310062, 0.0001761177263688296, 0.0001710103388177231, 0.00017652912356425077, 0.0000017533228628963116 ]
{ "id": 0, "code_window": [ " padding: ${theme.spacing(1)};\n", " background: ${theme.colors.background.primary};\n", " border: 1px solid ${theme.components.panel.borderColor};\n", " border-bottom: none;\n", " `,\n", " closeButton: css`\n", " margin-left: ${theme.spacing(1)};\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " border-top-left-radius: ${theme.shape.borderRadius(1.5)};\n" ], "file_path": "public/app/features/dashboard/components/PanelEditor/OptionsPaneOptions.tsx", "type": "add", "edit_start_line_idx": 175 }
import React, { useMemo, useState } from 'react'; import { GrafanaTheme2, SelectableValue } from '@grafana/data'; import { CustomScrollbar, FilterInput, RadioButtonGroup, useStyles2 } from '@grafana/ui'; import { getPanelFrameCategory } from './getPanelFrameOptions'; import { getVizualizationOptions } from './getVizualizationOptions'; import { css } from '@emotion/css'; import { OptionsPaneCategory } from './OptionsPaneCategory'; import { getFieldOverrideCategories } from './getFieldOverrideElements'; import { OptionsPaneCategoryDescriptor } from './OptionsPaneCategoryDescriptor'; import { OptionSearchEngine } from './state/OptionSearchEngine'; import { AngularPanelOptions } from './AngularPanelOptions'; import { getRecentOptions } from './state/getRecentOptions'; import { isPanelModelLibraryPanel } from '../../../library-panels/guard'; import { getLibraryPanelOptionsCategory } from './getLibraryPanelOptions'; import { OptionPaneRenderProps } from './types'; export const OptionsPaneOptions: React.FC<OptionPaneRenderProps> = (props) => { const { plugin, dashboard, panel } = props; const [searchQuery, setSearchQuery] = useState(''); const [listMode, setListMode] = useState(OptionFilter.All); const styles = useStyles2(getStyles); const [panelFrameOptions, vizOptions, justOverrides, libraryPanelOptions] = useMemo( () => [ getPanelFrameCategory(props), getVizualizationOptions(props), getFieldOverrideCategories(props), getLibraryPanelOptionsCategory(props), ], // eslint-disable-next-line react-hooks/exhaustive-deps [panel.configRev, props.data, props.instanceState] ); const mainBoxElements: React.ReactNode[] = []; const isSearching = searchQuery.length > 0; const optionRadioFilters = useMemo(getOptionRadioFilters, []); const allOptions = isPanelModelLibraryPanel(panel) ? [libraryPanelOptions, panelFrameOptions, ...vizOptions] : [panelFrameOptions, ...vizOptions]; if (isSearching) { mainBoxElements.push(renderSearchHits(allOptions, justOverrides, searchQuery)); // If searching for angular panel, then we need to add notice that results are limited if (props.plugin.angularPanelCtrl) { mainBoxElements.push( <div className={styles.searchNotice} key="Search notice"> This is an old visualization type that does not support searching all options. </div> ); } } else { switch (listMode) { case OptionFilter.All: if (isPanelModelLibraryPanel(panel)) { // Library Panel options first mainBoxElements.push(libraryPanelOptions.render()); } // Panel frame options second mainBoxElements.push(panelFrameOptions.render()); // If angular add those options next if (props.plugin.angularPanelCtrl) { mainBoxElements.push( <AngularPanelOptions plugin={plugin} dashboard={dashboard} panel={panel} key="AngularOptions" /> ); } // Then add all panel and field defaults for (const item of vizOptions) { mainBoxElements.push(item.render()); } for (const item of justOverrides) { mainBoxElements.push(item.render()); } break; case OptionFilter.Overrides: for (const override of justOverrides) { mainBoxElements.push(override.render()); } break; case OptionFilter.Recent: mainBoxElements.push( <OptionsPaneCategory id="Recent options" title="Recent options" key="Recent options" forceOpen={1}> {getRecentOptions(allOptions).map((item) => item.render())} </OptionsPaneCategory> ); break; } } // only show radio buttons if we are searching or if the plugin has field config const showSearchRadioButtons = !isSearching && !plugin.fieldConfigRegistry.isEmpty(); return ( <div className={styles.wrapper}> <div className={styles.formBox}> <div className={styles.formRow}> <FilterInput width={0} value={searchQuery} onChange={setSearchQuery} placeholder={'Search options'} /> </div> {showSearchRadioButtons && ( <div className={styles.formRow}> <RadioButtonGroup options={optionRadioFilters} value={listMode} fullWidth onChange={setListMode} /> </div> )} </div> <div className={styles.scrollWrapper}> <CustomScrollbar autoHeightMin="100%"> <div className={styles.mainBox}>{mainBoxElements}</div> </CustomScrollbar> </div> </div> ); }; function getOptionRadioFilters(): Array<SelectableValue<OptionFilter>> { return [ { label: OptionFilter.All, value: OptionFilter.All }, { label: OptionFilter.Overrides, value: OptionFilter.Overrides }, ]; } export enum OptionFilter { All = 'All', Overrides = 'Overrides', Recent = 'Recent', } function renderSearchHits( allOptions: OptionsPaneCategoryDescriptor[], overrides: OptionsPaneCategoryDescriptor[], searchQuery: string ) { const engine = new OptionSearchEngine(allOptions, overrides); const { optionHits, totalCount, overrideHits } = engine.search(searchQuery); return ( <div key="search results"> <OptionsPaneCategory id="Found options" title={`Matched ${optionHits.length}/${totalCount} options`} key="Normal options" forceOpen={1} > {optionHits.map((hit) => hit.render(searchQuery))} </OptionsPaneCategory> {overrideHits.map((override) => override.render(searchQuery))} </div> ); } const getStyles = (theme: GrafanaTheme2) => ({ wrapper: css` height: 100%; display: flex; flex-direction: column; flex: 1 1 0; .search-fragment-highlight { color: ${theme.colors.warning.text}; background: transparent; } `, searchBox: css` display: flex; flex-direction: column; min-height: 0; `, formRow: css` margin-bottom: ${theme.spacing(1)}; `, formBox: css` padding: ${theme.spacing(1)}; background: ${theme.colors.background.primary}; border: 1px solid ${theme.components.panel.borderColor}; border-bottom: none; `, closeButton: css` margin-left: ${theme.spacing(1)}; `, searchHits: css` padding: ${theme.spacing(1, 1, 0, 1)}; `, scrollWrapper: css` flex-grow: 1; min-height: 0; `, searchNotice: css` font-size: ${theme.typography.size.sm}; color: ${theme.colors.text.secondary}; padding: ${theme.spacing(1)}; text-align: center; `, mainBox: css` background: ${theme.colors.background.primary}; border: 1px solid ${theme.components.panel.borderColor}; border-top: none; flex-grow: 1; `, });
public/app/features/dashboard/components/PanelEditor/OptionsPaneOptions.tsx
1
https://github.com/grafana/grafana/commit/78ebac0116c0aebd99d261c3f138819dc957bece
[ 0.9896255135536194, 0.08494745194911957, 0.0001633140491321683, 0.000183854324859567, 0.2556231617927551 ]
{ "id": 0, "code_window": [ " padding: ${theme.spacing(1)};\n", " background: ${theme.colors.background.primary};\n", " border: 1px solid ${theme.components.panel.borderColor};\n", " border-bottom: none;\n", " `,\n", " closeButton: css`\n", " margin-left: ${theme.spacing(1)};\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " border-top-left-radius: ${theme.shape.borderRadius(1.5)};\n" ], "file_path": "public/app/features/dashboard/components/PanelEditor/OptionsPaneOptions.tsx", "type": "add", "edit_start_line_idx": 175 }
import Centrifuge from 'centrifuge/dist/centrifuge'; import { GrafanaLiveSrv, setGrafanaLiveSrv, getGrafanaLiveSrv, config, LiveDataStreamOptions, toDataQueryError, getBackendSrv, } from '@grafana/runtime'; import { BehaviorSubject, Observable, of } from 'rxjs'; import { LiveChannelScope, LiveChannelAddress, LiveChannelConnectionState, LiveChannelConfig, LiveChannelEvent, DataQueryResponse, LiveChannelPresenceStatus, isValidLiveChannelAddress, LoadingState, DataFrameJSON, StreamingDataFrame, DataFrame, dataFrameToJSON, isLiveChannelMessageEvent, isLiveChannelStatusEvent, toLiveChannelId, } from '@grafana/data'; import { CentrifugeLiveChannel, getErrorChannel } from './channel'; import { GrafanaLiveScope, grafanaLiveCoreFeatures, GrafanaLiveDataSourceScope, GrafanaLivePluginScope, GrafanaLiveStreamScope, } from './scopes'; import { registerLiveFeatures } from './features'; import { contextSrv } from '../../core/services/context_srv'; import { liveTimer } from '../dashboard/dashgrid/liveTimer'; export const sessionId = (window as any)?.grafanaBootData?.user?.id + '/' + Date.now().toString(16) + '/' + Math.random().toString(36).substring(2, 15); export class CentrifugeSrv implements GrafanaLiveSrv { readonly open = new Map<string, CentrifugeLiveChannel>(); readonly centrifuge: Centrifuge; readonly connectionState: BehaviorSubject<boolean>; readonly connectionBlocker: Promise<void>; readonly scopes: Record<LiveChannelScope, GrafanaLiveScope>; private readonly orgId: number; constructor() { const baseURL = window.location.origin.replace('http', 'ws'); const liveUrl = `${baseURL}${config.appSubUrl}/api/live/ws`; this.orgId = contextSrv.user.orgId; this.centrifuge = new Centrifuge(liveUrl, {}); this.centrifuge.setConnectData({ sessionId, orgId: this.orgId, }); // orgRole is set when logged in *or* anonomus users can use grafana if (config.liveEnabled && contextSrv.user.orgRole !== '') { this.centrifuge.connect(); // do connection } this.connectionState = new BehaviorSubject<boolean>(this.centrifuge.isConnected()); this.connectionBlocker = new Promise<void>((resolve) => { if (this.centrifuge.isConnected()) { return resolve(); } const connectListener = () => { resolve(); this.centrifuge.removeListener('connect', connectListener); }; this.centrifuge.addListener('connect', connectListener); }); this.scopes = { [LiveChannelScope.Grafana]: grafanaLiveCoreFeatures, [LiveChannelScope.DataSource]: new GrafanaLiveDataSourceScope(), [LiveChannelScope.Plugin]: new GrafanaLivePluginScope(), [LiveChannelScope.Stream]: new GrafanaLiveStreamScope(), }; // Register global listeners this.centrifuge.on('connect', this.onConnect); this.centrifuge.on('disconnect', this.onDisconnect); this.centrifuge.on('publish', this.onServerSideMessage); } //---------------------------------------------------------- // Internal functions //---------------------------------------------------------- onConnect = (context: any) => { this.connectionState.next(true); }; onDisconnect = (context: any) => { this.connectionState.next(false); }; onServerSideMessage = (context: any) => { console.log('Publication from server-side channel', context); }; /** * Get a channel. If the scope, namespace, or path is invalid, a shutdown * channel will be returned with an error state indicated in its status */ getChannel<TMessage>(addr: LiveChannelAddress): CentrifugeLiveChannel<TMessage> { const id = `${this.orgId}/${addr.scope}/${addr.namespace}/${addr.path}`; let channel = this.open.get(id); if (channel != null) { return channel; } const scope = this.scopes[addr.scope]; if (!scope) { return getErrorChannel<TMessage>('invalid scope', id, addr) as any; } channel = new CentrifugeLiveChannel(id, addr); channel.shutdownCallback = () => { this.open.delete(id); // remove it from the list of open channels }; this.open.set(id, channel); // Initialize the channel in the background this.initChannel(scope, channel).catch((err) => { if (channel) { channel.currentStatus.state = LiveChannelConnectionState.Invalid; channel.shutdownWithError(err); } this.open.delete(id); }); // return the not-yet initalized channel return channel; } private async initChannel(scope: GrafanaLiveScope, channel: CentrifugeLiveChannel): Promise<void> { const { addr } = channel; const support = await scope.getChannelSupport(addr.namespace); if (!support) { throw new Error(channel.addr.namespace + ' does not support streaming'); } const config = support.getChannelConfig(addr.path); if (!config) { throw new Error('unknown path: ' + addr.path); } const events = channel.initalize(config); if (!this.centrifuge.isConnected()) { await this.connectionBlocker; } channel.subscription = this.centrifuge.subscribe(channel.id, events); return; } //---------------------------------------------------------- // Exported functions //---------------------------------------------------------- /** * Listen for changes to the connection state */ getConnectionState() { return this.connectionState.asObservable(); } /** * Get a channel. If the scope, namespace, or path is invalid, a shutdown * channel will be returned with an error state indicated in its status. * * This is a singleton instance that stays active until explicitly shutdown. * Multiple requests for this channel will return the same object until * the channel is shutdown */ async getChannelInfo(addr: LiveChannelAddress): Promise<LiveChannelConfig> { const scope = this.scopes[addr.scope]; if (!scope) { return Promise.reject('invalid scope'); } const support = await scope.getChannelSupport(addr.namespace); if (!support) { return Promise.reject(addr.namespace + ' does not support streaming'); } return support.getChannelConfig(addr.path)!; } /** * Watch for messages in a channel */ getStream<T>(address: LiveChannelAddress): Observable<LiveChannelEvent<T>> { return this.getChannel<T>(address).getStream(); } /** * Connect to a channel and return results as DataFrames */ getDataStream(options: LiveDataStreamOptions): Observable<DataQueryResponse> { if (!isValidLiveChannelAddress(options.addr)) { return of({ error: toDataQueryError(`invalid channel address: ${JSON.stringify(options.addr)}`), state: LoadingState.Error, data: options.frame ? [options.frame] : [], }); } return new Observable<DataQueryResponse>((subscriber) => { const channel = this.getChannel(options.addr); const key = options.key ?? `xstr/${streamCounter++}`; let data: StreamingDataFrame | undefined = undefined; let filtered: DataFrame | undefined = undefined; let state = LoadingState.Streaming; let last = liveTimer.lastUpdate; let lastWidth = -1; const process = (msg: DataFrameJSON) => { if (!data) { data = new StreamingDataFrame(msg, options.buffer); } else { data.push(msg); } state = LoadingState.Streaming; const sameWidth = lastWidth === data.fields.length; lastWidth = data.fields.length; // Filter out fields if (!filtered || msg.schema || !sameWidth) { filtered = data; if (options.filter) { const { fields } = options.filter; if (fields?.length) { filtered = { ...data, fields: data.fields.filter((f) => fields.includes(f.name)), }; } } } const elapsed = liveTimer.lastUpdate - last; if (elapsed > 1000 || liveTimer.ok) { filtered.length = data.length; // make sure they stay up-to-date subscriber.next({ state, data: [filtered], key }); last = liveTimer.lastUpdate; } }; if (options.frame) { process(dataFrameToJSON(options.frame)); } else if (channel.lastMessageWithSchema) { process(channel.lastMessageWithSchema); } const sub = channel.getStream().subscribe({ error: (err: any) => { console.log('LiveQuery [error]', { err }, options.addr); state = LoadingState.Error; subscriber.next({ state, data: [data], key, error: toDataQueryError(err) }); sub.unsubscribe(); // close after error }, complete: () => { console.log('LiveQuery [complete]', options.addr); if (state !== LoadingState.Error) { state = LoadingState.Done; } // or track errors? subscriber.next({ state, data: [data], key }); subscriber.complete(); sub.unsubscribe(); }, next: (evt: LiveChannelEvent) => { if (isLiveChannelMessageEvent(evt)) { process(evt.message); return; } if (isLiveChannelStatusEvent(evt)) { if (evt.error) { let error = toDataQueryError(evt.error); error.message = `Streaming channel error: ${error.message}`; state = LoadingState.Error; subscriber.next({ state, data: [data], key, error }); return; } else if ( evt.state === LiveChannelConnectionState.Connected || evt.state === LiveChannelConnectionState.Pending ) { if (evt.message) { process(evt.message); } return; } console.log('ignore state', evt); } }, }); return () => { sub.unsubscribe(); }; }); } /** * For channels that support presence, this will request the current state from the server. * * Join and leave messages will be sent to the open stream */ getPresence(address: LiveChannelAddress): Promise<LiveChannelPresenceStatus> { return this.getChannel(address).getPresence(); } /** * Publish into a channel * * @alpha -- experimental */ publish(address: LiveChannelAddress, data: any): Promise<any> { return getBackendSrv().post(`api/live/publish`, { channel: toLiveChannelId(address), // orgId is from user data, }); } } // This is used to give a unique key for each stream. The actual value does not matter let streamCounter = 0; export function getGrafanaLiveCentrifugeSrv() { return getGrafanaLiveSrv() as CentrifugeSrv; } export function initGrafanaLive() { setGrafanaLiveSrv(new CentrifugeSrv()); registerLiveFeatures(); }
public/app/features/live/live.ts
0
https://github.com/grafana/grafana/commit/78ebac0116c0aebd99d261c3f138819dc957bece
[ 0.00017518040840514004, 0.0001694682432571426, 0.0001650777121540159, 0.00016919329937081784, 0.0000027258984118816443 ]
{ "id": 0, "code_window": [ " padding: ${theme.spacing(1)};\n", " background: ${theme.colors.background.primary};\n", " border: 1px solid ${theme.components.panel.borderColor};\n", " border-bottom: none;\n", " `,\n", " closeButton: css`\n", " margin-left: ${theme.spacing(1)};\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " border-top-left-radius: ${theme.shape.borderRadius(1.5)};\n" ], "file_path": "public/app/features/dashboard/components/PanelEditor/OptionsPaneOptions.tsx", "type": "add", "edit_start_line_idx": 175 }
<?xml version="1.0" encoding="utf-8"?> <!-- Generator: Adobe Illustrator 19.0.1, SVG Export Plug-In . SVG Version: 6.00 Build 0) --> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> <svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="121px" height="100px" viewBox="0 0 121 100" style="enable-background:new 0 0 121 100;" xml:space="preserve"> <style type="text/css"> .st0{fill:url(#SVGID_1_);} .st1{fill:#161719;} .st2{fill:url(#SVGID_2_);} .st3{fill:url(#SVGID_3_);} </style> <g> <g> <linearGradient id="SVGID_1_" gradientUnits="userSpaceOnUse" x1="60.5" y1="130.7753" x2="60.5" y2="18.6673"> <stop offset="0" style="stop-color:#FFF100"/> <stop offset="1" style="stop-color:#F05A28"/> </linearGradient> <path class="st0" d="M120.8,50L87.2,16.4C78.1,6.3,64.9,0,50.2,0c-27.6,0-50,22.4-50,50s22.4,50,50,50c14.4,0,27.5-6.1,36.6-15.9 c0.1-0.1,0.1-0.1,0.2-0.2L120.8,50z"/> </g> <path class="st1" d="M94.4,49.5c0-24.4-19.9-44.3-44.3-44.3S5.8,25.1,5.8,49.5s19.9,44.3,44.3,44.3S94.4,73.9,94.4,49.5z"/> <g> <g> <g> <linearGradient id="SVGID_2_" gradientUnits="userSpaceOnUse" x1="49.3811" y1="132.2195" x2="49.3811" y2="36.6876"> <stop offset="0" style="stop-color:#FFF100"/> <stop offset="1" style="stop-color:#F05A28"/> </linearGradient> <path class="st2" d="M49.4,77.3c4,0,7.3-3.3,7.3-7.3H42.1C42.1,74.1,45.4,77.3,49.4,77.3z"/> </g> </g> <g> <linearGradient id="SVGID_3_" gradientUnits="userSpaceOnUse" x1="49.3811" y1="132.2195" x2="49.3811" y2="36.6876"> <stop offset="0" style="stop-color:#FFF100"/> <stop offset="1" style="stop-color:#F05A28"/> </linearGradient> <path class="st3" d="M68.3,58.6v-9.2c0-11.3-5.9-20.8-14-23.5c0-2.7-2.2-4.9-4.9-4.9c-2.7,0-4.9,2.2-4.9,4.9 c-8.1,2.8-14,12.3-14,23.5v9.2c-2.2,0-4,1.8-4,4c0,2.2,1.8,4,4,4v0h0.1h37.8h0.1v0c2.2,0,4-1.8,4-4 C72.3,60.4,70.5,58.6,68.3,58.6z"/> </g> </g> </g> </svg>
public/img/icons_dark_theme/icon_alerting_active.svg
0
https://github.com/grafana/grafana/commit/78ebac0116c0aebd99d261c3f138819dc957bece
[ 0.00017223686154466122, 0.00016945874085649848, 0.00016674338257871568, 0.00016986671835184097, 0.0000018599331497171079 ]
{ "id": 0, "code_window": [ " padding: ${theme.spacing(1)};\n", " background: ${theme.colors.background.primary};\n", " border: 1px solid ${theme.components.panel.borderColor};\n", " border-bottom: none;\n", " `,\n", " closeButton: css`\n", " margin-left: ${theme.spacing(1)};\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " border-top-left-radius: ${theme.shape.borderRadius(1.5)};\n" ], "file_path": "public/app/features/dashboard/components/PanelEditor/OptionsPaneOptions.tsx", "type": "add", "edit_start_line_idx": 175 }
import React from 'react'; import renderer from 'react-test-renderer'; import { shallow } from 'enzyme'; import { Input } from './Input'; import { EventsWithValidation } from '../../../../utils'; import { ValidationEvents } from '../../../../types'; const TEST_ERROR_MESSAGE = 'Value must be empty or less than 3 chars'; const testBlurValidation: ValidationEvents = { [EventsWithValidation.onBlur]: [ { rule: (value: string) => { return !value || value.length < 3; }, errorMessage: TEST_ERROR_MESSAGE, }, ], }; describe('Input', () => { it('renders correctly', () => { const tree = renderer.create(<Input />).toJSON(); expect(tree).toMatchSnapshot(); }); it('should validate with error onBlur', () => { const wrapper = shallow(<Input validationEvents={testBlurValidation} />); const evt = { persist: jest.fn, target: { value: 'I can not be more than 2 chars', }, }; wrapper.find('input').simulate('blur', evt); expect(wrapper.state('error')).toBe(TEST_ERROR_MESSAGE); }); it('should validate without error onBlur', () => { const wrapper = shallow(<Input validationEvents={testBlurValidation} />); const evt = { persist: jest.fn, target: { value: 'Hi', }, }; wrapper.find('input').simulate('blur', evt); expect(wrapper.state('error')).toBe(null); }); });
packages/grafana-ui/src/components/Forms/Legacy/Input/Input.test.tsx
0
https://github.com/grafana/grafana/commit/78ebac0116c0aebd99d261c3f138819dc957bece
[ 0.00017511160694994032, 0.00017229469085577875, 0.00016976569895632565, 0.00017231391393579543, 0.0000018882109316109563 ]
{ "id": 1, "code_window": [ " panelWrapper: css`\n", " flex: 1 1 0;\n", " min-height: 0;\n", " width: 100%;\n", " padding-left: ${paneSpacing};\n", " padding-right: 2px;\n", " `,\n", " tabsWrapper: css`\n", " height: 100%;\n", " width: 100%;\n", " `,\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "public/app/features/dashboard/components/PanelEditor/PanelEditor.tsx", "type": "replace", "edit_start_line_idx": 509 }
import React, { FC, useEffect } from 'react'; import { css } from '@emotion/css'; import { IconName, Tab, TabContent, TabsBar, useForceUpdate, useStyles2 } from '@grafana/ui'; import { TransformationsEditor } from '../TransformationsEditor/TransformationsEditor'; import { DashboardModel, PanelModel } from '../../state'; import { PanelEditorTab, PanelEditorTabId } from './types'; import { Subscription } from 'rxjs'; import { PanelQueriesChangedEvent, PanelTransformationsChangedEvent } from 'app/types/events'; import { PanelEditorQueries } from './PanelEditorQueries'; import { GrafanaTheme2 } from '@grafana/data'; import { config } from '@grafana/runtime'; import AlertTabIndex from 'app/features/alerting/AlertTabIndex'; import { PanelAlertTab } from 'app/features/alerting/unified/PanelAlertTab'; interface PanelEditorTabsProps { panel: PanelModel; dashboard: DashboardModel; tabs: PanelEditorTab[]; onChangeTab: (tab: PanelEditorTab) => void; } export const PanelEditorTabs: FC<PanelEditorTabsProps> = React.memo(({ panel, dashboard, tabs, onChangeTab }) => { const forceUpdate = useForceUpdate(); const styles = useStyles2(getStyles); useEffect(() => { const eventSubs = new Subscription(); eventSubs.add(panel.events.subscribe(PanelQueriesChangedEvent, forceUpdate)); eventSubs.add(panel.events.subscribe(PanelTransformationsChangedEvent, forceUpdate)); return () => eventSubs.unsubscribe(); }, [panel, forceUpdate]); const activeTab = tabs.find((item) => item.active)!; if (tabs.length === 0) { return null; } return ( <div className={styles.wrapper}> <TabsBar className={styles.tabBar}> {tabs.map((tab) => { if (config.unifiedAlertingEnabled && tab.id === PanelEditorTabId.Alert) { return ( <PanelAlertTab key={tab.id} label={tab.text} active={tab.active} onChangeTab={() => onChangeTab(tab)} icon={tab.icon as IconName} panel={panel} dashboard={dashboard} /> ); } return ( <Tab key={tab.id} label={tab.text} active={tab.active} onChangeTab={() => onChangeTab(tab)} icon={tab.icon as IconName} counter={getCounter(panel, tab)} /> ); })} </TabsBar> <TabContent className={styles.tabContent}> {activeTab.id === PanelEditorTabId.Query && <PanelEditorQueries panel={panel} queries={panel.targets} />} {activeTab.id === PanelEditorTabId.Alert && <AlertTabIndex panel={panel} dashboard={dashboard} />} {activeTab.id === PanelEditorTabId.Transform && <TransformationsEditor panel={panel} />} </TabContent> </div> ); }); PanelEditorTabs.displayName = 'PanelEditorTabs'; function getCounter(panel: PanelModel, tab: PanelEditorTab) { switch (tab.id) { case PanelEditorTabId.Query: return panel.targets.length; case PanelEditorTabId.Alert: return panel.alert ? 1 : 0; case PanelEditorTabId.Transform: const transformations = panel.getTransformations() ?? []; return transformations.length; } return null; } const getStyles = (theme: GrafanaTheme2) => { return { wrapper: css` display: flex; flex-direction: column; height: 100%; `, tabBar: css` padding-left: ${theme.spacing(2)}; `, tabContent: css` padding: 0; display: flex; flex-direction: column; flex-grow: 1; min-height: 0; background: ${theme.colors.background.primary}; border-right: 1px solid ${theme.components.panel.borderColor}; `, }; };
public/app/features/dashboard/components/PanelEditor/PanelEditorTabs.tsx
1
https://github.com/grafana/grafana/commit/78ebac0116c0aebd99d261c3f138819dc957bece
[ 0.0027361141983419657, 0.0006204659002833068, 0.000166779151186347, 0.00022661109687760472, 0.0008361617801710963 ]
{ "id": 1, "code_window": [ " panelWrapper: css`\n", " flex: 1 1 0;\n", " min-height: 0;\n", " width: 100%;\n", " padding-left: ${paneSpacing};\n", " padding-right: 2px;\n", " `,\n", " tabsWrapper: css`\n", " height: 100%;\n", " width: 100%;\n", " `,\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "public/app/features/dashboard/components/PanelEditor/PanelEditor.tsx", "type": "replace", "edit_start_line_idx": 509 }
import { deprecationWarning, UrlQueryMap, urlUtil } from '@grafana/data'; import * as H from 'history'; import { LocationUpdate } from './LocationSrv'; import { attachDebugger, createLogger } from '@grafana/ui'; import { config } from '../config'; /** * @alpha * A wrapper to help work with browser location and history */ export interface LocationService { partial: (query: Record<string, any>, replace?: boolean) => void; push: (location: H.Path | H.LocationDescriptor<any>) => void; replace: (location: H.Path | H.LocationDescriptor<any>) => void; reload: () => void; getLocation: () => H.Location; getHistory: () => H.History; getSearch: () => URLSearchParams; getSearchObject: () => UrlQueryMap; /** * This is from the old LocationSrv interface * @deprecated use partial, push or replace instead */ update: (update: LocationUpdate) => void; } /** @internal */ export class HistoryWrapper implements LocationService { private readonly history: H.History; constructor(history?: H.History) { // If no history passed create an in memory one if being called from test this.history = history || (process.env.NODE_ENV === 'test' ? H.createMemoryHistory({ initialEntries: ['/'] }) : H.createBrowserHistory({ basename: config.appSubUrl ?? '/' })); this.partial = this.partial.bind(this); this.push = this.push.bind(this); this.replace = this.replace.bind(this); this.getSearch = this.getSearch.bind(this); this.getHistory = this.getHistory.bind(this); this.getLocation = this.getLocation.bind(this); } getHistory() { return this.history; } getSearch() { return new URLSearchParams(this.history.location.search); } partial(query: Record<string, any>, replace?: boolean) { const currentLocation = this.history.location; const newQuery = this.getSearchObject(); for (const key of Object.keys(query)) { // removing params with null | undefined if (query[key] === null || query[key] === undefined) { delete newQuery[key]; } else { newQuery[key] = query[key]; } } const updatedUrl = urlUtil.renderUrl(currentLocation.pathname, newQuery); if (replace) { this.history.replace(updatedUrl, this.history.location.state); } else { this.history.push(updatedUrl, this.history.location.state); } } push(location: H.Path | H.LocationDescriptor) { this.history.push(location); } replace(location: H.Path | H.LocationDescriptor) { this.history.replace(location); } reload() { const prevState = (this.history.location.state as any)?.routeReloadCounter; this.history.replace({ ...this.history.location, state: { routeReloadCounter: prevState ? prevState + 1 : 1 }, }); } getLocation() { return this.history.location; } getSearchObject() { return locationSearchToObject(this.history.location.search); } /** @deprecated use partial, push or replace instead */ update(options: LocationUpdate) { deprecationWarning('LocationSrv', 'update', 'partial, push or replace'); if (options.partial && options.query) { this.partial(options.query, options.partial); } else { const newLocation: H.LocationDescriptor = { pathname: options.path, }; if (options.query) { newLocation.search = urlUtil.toUrlParams(options.query); } if (options.replace) { this.replace(newLocation); } else { this.push(newLocation); } } } } /** * @alpha * Parses a location search string to an object * */ export function locationSearchToObject(search: string | number): UrlQueryMap { let queryString = typeof search === 'number' ? String(search) : search; if (queryString.length > 0) { if (queryString.startsWith('?')) { return urlUtil.parseKeyValue(queryString.substring(1)); } return urlUtil.parseKeyValue(queryString); } return {}; } /** * @alpha */ export let locationService: LocationService = new HistoryWrapper(); /** @internal * Used for tests only */ export const setLocationService = (location: LocationService) => { if (process.env.NODE_ENV !== 'test') { throw new Error('locationService can be only overriden in test environment'); } locationService = location; }; const navigationLog = createLogger('Router'); /** @internal */ export const navigationLogger = navigationLog.logger; // For debugging purposes the location service is attached to global _debug variable attachDebugger('location', locationService, navigationLog);
packages/grafana-runtime/src/services/LocationService.ts
0
https://github.com/grafana/grafana/commit/78ebac0116c0aebd99d261c3f138819dc957bece
[ 0.0001747626520227641, 0.00017090734036173671, 0.00016313802916556597, 0.00017180514987558126, 0.0000027948351544182515 ]
{ "id": 1, "code_window": [ " panelWrapper: css`\n", " flex: 1 1 0;\n", " min-height: 0;\n", " width: 100%;\n", " padding-left: ${paneSpacing};\n", " padding-right: 2px;\n", " `,\n", " tabsWrapper: css`\n", " height: 100%;\n", " width: 100%;\n", " `,\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "public/app/features/dashboard/components/PanelEditor/PanelEditor.tsx", "type": "replace", "edit_start_line_idx": 509 }
// Copyright (c) 2017 Uber Technologies, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import React, { useContext } from 'react'; import hoistNonReactStatics from 'hoist-non-react-statics'; import memoizeOne from 'memoize-one'; import tinycolor from 'tinycolor2'; const COLORS_HEX = [ '#17B8BE', '#F8DCA1', '#B7885E', '#FFCB99', '#F89570', '#829AE3', '#E79FD5', '#1E96BE', '#89DAC1', '#B3AD9E', '#12939A', '#DDB27C', '#88572C', '#FF9833', '#EF5D28', '#162A65', '#DA70BF', '#125C77', '#4DC19C', '#776E57', ]; const COLORS_HEX_DARK = [ '#17B8BE', '#F8DCA1', '#B7885E', '#FFCB99', '#F89570', '#829AE3', '#E79FD5', '#1E96BE', '#89DAC1', '#B3AD9E', '#12939A', '#DDB27C', '#88572C', '#FF9833', '#EF5D28', '#DA70BF', '#4DC19C', '#776E57', ]; export type ThemeOptions = Partial<Theme>; export enum ThemeType { Dark, Light, } export type Theme = { type: ThemeType; servicesColorPalette: string[]; borderStyle: string; components?: { TraceName?: { fontSize?: number | string; }; }; }; export const defaultTheme: Theme = { type: ThemeType.Light, borderStyle: '1px solid #bbb', servicesColorPalette: COLORS_HEX, }; export function isLight(theme?: Theme | ThemeOptions) { // Light theme is default type not set which only happens if called for ThemeOptions. return theme && theme.type ? theme.type === ThemeType.Light : false; } const ThemeContext = React.createContext<ThemeOptions | undefined>(undefined); ThemeContext.displayName = 'ThemeContext'; export const ThemeProvider = ThemeContext.Provider; type ThemeConsumerProps = { children: (theme: Theme) => React.ReactNode; }; export function ThemeConsumer(props: ThemeConsumerProps) { return ( <ThemeContext.Consumer> {(value: ThemeOptions | undefined) => { const theme = memoizedThemeMerge(value); return props.children(theme); }} </ThemeContext.Consumer> ); } const memoizedThemeMerge = memoizeOne((value?: ThemeOptions) => { const darkOverrides: Partial<Theme> = {}; if (!isLight(value)) { darkOverrides.servicesColorPalette = COLORS_HEX_DARK; } return value ? { ...defaultTheme, ...darkOverrides, ...value, } : defaultTheme; }); type WrappedWithThemeComponent<Props> = React.ComponentType<Omit<Props, 'theme'>> & { wrapped: React.ComponentType<Props>; }; export const withTheme = <Props extends { theme: Theme }, Statics extends {} = {}>( Component: React.ComponentType<Props> ): WrappedWithThemeComponent<Props> => { let WithTheme: React.ComponentType<Omit<Props, 'theme'>> = (props) => { return ( <ThemeConsumer> {(theme: Theme) => { return ( <Component {...({ ...props, theme, } as Props & { theme: Theme })} /> ); }} </ThemeConsumer> ); }; WithTheme.displayName = `WithTheme(${Component.displayName})`; WithTheme = hoistNonReactStatics<React.ComponentType<Omit<Props, 'theme'>>, React.ComponentType<Props>>( WithTheme, Component ); (WithTheme as WrappedWithThemeComponent<Props>).wrapped = Component; return WithTheme as WrappedWithThemeComponent<Props>; }; export function useTheme(): Theme { const theme = useContext(ThemeContext); return { ...defaultTheme, ...theme, }; } export const createStyle = <Fn extends (this: any, ...newArgs: any[]) => ReturnType<Fn>>(fn: Fn) => { return memoizeOne(fn); }; /** * Tries to get a dark variant color. Either by simply inverting the luminosity and darkening or lightening the color * a bit, or if base is provided, tries 2 variants of lighter and darker colors and checks which is more readable with * the base. * @param theme * @param hex * @param base */ export function autoColor(theme: Theme, hex: string, base?: string) { if (isLight(theme)) { return hex; } else { if (base) { const color = tinycolor(hex); return tinycolor .mostReadable( base, [ color.clone().lighten(25), color.clone().lighten(10), color, color.clone().darken(10), color.clone().darken(25), ], { includeFallbackColors: false, } ) .toHex8String(); } const color = tinycolor(hex).toHsl(); color.l = 1 - color.l; const newColor = tinycolor(color); return newColor.isLight() ? newColor.darken(5).toHex8String() : newColor.lighten(5).toHex8String(); } } /** * With theme overrides you can use both number or string (for things like rem units) so this makes sure we convert * the value accordingly or use fallback if not set */ export function safeSize(size: number | string | undefined, fallback: string): string { if (!size) { return fallback; } if (typeof size === 'string') { return size; } else { return `${size}px`; } }
packages/jaeger-ui-components/src/Theme.tsx
0
https://github.com/grafana/grafana/commit/78ebac0116c0aebd99d261c3f138819dc957bece
[ 0.000856120022945106, 0.00020260065502952784, 0.0001622198906261474, 0.00017365934036206454, 0.00013938879419583827 ]
{ "id": 1, "code_window": [ " panelWrapper: css`\n", " flex: 1 1 0;\n", " min-height: 0;\n", " width: 100%;\n", " padding-left: ${paneSpacing};\n", " padding-right: 2px;\n", " `,\n", " tabsWrapper: css`\n", " height: 100%;\n", " width: 100%;\n", " `,\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "public/app/features/dashboard/components/PanelEditor/PanelEditor.tsx", "type": "replace", "edit_start_line_idx": 509 }
<?xml version="1.0" encoding="utf-8" ?> <!-- Copyright (c) .NET Foundation and contributors. All rights reserved. Licensed under the Microsoft Reciprocal License. See LICENSE.TXT file in the project root for full license information. --> <configuration> <startup useLegacyV2RuntimeActivationPolicy="true"> <supportedRuntime version="v4.0" /> <supportedRuntime version="v2.0.50727" /> </startup> <runtime> <loadFromRemoteSources enabled="true"/> <AppContextSwitchOverrides value="Switch.System.IO.UseLegacyPathHandling=false;Switch.System.IO.BlockLongPaths=false" /> </runtime> </configuration>
scripts/build/ci-msi-build/msigenerator/light.exe.config
0
https://github.com/grafana/grafana/commit/78ebac0116c0aebd99d261c3f138819dc957bece
[ 0.0001722838351270184, 0.00016878977476153523, 0.00016529571439605206, 0.00016878977476153523, 0.0000034940603654831648 ]
{ "id": 2, "code_window": [ " }\n", "\n", " return (\n", " <div className={styles.wrapper}>\n", " <TabsBar className={styles.tabBar}>\n", " {tabs.map((tab) => {\n", " if (config.unifiedAlertingEnabled && tab.id === PanelEditorTabId.Alert) {\n", " return (\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " <TabsBar className={styles.tabBar} hideBorder>\n" ], "file_path": "public/app/features/dashboard/components/PanelEditor/PanelEditorTabs.tsx", "type": "replace", "edit_start_line_idx": 40 }
import React, { FC, useEffect } from 'react'; import { css } from '@emotion/css'; import { IconName, Tab, TabContent, TabsBar, useForceUpdate, useStyles2 } from '@grafana/ui'; import { TransformationsEditor } from '../TransformationsEditor/TransformationsEditor'; import { DashboardModel, PanelModel } from '../../state'; import { PanelEditorTab, PanelEditorTabId } from './types'; import { Subscription } from 'rxjs'; import { PanelQueriesChangedEvent, PanelTransformationsChangedEvent } from 'app/types/events'; import { PanelEditorQueries } from './PanelEditorQueries'; import { GrafanaTheme2 } from '@grafana/data'; import { config } from '@grafana/runtime'; import AlertTabIndex from 'app/features/alerting/AlertTabIndex'; import { PanelAlertTab } from 'app/features/alerting/unified/PanelAlertTab'; interface PanelEditorTabsProps { panel: PanelModel; dashboard: DashboardModel; tabs: PanelEditorTab[]; onChangeTab: (tab: PanelEditorTab) => void; } export const PanelEditorTabs: FC<PanelEditorTabsProps> = React.memo(({ panel, dashboard, tabs, onChangeTab }) => { const forceUpdate = useForceUpdate(); const styles = useStyles2(getStyles); useEffect(() => { const eventSubs = new Subscription(); eventSubs.add(panel.events.subscribe(PanelQueriesChangedEvent, forceUpdate)); eventSubs.add(panel.events.subscribe(PanelTransformationsChangedEvent, forceUpdate)); return () => eventSubs.unsubscribe(); }, [panel, forceUpdate]); const activeTab = tabs.find((item) => item.active)!; if (tabs.length === 0) { return null; } return ( <div className={styles.wrapper}> <TabsBar className={styles.tabBar}> {tabs.map((tab) => { if (config.unifiedAlertingEnabled && tab.id === PanelEditorTabId.Alert) { return ( <PanelAlertTab key={tab.id} label={tab.text} active={tab.active} onChangeTab={() => onChangeTab(tab)} icon={tab.icon as IconName} panel={panel} dashboard={dashboard} /> ); } return ( <Tab key={tab.id} label={tab.text} active={tab.active} onChangeTab={() => onChangeTab(tab)} icon={tab.icon as IconName} counter={getCounter(panel, tab)} /> ); })} </TabsBar> <TabContent className={styles.tabContent}> {activeTab.id === PanelEditorTabId.Query && <PanelEditorQueries panel={panel} queries={panel.targets} />} {activeTab.id === PanelEditorTabId.Alert && <AlertTabIndex panel={panel} dashboard={dashboard} />} {activeTab.id === PanelEditorTabId.Transform && <TransformationsEditor panel={panel} />} </TabContent> </div> ); }); PanelEditorTabs.displayName = 'PanelEditorTabs'; function getCounter(panel: PanelModel, tab: PanelEditorTab) { switch (tab.id) { case PanelEditorTabId.Query: return panel.targets.length; case PanelEditorTabId.Alert: return panel.alert ? 1 : 0; case PanelEditorTabId.Transform: const transformations = panel.getTransformations() ?? []; return transformations.length; } return null; } const getStyles = (theme: GrafanaTheme2) => { return { wrapper: css` display: flex; flex-direction: column; height: 100%; `, tabBar: css` padding-left: ${theme.spacing(2)}; `, tabContent: css` padding: 0; display: flex; flex-direction: column; flex-grow: 1; min-height: 0; background: ${theme.colors.background.primary}; border-right: 1px solid ${theme.components.panel.borderColor}; `, }; };
public/app/features/dashboard/components/PanelEditor/PanelEditorTabs.tsx
1
https://github.com/grafana/grafana/commit/78ebac0116c0aebd99d261c3f138819dc957bece
[ 0.6185513138771057, 0.06388027220964432, 0.00017437830683775246, 0.0010874371509999037, 0.16941601037979126 ]
{ "id": 2, "code_window": [ " }\n", "\n", " return (\n", " <div className={styles.wrapper}>\n", " <TabsBar className={styles.tabBar}>\n", " {tabs.map((tab) => {\n", " if (config.unifiedAlertingEnabled && tab.id === PanelEditorTabId.Alert) {\n", " return (\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " <TabsBar className={styles.tabBar} hideBorder>\n" ], "file_path": "public/app/features/dashboard/components/PanelEditor/PanelEditorTabs.tsx", "type": "replace", "edit_start_line_idx": 40 }
package flux import ( "context" "errors" "fmt" "strings" "github.com/grafana/grafana-plugin-sdk-go/backend" "github.com/grafana/grafana-plugin-sdk-go/data" "github.com/influxdata/influxdb-client-go/v2/api" ) const maxPointsEnforceFactor float64 = 10 // executeQuery runs a flux query using the queryModel to interpolate the query and the runner to execute it. // maxSeries somehow limits the response. func executeQuery(ctx context.Context, query queryModel, runner queryRunner, maxSeries int) (dr backend.DataResponse) { dr = backend.DataResponse{} flux := interpolate(query) glog.Debug("Executing Flux query", "flux", flux) tables, err := runner.runQuery(ctx, flux) if err != nil { glog.Warn("Flux query failed", "err", err, "query", flux) dr.Error = err } else { // we only enforce a larger number than maxDataPoints maxPointsEnforced := int(float64(query.MaxDataPoints) * maxPointsEnforceFactor) dr = readDataFrames(tables, maxPointsEnforced, maxSeries) if dr.Error != nil { // we check if a too-many-data-points error happened, and if it is so, // we improve the error-message. // (we have to do it in such a complicated way, because at the point where // the error happens, there is not enough info to create a nice error message) var maxPointError maxPointsExceededError if errors.As(dr.Error, &maxPointError) { text := fmt.Sprintf("A query returned too many datapoints and the results have been truncated at %d points to prevent memory issues. At the current graph size, Grafana can only draw %d.", maxPointError.Count, query.MaxDataPoints) // we recommend to the user to use AggregateWindow(), but only if it is not already used if !strings.Contains(query.RawQuery, "aggregateWindow(") { text += " Try using the aggregateWindow() function in your query to reduce the number of points returned." } dr.Error = fmt.Errorf(text) } } } // Make sure there is at least one frame if len(dr.Frames) == 0 { dr.Frames = append(dr.Frames, data.NewFrame("")) } firstFrame := dr.Frames[0] if firstFrame.Meta == nil { firstFrame.SetMeta(&data.FrameMeta{}) } firstFrame.Meta.ExecutedQueryString = flux return dr } func readDataFrames(result *api.QueryTableResult, maxPoints int, maxSeries int) (dr backend.DataResponse) { glog.Debug("Reading data frames from query result", "maxPoints", maxPoints, "maxSeries", maxSeries) dr = backend.DataResponse{} builder := &frameBuilder{ maxPoints: maxPoints, maxSeries: maxSeries, } for result.Next() { // Observe when there is new grouping key producing new table if result.TableChanged() { if builder.frames != nil { for _, frame := range builder.frames { dr.Frames = append(dr.Frames, frame) } } err := builder.Init(result.TableMetadata()) if err != nil { dr.Error = err return } } if builder.frames == nil { dr.Error = fmt.Errorf("invalid state") return dr } err := builder.Append(result.Record()) if err != nil { dr.Error = err break } } // Add the inprogress record if builder.frames != nil { for _, frame := range builder.frames { dr.Frames = append(dr.Frames, frame) } } // result.Err() is probably more important then the other errors if result.Err() != nil { dr.Error = result.Err() } return dr }
pkg/tsdb/influxdb/flux/executor.go
0
https://github.com/grafana/grafana/commit/78ebac0116c0aebd99d261c3f138819dc957bece
[ 0.00017906518769450486, 0.00017561989079695195, 0.0001684592425590381, 0.00017683254554867744, 0.0000031426420719071757 ]