function AbstractWalker() { return _super !== null && _super.apply(this, arguments) || this; }
n/a
function BlockScopeAwareRuleWalker(sourceFile, options) { var _this = _super.call(this, sourceFile, options) || this; // initialize with global scope if file is not a module _this.blockScopeStack = ts.isExternalModule(sourceFile) ? [] : [_this.createBlockScope(sourceFile)]; return _this; }
n/a
function EnableDisableRulesWalker(sourceFile, ruleOptionsList) { this.sourceFile = sourceFile; this.enableDisableRuleMap = new Map(); this.enabledRules = []; for (var _i = 0, ruleOptionsList_1 = ruleOptionsList; _i < ruleOptionsList_1.length; _i++) { var ruleOptions = ruleOptionsList_1[_i]; if (ruleOptions.ruleSeverity !== "off") { this.enabledRules.push(ruleOptions.ruleName); this.enableDisableRuleMap.set(ruleOptions.ruleName, [{ isEnabled: true, position: 0, }]); } } }
n/a
function Formatter() { return _super !== null && _super.apply(this, arguments) || this; }
n/a
function Formatter() { return _super !== null && _super.apply(this, arguments) || this; }
n/a
function Formatter() { return _super !== null && _super.apply(this, arguments) || this; }
n/a
function Formatter() { return _super !== null && _super.apply(this, arguments) || this; }
n/a
function Formatter() { return _super !== null && _super.apply(this, arguments) || this; }
n/a
function Formatter() { return _super !== null && _super.apply(this, arguments) || this; }
n/a
function Formatter() { return _super !== null && _super.apply(this, arguments) || this; }
n/a
function Formatter() { return _super !== null && _super.apply(this, arguments) || this; }
n/a
function Linter(options, program) { this.options = options; this.program = program; this.failures = []; this.fixes = []; if (typeof options !== "object") { throw new Error("Unknown Linter options type: " + typeof options); } if (options.configuration != null) { throw new Error("ILinterOptions does not contain the property `configuration` as of version 4. " + "Did you mean to pass the `IConfigurationFile` object to lint() ? "); } }
n/a
function ProgramAwareRuleWalker(sourceFile, options, program) { var _this = _super.call(this, sourceFile, options) || this; _this.program = program; _this.typeChecker = program.getTypeChecker(); return _this; }
n/a
function Replacement(innerStart, innerLength, innerText) { this.innerStart = innerStart; this.innerLength = innerLength; this.innerText = innerText; }
n/a
function RuleFailure(sourceFile, start, end, failure, ruleName, fix) { this.sourceFile = sourceFile; this.failure = failure; this.ruleName = ruleName; this.fix = fix; this.fileName = sourceFile.fileName; this.startPosition = this.createFailurePosition(start); this.endPosition = this.createFailurePosition(end); this.rawLines = sourceFile.text; this.ruleSeverity = "error"; }
n/a
function RuleFailurePosition(position, lineAndCharacter) { this.position = position; this.lineAndCharacter = lineAndCharacter; }
n/a
function RuleWalker(sourceFile, options) { var _this = _super.call(this) || this; _this.sourceFile = sourceFile; _this.failures = []; _this.options = options.ruleArguments; _this.limit = _this.sourceFile.getFullWidth(); _this.ruleName = options.ruleName; return _this; }
n/a
function AbstractRule(options) { this.options = options; this.ruleName = options.ruleName; this.ruleArguments = options.ruleArguments; this.ruleSeverity = options.ruleSeverity; }
n/a
function OptionallyTypedRule() { return _super !== null && _super.apply(this, arguments) || this; }
n/a
function TypedRule() { return _super !== null && _super.apply(this, arguments) || this; }
n/a
function ScopeAwareRuleWalker(sourceFile, options) { var _this = _super.call(this, sourceFile, options) || this; // initialize with global scope if file is not a module _this.scopeStack = ts.isExternalModule(sourceFile) ? [] : [_this.createScope(sourceFile)]; return _this; }
n/a
function SyntaxWalker() { }
n/a
function WalkContext(sourceFile, ruleName, options) { this.sourceFile = sourceFile; this.ruleName = ruleName; this.options = options; this.failures = []; }
n/a
function ancestorWhere(node, predicate) { var cur = node; do { if (predicate(cur)) { return cur; } cur = cur.parent; } while (cur); return undefined; }
n/a
function childOfKind(node, kind) { return node.getChildren().find(function (child) { return child.kind === kind; }); }
n/a
function doesIntersect(failure, disabledIntervals) { return disabledIntervals.some(function (interval) { var maxStart = Math.max(interval.startPosition, failure.getStartPosition().getPosition()); var minEnd = Math.min(interval.endPosition, failure.getEndPosition().getPosition()); return maxStart <= minEnd; }); }
n/a
function findFormatter(name, formattersDirectory) { if (typeof name === "function") { return name; } else if (typeof name === "string") { name = name.trim(); var camelizedName = utils_1.camelize(name + "Formatter"); // first check for core formatters var Formatter = loadFormatter(CORE_FORMATTERS_DIRECTORY, camelizedName); if (Formatter != null) { return Formatter; } // then check for rules within the first level of rulesDirectory if (formattersDirectory) { Formatter = loadFormatter(formattersDirectory, camelizedName); if (Formatter) { return Formatter; } } // else try to resolve as module return loadFormatterModule(name); } else { // If an something else is passed as a name (e.g. object) throw new Error("Name of type " + typeof name + " is not supported."); } }
n/a
function findRule(name, rulesDirectories) { var camelizedName = transformName(name); var Rule; // first check for core rules Rule = loadCachedRule(CORE_RULES_DIRECTORY, camelizedName); if (Rule == null) { // then check for rules within the first level of rulesDirectory for (var _i = 0, _a = utils_1.arrayify(rulesDirectories); _i < _a.length; _i++) { var dir = _a[_i]; Rule = loadCachedRule(dir, camelizedName, true); if (Rule != null) { break; } } } return Rule; }
n/a
function forEachComment(node, cb) {
/* Visit all tokens and skip trivia.
Comment ranges between tokens are parsed without the need of a scanner.
forEachToken also does intentionally not pay attention to the correct comment ownership of nodes as it always
scans all trivia before each token, which could include trailing comments of the previous token.
Comment onwership is done right in this function*/
return forEachToken(node, true, function (fullText, tokenKind, pos, parent) {
// don't search for comments inside JsxText
if (canHaveLeadingTrivia(tokenKind, parent)) {
// Comments before the first token (pos.fullStart === 0) are all considered leading comments, so no need for special
treatment
var comments = ts.getLeadingCommentRanges(fullText, pos.fullStart);
if (comments !== undefined) {
for (var _i = 0, comments_1 = comments; _i < comments_1.length; _i++) {
var comment = comments_1[_i];
cb(fullText, comment.kind, { fullStart: pos.fullStart, tokenStart: comment.pos, end: comment.end });
}
}
}
if (canHaveTrailingTrivia(tokenKind, parent)) {
var comments = ts.getTrailingCommentRanges(fullText, pos.end);
if (comments !== undefined) {
for (var _a = 0, comments_2 = comments; _a < comments_2.length; _a++) {
var comment = comments_2[_a];
cb(fullText, comment.kind, { fullStart: pos.fullStart, tokenStart: comment.pos, end: comment.end });
}
}
}
});
}
...
position: 0,
}]);
}
}
}
EnableDisableRulesWalker.prototype.getEnableDisableRuleMap = function () {
var _this = this;
utils.forEachComment(this.sourceFile, function (fullText, comment) {
var commentText = comment.kind === ts.SyntaxKind.SingleLineCommentTrivia
? fullText.substring(comment.pos + 2, comment.end)
: fullText.substring(comment.pos + 2, comment.end - 2);
return _this.handleComment(commentText, comment);
});
return this.enableDisableRuleMap;
};
...
function forEachToken(node, skipTrivia, cb, filter) {
// this function will most likely be called with SourceFile anyways, so there is no need for an additional parameter
var sourceFile = node.getSourceFile();
var fullText = sourceFile.text;
var iterateFn = filter === undefined ? iterateChildren : iterateWithFilter;
var handleTrivia = skipTrivia ? undefined : createTriviaHandler(sourceFile, cb);
iterateFn(node);
// this function is used to save the if condition for the common case where no filter is provided
function iterateWithFilter(child) {
if (filter(child)) {
return iterateChildren(child);
}
}
function iterateChildren(child) {
if (child.kind < ts.SyntaxKind.FirstNode ||
// for backwards compatibility to typescript 2.0.10
// JsxText was no Token, but a Node in that version
child.kind === ts.SyntaxKind.JsxText) {
// we found a token, tokens have no children, stop recursing here
return callback(child);
}
/* Exclude everything contained in JsDoc, it will be handled with the other trivia anyway.
* When we would handle JsDoc tokens like regular ones, we would scan some trivia multiple times.
* Even worse, we would scan for trivia inside the JsDoc comment, which yields unexpected results.*/
if (child.kind !== ts.SyntaxKind.JSDocComment) {
// recurse into Node's children to find tokens
return child.getChildren(sourceFile).forEach(iterateFn);
}
}
function callback(token) {
var tokenStart = token.getStart(sourceFile);
if (!skipTrivia && tokenStart !== token.pos) {
// we only have to handle trivia before each token, because there is nothing after EndOfFileToken
handleTrivia(token.pos, tokenStart, token);
}
return cb(fullText, token.kind, { tokenStart: tokenStart, fullStart: token.pos, end: token.end }, token.parent);
}
}
n/a
function getBindingElementVariableDeclaration(node) { var currentParent = node.parent; while (currentParent.kind !== ts.SyntaxKind.VariableDeclaration) { if (currentParent.parent == null) { return null; // function parameter, no variable declaration } else { currentParent = currentParent.parent; } } return currentParent; }
n/a
function getEqualsKind(node) { switch (node.kind) { case ts.SyntaxKind.EqualsEqualsToken: return { isPositive: true, isStrict: false }; case ts.SyntaxKind.EqualsEqualsEqualsToken: return { isPositive: true, isStrict: true }; case ts.SyntaxKind.ExclamationEqualsToken: return { isPositive: false, isStrict: false }; case ts.SyntaxKind.ExclamationEqualsEqualsToken: return { isPositive: false, isStrict: true }; default: return undefined; } }
n/a
function getSourceFile(fileName, source) { var normalizedName = path.normalize(fileName).replace(/\\/g, "/"); return ts.createSourceFile(normalizedName, source, ts.ScriptTarget.ES5, /*setParentNodes*/ true); }
n/a
function hasCommentAfterPosition(text, position) { return ts.getTrailingCommentRanges(text, position) !== undefined || ts.getLeadingCommentRanges(text, position) !== undefined; }
n/a
function hasModifier(modifiers) { var modifierKinds = []; for (var _i = 1; _i < arguments.length; _i++) { modifierKinds[_i - 1] = arguments[_i]; } if (modifiers === undefined || modifierKinds.length === 0) { return false; } return modifiers.some(function (m) { return modifierKinds.some(function (k) { return m.kind === k; }); }); }
n/a
function isAssignment(node) { if (node.kind === ts.SyntaxKind.BinaryExpression) { var binaryExpression = node; return binaryExpression.operatorToken.kind >= ts.SyntaxKind.FirstAssignment && binaryExpression.operatorToken.kind <= ts.SyntaxKind.LastAssignment; } else { return false; } }
n/a
function isBlockScopeBoundary(node) { return isScopeBoundary(node) || node.kind === ts.SyntaxKind.Block || isLoop(node) || node.kind === ts.SyntaxKind.WithStatement || node.kind === ts.SyntaxKind.SwitchStatement || node.parent !== undefined && (node.parent.kind === ts.SyntaxKind.TryStatement || node.parent.kind === ts.SyntaxKind.IfStatement); }
n/a
function isBlockScopedBindingElement(node) { var variableDeclaration = getBindingElementVariableDeclaration(node); // if no variable declaration, it must be a function param, which is block scoped return (variableDeclaration == null) || isBlockScopedVariable(variableDeclaration); }
n/a
function isBlockScopedVariable(node) { var parentNode = (node.kind === ts.SyntaxKind.VariableDeclaration) ? node.parent : node.declarationList; return isNodeFlagSet(parentNode, ts.NodeFlags.Let) || isNodeFlagSet(parentNode, ts.NodeFlags.Const); }
n/a
function isCombinedModifierFlagSet(node, flagToCheck) { // tslint:disable-next-line:no-bitwise return (ts.getCombinedModifierFlags(node) & flagToCheck) !== 0; }
n/a
function isCombinedNodeFlagSet(node, flagToCheck) { // tslint:disable-next-line:no-bitwise return (ts.getCombinedNodeFlags(node) & flagToCheck) !== 0; }
n/a
function isLoop(node) { return node.kind === ts.SyntaxKind.DoStatement || node.kind === ts.SyntaxKind.WhileStatement || node.kind === ts.SyntaxKind.ForStatement || node.kind === ts.SyntaxKind.ForInStatement || node.kind === ts.SyntaxKind.ForOfStatement; }
n/a
function isNestedModuleDeclaration(decl) { // in a declaration expression like 'module a.b.c' - 'a' is the top level module declaration node and 'b' and 'c' // are nested therefore we can depend that a node's position will only match with its name's position for nested // nodes return decl.name.pos === decl.pos; }
n/a
function isNodeFlagSet(node, flagToCheck) { // tslint:disable-next-line:no-bitwise return (node.flags & flagToCheck) !== 0; }
n/a
function isObjectFlagSet(objectType, flagToCheck) { // tslint:disable-next-line:no-bitwise return (objectType.objectFlags & flagToCheck) !== 0; }
n/a
function isScopeBoundary(node) { return node.kind === ts.SyntaxKind.FunctionDeclaration || node.kind === ts.SyntaxKind.FunctionExpression || node.kind === ts.SyntaxKind.PropertyAssignment || node.kind === ts.SyntaxKind.ShorthandPropertyAssignment || node.kind === ts.SyntaxKind.MethodDeclaration || node.kind === ts.SyntaxKind.Constructor || node.kind === ts.SyntaxKind.ModuleDeclaration || node.kind === ts.SyntaxKind.ArrowFunction || node.kind === ts.SyntaxKind.ParenthesizedExpression || node.kind === ts.SyntaxKind.ClassDeclaration || node.kind === ts.SyntaxKind.ClassExpression || node.kind === ts.SyntaxKind.InterfaceDeclaration || node.kind === ts.SyntaxKind.GetAccessor || node.kind === ts.SyntaxKind.SetAccessor || node.kind === ts.SyntaxKind.SourceFile && ts.isExternalModule(node); }
n/a
function isSymbolFlagSet(symbol, flagToCheck) { // tslint:disable-next-line:no-bitwise return (symbol.flags & flagToCheck) !== 0; }
n/a
function isTypeFlagSet(type, flagToCheck) { // tslint:disable-next-line:no-bitwise return (type.flags & flagToCheck) !== 0; }
n/a
function isTypedRule(rule) { return "applyWithProgram" in rule; }
n/a
function loadRules(ruleOptionsList, enableDisableRuleMap, rulesDirectories, isJs) { var rules = []; var notFoundRules = []; var notAllowedInJsRules = []; for (var _i = 0, ruleOptionsList_1 = ruleOptionsList; _i < ruleOptionsList_1.length; _i++) { var ruleOptions = ruleOptionsList_1[_i]; var ruleName = ruleOptions.ruleName; var enableDisableRules = enableDisableRuleMap.get(ruleName); if (ruleOptions.ruleSeverity !== "off" || enableDisableRuleMap) { var Rule = findRule(ruleName, rulesDirectories); if (Rule == null) { notFoundRules.push(ruleName); } else { if (isJs && Rule.metadata && Rule.metadata.typescriptOnly) { notAllowedInJsRules.push(ruleName); } else { var ruleSpecificList = enableDisableRules || []; ruleOptions.disabledIntervals = buildDisabledIntervalsFromSwitches(ruleSpecificList); rules.push(new Rule(ruleOptions)); if (Rule.metadata && Rule.metadata.deprecationMessage) { error_1.showWarningOnce(Rule.metadata.ruleName + " is deprecated. " + Rule.metadata.deprecationMessage); } } } } } if (notFoundRules.length > 0) { var warning = (_a = ["\n Could not find implementations for the following rules specified in the configuration :\n ", "\n Try upgrading TSLint and/or ensuring that you have all necessary custom rules installed.\n If TSLint was recently upgraded, you may have old rules configured which need to be cleaned up.\n "], _a.raw = ["\n Could not find implementations for the following rules specified in the configuration:\n ", "\n Try upgrading TSLint and/or ensuring that you have all necessary custom rules installed.\n If TSLint was recently upgraded, you may have old rules configured which need to be cleaned up.\n "], utils_1.dedent(_a, notFoundRules.join("\n "))); console.warn(warning); } if (notAllowedInJsRules.length > 0) { var warning = (_b = ["\n Following rules specified in configuration couldn't be applied to .js or .jsx files:\n ", "\n Make sure to exclude them from \"jsRules\" section of your tslint.json.\n "], _b.raw = ["\n Following rules specified in configuration couldn't be applied to .js or .jsx files:\n ", "\n Make sure to exclude them from \"jsRules\" section of your tslint.json.\n "], utils_1.dedent(_b, notAllowedInJsRules.join("\n "))); console.warn(warning); } if (rules.length === 0) { console.warn("No valid rules have been specified"); } return rules; var _a, _b; }
n/a
function someAncestor(node, predicate) { return predicate(node) || (node.parent != null && someAncestor(node.parent, predicate)); }
n/a
function unwrapParentheses(node) { while (node.kind === ts.SyntaxKind.ParenthesizedExpression) { node = node.expression; } return node; }
n/a
function AbstractWalker() { return _super !== null && _super.apply(this, arguments) || this; }
n/a
function AbstractWalker() { return _super !== null && _super.apply(this, arguments) || this; }
n/a
getFailures = function () { return this.failures; }
n/a
getSourceFile = function () { return this.sourceFile; }
n/a
function BlockScopeAwareRuleWalker(sourceFile, options) { var _this = _super.call(this, sourceFile, options) || this; // initialize with global scope if file is not a module _this.blockScopeStack = ts.isExternalModule(sourceFile) ? [] : [_this.createBlockScope(sourceFile)]; return _this; }
n/a
function BlockScopeAwareRuleWalker(sourceFile, options) { var _this = _super.call(this, sourceFile, options) || this; // initialize with global scope if file is not a module _this.blockScopeStack = ts.isExternalModule(sourceFile) ? [] : [_this.createBlockScope(sourceFile)]; return _this; }
n/a
findBlockScope = function (predicate) { // look through block scopes from local -> global for (var i = this.blockScopeStack.length - 1; i >= 0; i--) { if (predicate(this.blockScopeStack[i])) { return this.blockScopeStack[i]; } } return undefined; }
n/a
getAllBlockScopes = function () { return this.blockScopeStack; }
n/a
getCurrentBlockDepth = function () { return this.blockScopeStack.length; }
n/a
getCurrentBlockScope = function () { return this.blockScopeStack[this.blockScopeStack.length - 1]; }
n/a
isBlockScopeBoundary = function (node) { return utils_1.isBlockScopeBoundary(node); }
n/a
onBlockScopeEnd = function () { return; }
n/a
onBlockScopeStart = function () { return; }
n/a
visitNode = function (node) { var isNewBlockScope = this.isBlockScopeBoundary(node); if (isNewBlockScope) { this.blockScopeStack.push(this.createBlockScope(node)); this.onBlockScopeStart(); } _super.prototype.visitNode.call(this, node); if (isNewBlockScope) { this.onBlockScopeEnd(); this.blockScopeStack.pop(); } }
n/a
function convertRuleOptions(ruleConfiguration) { var output = []; ruleConfiguration.forEach(function (partialOptions, ruleName) { var options = { disabledIntervals: [], ruleArguments: partialOptions.ruleArguments || [], ruleName: ruleName, ruleSeverity: partialOptions.ruleSeverity || "error", }; output.push(options); }); return output; }
n/a
function extendConfigurationFile(targetConfig, nextConfigSource) { var combineProperties = function (targetProperty, nextProperty) { var combinedProperty = {}; for (var _i = 0, _a = Object.keys(utils_1.objectify(targetProperty)); _i < _a.length; _i++) { var name = _a[_i]; combinedProperty[name] = targetProperty[name]; } // next config source overwrites the target config object for (var _b = 0, _c = Object.keys(utils_1.objectify(nextProperty)); _b < _c.length; _b++) { var name = _c[_b]; combinedProperty[name] = nextProperty[name]; } return combinedProperty; }; var combineMaps = function (target, next) { var combined = new Map(); target.forEach(function (options, ruleName) { combined.set(ruleName, options); }); next.forEach(function (options, ruleName) { var combinedRule = combined.get(ruleName); if (combinedRule != null) { combined.set(ruleName, combineProperties(combinedRule, options)); } else { combined.set(ruleName, options); } }); return combined; }; var combinedRulesDirs = targetConfig.rulesDirectory.concat(nextConfigSource.rulesDirectory); var dedupedRulesDirs = Array.from(new Set(combinedRulesDirs)); return { extends: [], jsRules: combineMaps(targetConfig.jsRules, nextConfigSource.jsRules), linterOptions: combineProperties(targetConfig.linterOptions, nextConfigSource.linterOptions), rules: combineMaps(targetConfig.rules, nextConfigSource.rules), rulesDirectory: dedupedRulesDirs, }; }
n/a
function findConfiguration(configFile, inputFilePath) { var path = findConfigurationPath(configFile, inputFilePath); var loadResult = { path: path }; try { loadResult.results = loadConfigurationFromPath(path); return loadResult; } catch (error) { throw new error_1.FatalError("Failed to load " + path + ": " + error.message, error); } }
...
}
finally {
fs.closeSync(fd);
}
var contents = fs.readFileSync(file, "utf8");
var folder = path.dirname(file);
if (lastFolder !== folder) {
configFile = configuration_1.findConfiguration(possibleConfigAbsolutePath, folder
).results;
lastFolder = folder;
}
linter.lint(file, contents, configFile);
}
var lintResult = linter.getResult();
this.outputStream.write(lintResult.output, function () {
if (_this.options.force || lintResult.errorCount === 0) {
...
function findConfigurationPath(suppliedConfigFilePath, inputFilePath) { if (suppliedConfigFilePath != null) { if (!fs.existsSync(suppliedConfigFilePath)) { throw new Error("Could not find config file at: " + path.resolve(suppliedConfigFilePath)); } else { return path.resolve(suppliedConfigFilePath); } } else { // search for tslint.json from input file location var configFilePath = findup(exports.CONFIG_FILENAME, { cwd: inputFilePath, nocase: true }); if (configFilePath != null && fs.existsSync(configFilePath)) { return path.resolve(configFilePath); } // search for tslint.json in home directory var homeDir = getHomeDir(); if (homeDir != null) { configFilePath = path.join(homeDir, exports.CONFIG_FILENAME); if (fs.existsSync(configFilePath)) { return path.resolve(configFilePath); } } // no path could be found return undefined; } }
n/a
function getRelativePath(directory, relativeTo) { if (directory != null) { var basePath = relativeTo || process.cwd(); return path.resolve(basePath, directory); } return undefined; }
...
var cachedRule = cachedRules.get(fullPath);
if (cachedRule !== undefined) {
return cachedRule;
}
// get absolute path
var absolutePath = directory;
if (isCustomPath) {
absolutePath = configuration_1.getRelativePath(directory);
if (absolutePath != null) {
if (!fs.existsSync(absolutePath)) {
throw new Error("Could not find custom rule directory: " + directory);
}
}
}
var Rule = null;
...
function getRulesDirectories(directories, relativeTo) { var rulesDirectories = utils_1.arrayify(directories) .map(function (dir) { return getRelativePath(dir, relativeTo); }) .filter(function (dir) { return dir !== undefined; }); for (var _i = 0, rulesDirectories_1 = rulesDirectories; _i < rulesDirectories_1.length; _i++) { var directory = rulesDirectories_1[_i]; if (directory != null && !fs.existsSync(directory)) { throw new Error("Could not find custom rule directory: " + directory); } } return rulesDirectories; }
n/a
function loadConfigurationFromPath(configFilePath) { if (configFilePath == null) { return exports.DEFAULT_CONFIG; } else { var resolvedConfigFilePath = resolveConfigurationPath(configFilePath); var rawConfigFile = void 0; if (path.extname(resolvedConfigFilePath) === ".json") { var fileContent = utils_1.stripComments(fs.readFileSync(resolvedConfigFilePath) .toString() .replace(/^\uFEFF/, "")); rawConfigFile = JSON.parse(fileContent); } else { rawConfigFile = require(resolvedConfigFilePath); delete require.cache[resolvedConfigFilePath]; } var configFileDir_1 = path.dirname(resolvedConfigFilePath); var configFile = parseConfigFile(rawConfigFile, configFileDir_1); // load configurations, in order, using their identifiers or relative paths // apply the current configuration last by placing it last in this array var configs = configFile.extends.map(function (name) { var nextConfigFilePath = resolveConfigurationPath(name, configFileDir_1); return loadConfigurationFromPath(nextConfigFilePath); }).concat([configFile]); return configs.reduce(extendConfigurationFile, exports.EMPTY_CONFIG); } }
n/a
function parseConfigFile(configFile, configFileDir) { var rules = new Map(); var jsRules = new Map(); if (configFile.rules) { for (var ruleName in configFile.rules) { if (configFile.rules.hasOwnProperty(ruleName)) { rules.set(ruleName, parseRuleOptions(configFile.rules[ruleName], configFile.defaultSeverity)); } } } if (configFile.jsRules) { for (var ruleName in configFile.jsRules) { if (configFile.jsRules.hasOwnProperty(ruleName)) { jsRules.set(ruleName, parseRuleOptions(configFile.jsRules[ruleName], configFile.defaultSeverity)); } } } return { extends: utils_1.arrayify(configFile.extends), jsRules: jsRules, linterOptions: configFile.linterOptions || {}, rulesDirectory: getRulesDirectories(configFile.rulesDirectory, configFileDir), rules: rules, }; }
n/a
function EnableDisableRulesWalker(sourceFile, ruleOptionsList) { this.sourceFile = sourceFile; this.enableDisableRuleMap = new Map(); this.enabledRules = []; for (var _i = 0, ruleOptionsList_1 = ruleOptionsList; _i < ruleOptionsList_1.length; _i++) { var ruleOptions = ruleOptionsList_1[_i]; if (ruleOptions.ruleSeverity !== "off") { this.enabledRules.push(ruleOptions.ruleName); this.enableDisableRuleMap.set(ruleOptions.ruleName, [{ isEnabled: true, position: 0, }]); } } }
n/a
getEnableDisableRuleMap = function () { var _this = this; utils.forEachComment(this.sourceFile, function (fullText, comment) { var commentText = comment.kind === ts.SyntaxKind.SingleLineCommentTrivia ? fullText.substring(comment.pos + 2, comment.end) : fullText.substring(comment.pos + 2, comment.end - 2); return _this.handleComment(commentText, comment); }); return this.enableDisableRuleMap; }
n/a
getStartOfLinePosition = function (position, lineOffset) { if (lineOffset === void 0) { lineOffset = 0; } var line = ts.getLineAndCharacterOfPosition(this.sourceFile, position).line + lineOffset; var lineStarts = this.sourceFile.getLineStarts(); if (line >= lineStarts.length) { // next line ends with eof or there is no next line // undefined switches the rule until the end and avoids an extra array entry return undefined; } return lineStarts[line]; }
...
}
};
EnableDisableRulesWalker.prototype.handleTslintLineSwitch = function (rules, isEnabled, modifier, range) {
var start;
var end;
if (modifier === "line") {
// start at the beginning of the line where comment starts
start = this.getStartOfLinePosition(range.pos);
// end at the beginning of the line following the comment
end = this.getStartOfLinePosition(range.end, 1);
}
else if (modifier === "next-line") {
// start at the beginning of the line following the comment
start = this.getStartOfLinePosition(range.end, 1);
if (start === undefined) {
...
handleComment = function (commentText, range) { // regex is: start of string followed by any amount of whitespace // followed by tslint and colon // followed by either "enable" or "disable" // followed optionally by -line or -next-line // followed by either colon, whitespace or end of string var match = /^\s*tslint:(enable|disable)(?:-(line|next-line))?(:|\s|$)/.exec(commentText); if (match !== null) { // remove everything matched by the previous regex to get only the specified rules // split at whitespaces // filter empty items coming from whitespaces at start, at end or empty list var rulesList = commentText.substr(match[0].length) .split(/\s+/) .filter(function (rule) { return !!rule; }); if (rulesList.length === 0 && match[3] === ":") { // nothing to do here: an explicit separator was specified but no rules to switch return; } if (rulesList.length === 0 || rulesList.indexOf("all") !== -1) { // if list is empty we default to all enabled rules // if `all` is specified we ignore the other rules and take all enabled rules rulesList = this.enabledRules; } this.handleTslintLineSwitch(rulesList, match[1] === "enable", match[2], range); } }
...
}
EnableDisableRulesWalker.prototype.getEnableDisableRuleMap = function () {
var _this = this;
utils.forEachComment(this.sourceFile, function (fullText, comment) {
var commentText = comment.kind === ts.SyntaxKind.SingleLineCommentTrivia
? fullText.substring(comment.pos + 2, comment.end)
: fullText.substring(comment.pos + 2, comment.end - 2);
return _this.handleComment(commentText, comment);
});
return this.enableDisableRuleMap;
};
EnableDisableRulesWalker.prototype.getStartOfLinePosition = function (position, lineOffset) {
if (lineOffset === void 0) { lineOffset = 0; }
var line = ts.getLineAndCharacterOfPosition(this.sourceFile, position).line + lineOffset;
var lineStarts = this.sourceFile.getLineStarts();
...
handleTslintLineSwitch = function (rules, isEnabled, modifier, range) { var start; var end; if (modifier === "line") { // start at the beginning of the line where comment starts start = this.getStartOfLinePosition(range.pos); // end at the beginning of the line following the comment end = this.getStartOfLinePosition(range.end, 1); } else if (modifier === "next-line") { // start at the beginning of the line following the comment start = this.getStartOfLinePosition(range.end, 1); if (start === undefined) { // no need to switch anything, there is no next line return; } // end at the beginning of the line following the next line end = this.getStartOfLinePosition(range.end, 2); } else { // switch rule for the rest of the file // start at the current position, but skip end position start = range.pos; end = undefined; } for (var _i = 0, rules_1 = rules; _i < rules_1.length; _i++) { var ruleToSwitch = rules_1[_i]; this.switchRuleState(ruleToSwitch, isEnabled, start, end); } }
...
}
if (rulesList.length === 0 ||
rulesList.indexOf("all") !== -1) {
// if list is empty we default to all enabled rules
// if `all` is specified we ignore the other rules and take all enabled rules
rulesList = this.enabledRules;
}
this.handleTslintLineSwitch(rulesList, match[1] === "enable", match
[2], range);
}
};
EnableDisableRulesWalker.prototype.handleTslintLineSwitch = function (rules, isEnabled, modifier, range) {
var start;
var end;
if (modifier === "line") {
// start at the beginning of the line where comment starts
...
switchRuleState = function (ruleName, isEnabled, start, end) { var ruleStateMap = this.enableDisableRuleMap.get(ruleName); if (ruleStateMap === undefined || isEnabled === ruleStateMap[ruleStateMap.length - 1].isEnabled // no need to add switch points if there is no change ) { return; } ruleStateMap.push({ isEnabled: isEnabled, position: start, }); if (end) { // we only get here when rule state changes therefore we can safely use opposite state ruleStateMap.push({ isEnabled: !isEnabled, position: end, }); } }
...
// switch rule for the rest of the file
// start at the current position, but skip end position
start = range.pos;
end = undefined;
}
for (var _i = 0, rules_1 = rules; _i < rules_1.length; _i++) {
var ruleToSwitch = rules_1[_i];
this.switchRuleState(ruleToSwitch, isEnabled, start, end);
}
};
return EnableDisableRulesWalker;
}());
exports.EnableDisableRulesWalker = EnableDisableRulesWalker;
...
function AbstractFormatter() { }
n/a
function Formatter() { return _super !== null && _super.apply(this, arguments) || this; }
n/a
function Formatter() { return _super !== null && _super.apply(this, arguments) || this; }
n/a
function Formatter() { return _super !== null && _super.apply(this, arguments) || this; }
n/a
function Formatter() { return _super !== null && _super.apply(this, arguments) || this; }
n/a
function Formatter() { return _super !== null && _super.apply(this, arguments) || this; }
n/a
function Formatter() { return _super !== null && _super.apply(this, arguments) || this; }
n/a
function Formatter() { return _super !== null && _super.apply(this, arguments) || this; }
n/a
function Formatter() { return _super !== null && _super.apply(this, arguments) || this; }
n/a
function Formatter() { return _super !== null && _super.apply(this, arguments) || this; }
n/a
function Formatter() { return _super !== null && _super.apply(this, arguments) || this; }
n/a
format = function (failures) { if (typeof failures[0] === "undefined") { return "\n"; } var outputLines = []; var currentFile; for (var _i = 0, failures_1 = failures; _i < failures_1.length; _i++) { var failure = failures_1[_i]; var fileName = failure.getFileName(); // Output the name of each file once if (currentFile !== fileName) { outputLines.push(""); outputLines.push(fileName); currentFile = fileName; } var failureString = failure.getFailure(); failureString = colors.red(failureString); // Rule var ruleName = failure.getRuleName(); ruleName = colors.gray("(" + ruleName + ")"); // Frame var lineAndCharacter = failure.getStartPosition().getLineAndCharacter(); var frame = codeFrame(failure.getRawLines(), lineAndCharacter.line + 1, // babel-code-frame is 1 index lineAndCharacter.character, { forceColor: colors.enabled, highlightCode: true, }); // Ouput outputLines.push(failureString + " " + ruleName); outputLines.push(frame); outputLines.push(""); } // Removes initial blank line if (outputLines[0] === "") { outputLines.shift(); } return outputLines.join("\n") + "\n"; }
n/a
function Formatter() { return _super !== null && _super.apply(this, arguments) || this; }
n/a
function Formatter() { return _super !== null && _super.apply(this, arguments) || this; }
n/a
format = function (failures) { if (failures.length === 0) { return ""; } var files = []; var currentFile; for (var _i = 0, failures_1 = failures; _i < failures_1.length; _i++) { var failure = failures_1[_i]; var fileName = failure.getFileName(); if (fileName !== currentFile) { files.push(fileName); currentFile = fileName; } } return files.join("\n") + "\n"; }
n/a
function Formatter() { return _super !== null && _super.apply(this, arguments) || this; }
n/a
function Formatter() { return _super !== null && _super.apply(this, arguments) || this; }
n/a
format = function (failures) { var failuresJSON = failures.map(function (failure) { return failure.toJson(); }); return JSON.stringify(failuresJSON); }
n/a
function Formatter() { return _super !== null && _super.apply(this, arguments) || this; }
n/a
function Formatter() { return _super !== null && _super.apply(this, arguments) || this; }
n/a
format = function (failures) { var output = "<pmd version=\"tslint\">"; for (var _i = 0, failures_1 = failures; _i < failures_1.length; _i++) { var failure = failures_1[_i]; var failureString = failure.getFailure() .replace(/&/g, "&") .replace(/</g, "<") .replace(/>/g, ">") .replace(/'/g, "'") .replace(/"/g, """); var lineAndCharacter = failure.getStartPosition().getLineAndCharacter(); var priority = failure.getRuleSeverity() === "warning" ? 4 : 3; output += "<file name=\"" + failure.getFileName(); output += "\"><violation begincolumn=\"" + (lineAndCharacter.character + 1); output += "\" beginline=\"" + (lineAndCharacter.line + 1); output += "\" priority=\"" + priority + "\""; output += " rule=\"" + failureString + "\"> </violation></file>"; } output += "</pmd>"; return output; }
n/a
function Formatter() { return _super !== null && _super.apply(this, arguments) || this; }
n/a
function Formatter() { return _super !== null && _super.apply(this, arguments) || this; }
n/a
format = function (failures, fixes) { if (failures.length === 0 && (!fixes || fixes.length === 0)) { return "\n"; } var fixLines = []; if (fixes) { var perFileFixes = new Map(); for (var _i = 0, fixes_1 = fixes; _i < fixes_1.length; _i++) { var fix = fixes_1[_i]; perFileFixes.set(fix.getFileName(), (perFileFixes.get(fix.getFileName()) || 0) + 1); } perFileFixes.forEach(function (fixCount, fixedFile) { fixLines.push("Fixed " + fixCount + " error(s) in " + fixedFile); }); fixLines.push(""); // add a blank line between fixes and failures } var errorLines = failures.map(function (failure) { var fileName = failure.getFileName(); var failureString = failure.getFailure(); var lineAndCharacter = failure.getStartPosition().getLineAndCharacter(); var positionTuple = "[" + (lineAndCharacter.line + 1) + ", " + (lineAndCharacter.character + 1) + "]"; return failure.getRuleSeverity().toUpperCase() + ": " + fileName + positionTuple + ": " + failureString; }); return fixLines.concat(errorLines).join("\n") + "\n"; }
n/a
function Formatter() { return _super !== null && _super.apply(this, arguments) || this; }
n/a
function Formatter() { return _super !== null && _super.apply(this, arguments) || this; }
n/a
format = function (failures) { var outputLines = this.mapToMessages(failures); // Removes initial blank line if (outputLines[0] === "") { outputLines.shift(); } return outputLines.join("\n") + "\n"; }
n/a
getPositionMaxSize = function (failures) { var positionMaxSize = 0; for (var _i = 0, failures_2 = failures; _i < failures_2.length; _i++) { var failure = failures_2[_i]; var lineAndCharacter = failure.getStartPosition().getLineAndCharacter(); var positionSize = (lineAndCharacter.line + 1 + ":" + (lineAndCharacter.character + 1)).length; if (positionSize > positionMaxSize) { positionMaxSize = positionSize; } } return positionMaxSize; }
n/a
getRuleMaxSize = function (failures) { var ruleMaxSize = 0; for (var _i = 0, failures_3 = failures; _i < failures_3.length; _i++) { var failure = failures_3[_i]; var ruleSize = failure.getRuleName().length; if (ruleSize > ruleMaxSize) { ruleMaxSize = ruleSize; } } return ruleMaxSize; }
n/a
mapToMessages = function (failures) { if (!failures) { return []; } var outputLines = []; var positionMaxSize = this.getPositionMaxSize(failures); var ruleMaxSize = this.getRuleMaxSize(failures); var currentFile; for (var _i = 0, failures_1 = failures; _i < failures_1.length; _i++) { var failure = failures_1[_i]; var fileName = failure.getFileName(); // Output the name of each file once if (currentFile !== fileName) { outputLines.push(""); outputLines.push(fileName); currentFile = fileName; } var failureString = failure.getFailure(); failureString = colors.yellow(failureString); // Rule var ruleName = failure.getRuleName(); ruleName = this.pad(ruleName, ruleMaxSize); ruleName = colors.grey(ruleName); // Lines var lineAndCharacter = failure.getStartPosition().getLineAndCharacter(); var positionTuple = lineAndCharacter.line + 1 + ":" + (lineAndCharacter.character + 1); positionTuple = this.pad(positionTuple, positionMaxSize); if (failure.getRuleSeverity() === "warning") { positionTuple = colors.blue(failure.getRuleSeverity().toUpperCase() + ": " + positionTuple); } else { positionTuple = colors.red(failure.getRuleSeverity().toUpperCase() + ": " + positionTuple); } // Output var output = positionTuple + " " + ruleName + " " + failureString; outputLines.push(output); } return outputLines; }
n/a
pad = function (str, len) { var padder = Array(len + 1).join(" "); return (str + padder).substring(0, padder.length); }
n/a
function Formatter() { return _super !== null && _super.apply(this, arguments) || this; }
n/a
function Formatter() { return _super !== null && _super.apply(this, arguments) || this; }
n/a
format = function (failures) { var output = ["TAP version 13"]; if (failures.length === 0) { output = output.concat([ "1..0 # SKIP No failures", ]); } else { output = output.concat(["1.." + failures.length]).concat(this.mapToMessages(failures)); } return output.join("\n") + "\n"; }
n/a
mapToMessages = function (failures) { return failures.map(function (failure, i) { var fileName = failure.getFileName(); var failureString = failure.getFailure(); var ruleName = failure.getRuleName(); var failureMessage = failure.getFailure(); var failureSeverity = failure.getRuleSeverity(); var failureRaw = failure.getRawLines(); var lineAndCharacter = failure.getStartPosition().getLineAndCharacter(); return (_a = ["\n not ok ", " - ", "\n ---\n message : ", "\n severity: ", "\n data:\n ruleName: ", "\n fileName: ", "\n line: ", "\n character: ", "\n failureString: ", "\n rawLines: ", "\n ..."], _a.raw = ["\n not ok ", " - ", "\n ---\n message : ", "\n severity: ", "\n data:\n ruleName: ", "\n fileName: ", "\n line: ", "\n character: ", "\n failureString: ", "\n rawLines: ", "\n ..."], Utils.dedent(_a, String(i + 1), failureMessage, failureMessage, failureSeverity, ruleName, fileName, String(lineAndCharacter.line), String(lineAndCharacter.character), failureString, failureRaw)); var _a; }); }
n/a
function Formatter() { return _super !== null && _super.apply(this, arguments) || this; }
n/a
function Formatter() { return _super !== null && _super.apply(this, arguments) || this; }
n/a
format = function (failures) { return this.mapToMessages(failures) .join("\n") + "\n"; }
n/a
mapToMessages = function (failures) { return failures.map(function (failure) { var fileName = failure.getFileName(); var failureString = failure.getFailure(); var ruleName = failure.getRuleName(); var lineAndCharacter = failure.getStartPosition().getLineAndCharacter(); var positionTuple = "[" + (lineAndCharacter.line + 1) + ", " + (lineAndCharacter.character + 1) + "]"; return failure.getRuleSeverity().toUpperCase() + ": (" + ruleName + ") " + fileName + positionTuple + ": " + failureString ; }); }
n/a
function Linter(options, program) { this.options = options; this.program = program; this.failures = []; this.fixes = []; if (typeof options !== "object") { throw new Error("Unknown Linter options type: " + typeof options); } if (options.configuration != null) { throw new Error("ILinterOptions does not contain the property `configuration` as of version 4. " + "Did you mean to pass the `IConfigurationFile` object to lint() ? "); } }
n/a
createProgram = function (configFile, projectDirectory) { if (projectDirectory === undefined) { projectDirectory = path.dirname(configFile); } var config = ts.readConfigFile(configFile, ts.sys.readFile).config; var parseConfigHost = { fileExists: fs.existsSync, readDirectory: ts.sys.readDirectory, readFile: function (file) { return fs.readFileSync(file, "utf8"); }, useCaseSensitiveFileNames: true, }; var parsed = ts.parseJsonConfigFileContent(config, parseConfigHost, projectDirectory); var host = ts.createCompilerHost(parsed.options, true); var program = ts.createProgram(parsed.fileNames, parsed.options, host); return program; }
...
var files = this.options.files === undefined ? [] : this.options.files;
var program;
if (this.options.project != null) {
if (!fs.existsSync(this.options.project)) {
console.error("Invalid option for project: " + this.options.project);
return onComplete(1);
}
program = Linter.createProgram(this.options.project);
if (files.length === 0) {
files = Linter.getFileNames(program);
}
if (this.options.typeCheck) {
// if type checking, run the type checker
var diagnostics = ts.getPreEmitDiagnostics(program);
if (diagnostics.length > 0) {
...
function findConfiguration(configFile, inputFilePath) { var path = findConfigurationPath(configFile, inputFilePath); var loadResult = { path: path }; try { loadResult.results = loadConfigurationFromPath(path); return loadResult; } catch (error) { throw new error_1.FatalError("Failed to load " + path + ": " + error.message, error); } }
...
}
finally {
fs.closeSync(fd);
}
var contents = fs.readFileSync(file, "utf8");
var folder = path.dirname(file);
if (lastFolder !== folder) {
configFile = configuration_1.findConfiguration(possibleConfigAbsolutePath, folder
).results;
lastFolder = folder;
}
linter.lint(file, contents, configFile);
}
var lintResult = linter.getResult();
this.outputStream.write(lintResult.output, function () {
if (_this.options.force || lintResult.errorCount === 0) {
...
function findConfigurationPath(suppliedConfigFilePath, inputFilePath) { if (suppliedConfigFilePath != null) { if (!fs.existsSync(suppliedConfigFilePath)) { throw new Error("Could not find config file at: " + path.resolve(suppliedConfigFilePath)); } else { return path.resolve(suppliedConfigFilePath); } } else { // search for tslint.json from input file location var configFilePath = findup(exports.CONFIG_FILENAME, { cwd: inputFilePath, nocase: true }); if (configFilePath != null && fs.existsSync(configFilePath)) { return path.resolve(configFilePath); } // search for tslint.json in home directory var homeDir = getHomeDir(); if (homeDir != null) { configFilePath = path.join(homeDir, exports.CONFIG_FILENAME); if (fs.existsSync(configFilePath)) { return path.resolve(configFilePath); } } // no path could be found return undefined; } }
n/a
getFileNames = function (program) { return program.getSourceFiles().map(function (s) { return s.fileName; }).filter(function (l) { return l.substr(-5) !== ".d.ts "; }); }
...
if (this.options.project != null) {
if (!fs.existsSync(this.options.project)) {
console.error("Invalid option for project: " + this.options.project);
return onComplete(1);
}
program = Linter.createProgram(this.options.project);
if (files.length === 0) {
files = Linter.getFileNames(program);
}
if (this.options.typeCheck) {
// if type checking, run the type checker
var diagnostics = ts.getPreEmitDiagnostics(program);
if (diagnostics.length > 0) {
var messages = diagnostics.map(function (diag) {
// emit any error messages
...
function getRulesDirectories(directories, relativeTo) { var rulesDirectories = utils_1.arrayify(directories) .map(function (dir) { return getRelativePath(dir, relativeTo); }) .filter(function (dir) { return dir !== undefined; }); for (var _i = 0, rulesDirectories_1 = rulesDirectories; _i < rulesDirectories_1.length; _i++) { var directory = rulesDirectories_1[_i]; if (directory != null && !fs.existsSync(directory)) { throw new Error("Could not find custom rule directory: " + directory); } } return rulesDirectories; }
n/a
function loadConfigurationFromPath(configFilePath) { if (configFilePath == null) { return exports.DEFAULT_CONFIG; } else { var resolvedConfigFilePath = resolveConfigurationPath(configFilePath); var rawConfigFile = void 0; if (path.extname(resolvedConfigFilePath) === ".json") { var fileContent = utils_1.stripComments(fs.readFileSync(resolvedConfigFilePath) .toString() .replace(/^\uFEFF/, "")); rawConfigFile = JSON.parse(fileContent); } else { rawConfigFile = require(resolvedConfigFilePath); delete require.cache[resolvedConfigFilePath]; } var configFileDir_1 = path.dirname(resolvedConfigFilePath); var configFile = parseConfigFile(rawConfigFile, configFileDir_1); // load configurations, in order, using their identifiers or relative paths // apply the current configuration last by placing it last in this array var configs = configFile.extends.map(function (name) { var nextConfigFilePath = resolveConfigurationPath(name, configFileDir_1); return loadConfigurationFromPath(nextConfigFilePath); }).concat([configFile]); return configs.reduce(extendConfigurationFile, exports.EMPTY_CONFIG); } }
n/a
applyFixes = function (sourceFilePath, sourceContent, ruleFailures) { var fixesPerFile = ruleFailures .reduce(function (accum, c) { var currentFileName = c.getFileName(); var fix = c.getFix(); if (fix) { accum[currentFileName] = accum[currentFileName] || []; accum[currentFileName].push(fix); } return accum; }, {}); var hasFixes = Object.keys(fixesPerFile).length > 0; var result = sourceContent; if (hasFixes) { this.fixes = this.fixes.concat(ruleFailures); Object.keys(fixesPerFile).forEach(function (currentFileName) { var fixesForFile = fixesPerFile[currentFileName]; var source = fs.readFileSync(currentFileName, { encoding: "utf-8" }); source = rule_1.Replacement.applyFixes(source, fixesForFile); fs.writeFileSync(currentFileName, source, { encoding: "utf-8" }); if (sourceFilePath === currentFileName) { result = source; } }); } return result; }
n/a
applyRule = function (rule, sourceFile) { var ruleFailures = []; try { if (this.program && rule_1.isTypedRule(rule)) { ruleFailures = rule.applyWithProgram(sourceFile, this.program); } else { ruleFailures = rule.apply(sourceFile); } } catch (error) { if (error_1.isError(error)) { error_1.showWarningOnce("Warning: " + error.message); } else { console.warn("Warning: " + error); } } var fileFailures = []; for (var _i = 0, ruleFailures_1 = ruleFailures; _i < ruleFailures_1.length; _i++) { var ruleFailure = ruleFailures_1[_i]; if (!this.containsRule(this.failures, ruleFailure)) { fileFailures.push(ruleFailure); } } return fileFailures; }
n/a
containsRule = function (rules, rule) { return rules.some(function (r) { return r.equals(rule); }); }
n/a
getEnabledRules = function (sourceFile, configuration, isJs) { if (configuration === void 0) { configuration = configuration_1.DEFAULT_CONFIG; } var ruleOptionsList = configuration_1.convertRuleOptions(isJs ? configuration.jsRules : configuration.rules); // walk the code first to find all the intervals where rules are disabled var enableDisableRuleMap = new enableDisableRules_1.EnableDisableRulesWalker(sourceFile, ruleOptionsList).getEnableDisableRuleMap (); var rulesDirectories = utils_1.arrayify(this.options.rulesDirectory) .concat(utils_1.arrayify(configuration.rulesDirectory)); var configuredRules = ruleLoader_1.loadRules(ruleOptionsList, enableDisableRuleMap, rulesDirectories, isJs); return configuredRules.filter(function (r) { return r.isEnabled(); }); }
n/a
getResult = function () { var formatter; var formattersDirectory = configuration_1.getRelativePath(this.options.formattersDirectory); var formatterName = this.options.formatter || "prose"; var Formatter = formatterLoader_1.findFormatter(formatterName, formattersDirectory); if (Formatter) { formatter = new Formatter(); } else { throw new Error("formatter '" + formatterName + "' not found"); } var output = formatter.format(this.failures, this.fixes); var errorCount = this.failures.filter(function (failure) { return failure.getRuleSeverity() === "error"; }).length; return { errorCount: errorCount, failures: this.failures, fixes: this.fixes, format: formatterName, output: output, warningCount: this.failures.length - errorCount, }; }
...
var folder = path.dirname(file);
if (lastFolder !== folder) {
configFile = configuration_1.findConfiguration(possibleConfigAbsolutePath, folder).results;
lastFolder = folder;
}
linter.lint(file, contents, configFile);
}
var lintResult = linter.getResult();
this.outputStream.write(lintResult.output, function () {
if (_this.options.force || lintResult.errorCount === 0) {
onComplete(0);
}
else {
onComplete(2);
}
...
getSourceFile = function (fileName, source) { if (this.program) { var sourceFile = this.program.getSourceFile(fileName); if (sourceFile === undefined) { var INVALID_SOURCE_ERROR = (_a = ["\n Invalid source file: ", ". Ensure that the files supplied to lint have a .ts, .tsx, .js or .jsx extension.\n "], _a.raw = ["\n Invalid source file: ", ". Ensure that the files supplied to lint have a .ts, .tsx, .js or .jsx extension.\n "], utils_1.dedent(_a, fileName)); throw new Error(INVALID_SOURCE_ERROR); } // check if the program has been type checked if (!("resolvedModules" in sourceFile)) { throw new Error("Program must be type checked before linting"); } return sourceFile; } else { return utils.getSourceFile(fileName, source); } var _a; }
n/a
lint = function (fileName, source, configuration) { if (configuration === void 0) { configuration = configuration_1.DEFAULT_CONFIG; } var sourceFile = this.getSourceFile(fileName, source); var isJs = /\.jsx?$/i.test(fileName); var enabledRules = this.getEnabledRules(sourceFile, configuration, isJs); var hasLinterRun = false; var fileFailures = []; if (this.options.fix) { for (var _i = 0, enabledRules_1 = enabledRules; _i < enabledRules_1.length; _i++) { var rule = enabledRules_1[_i]; var ruleFailures = this.applyRule(rule, sourceFile); source = this.applyFixes(fileName, source, ruleFailures); sourceFile = this.getSourceFile(fileName, source); fileFailures = fileFailures.concat(ruleFailures); } hasLinterRun = true; } // make a 1st pass or make a 2nd pass if there were any fixes because the positions may be off if (!hasLinterRun || this.fixes.length > 0) { fileFailures = []; for (var _a = 0, enabledRules_2 = enabledRules; _a < enabledRules_2.length; _a++) { var rule = enabledRules_2[_a]; var ruleFailures = this.applyRule(rule, sourceFile); if (ruleFailures.length > 0) { fileFailures = fileFailures.concat(ruleFailures); } } } this.failures = this.failures.concat(fileFailures); // add rule severity to failures var ruleSeverityMap = new Map(enabledRules.map(function (rule) { return [rule.getOptions().ruleName, rule.getOptions().ruleSeverity]; })); for (var _b = 0, _c = this.failures; _b < _c.length; _b++) { var failure = _c[_b]; var severity = ruleSeverityMap.get(failure.getRuleName()); if (severity === undefined) { throw new Error("Severity for rule '" + failure.getRuleName() + " not found"); } failure.setRuleSeverity(severity); } }
...
}
var contents = fs.readFileSync(file, "utf8");
var folder = path.dirname(file);
if (lastFolder !== folder) {
configFile = configuration_1.findConfiguration(possibleConfigAbsolutePath, folder).results;
lastFolder = folder;
}
linter.lint(file, contents, configFile);
}
var lintResult = linter.getResult();
this.outputStream.write(lintResult.output, function () {
if (_this.options.force || lintResult.errorCount === 0) {
onComplete(0);
}
else {
...
function ProgramAwareRuleWalker(sourceFile, options, program) { var _this = _super.call(this, sourceFile, options) || this; _this.program = program; _this.typeChecker = program.getTypeChecker(); return _this; }
n/a
function ProgramAwareRuleWalker(sourceFile, options, program) { var _this = _super.call(this, sourceFile, options) || this; _this.program = program; _this.typeChecker = program.getTypeChecker(); return _this; }
n/a
getProgram = function () { return this.program; }
n/a
getTypeChecker = function () { return this.typeChecker; }
n/a
function Replacement(innerStart, innerLength, innerText) { this.innerStart = innerStart; this.innerLength = innerLength; this.innerText = innerText; }
n/a
appendText = function (start, text) { return new Replacement(start, 0, text); }
n/a
applyAll = function (content, replacements) { // sort in reverse so that diffs are properly applied replacements.sort(function (a, b) { return b.end - a.end; }); return replacements.reduce(function (text, r) { return r.apply(text); }, content); }
n/a
applyFixes = function (content, fixes) { return this.applyAll(content, utils_1.flatMap(fixes, utils_1.arrayify)); }
n/a
deleteFromTo = function (start, end) { return new Replacement(start, end - start, ""); }
n/a
deleteText = function (start, length) { return new Replacement(start, length, ""); }
n/a
replaceFromTo = function (start, end, text) { return new Replacement(start, end - start, text); }
n/a
replaceNode = function (node, text, sourceFile) { return this.replaceFromTo(node.getStart(sourceFile), node.getEnd(), text); }
n/a
apply = function (content) { return content.substring(0, this.start) + this.text + content.substring(this.start + this.length); }
n/a
function RuleFailure(sourceFile, start, end, failure, ruleName, fix) { this.sourceFile = sourceFile; this.failure = failure; this.ruleName = ruleName; this.fix = fix; this.fileName = sourceFile.fileName; this.startPosition = this.createFailurePosition(start); this.endPosition = this.createFailurePosition(end); this.rawLines = sourceFile.text; this.ruleSeverity = "error"; }
n/a
createFailurePosition = function (position) { var lineAndCharacter = this.sourceFile.getLineAndCharacterOfPosition(position); return new RuleFailurePosition(position, lineAndCharacter); }
n/a
equals = function (ruleFailure) { return this.failure === ruleFailure.getFailure() && this.fileName === ruleFailure.getFileName() && this.startPosition.equals(ruleFailure.getStartPosition()) && this.endPosition.equals(ruleFailure.getEndPosition()); }
n/a
getEndPosition = function () { return this.endPosition; }
n/a
getFailure = function () { return this.failure; }
n/a
getFileName = function () { return this.fileName; }
n/a
getFix = function () { return this.fix; }
n/a
getRawLines = function () { return this.rawLines; }
n/a
getRuleName = function () { return this.ruleName; }
n/a
getRuleSeverity = function () { return this.ruleSeverity; }
n/a
getStartPosition = function () { return this.startPosition; }
n/a
hasFix = function () { return this.fix !== undefined; }
n/a
setRuleSeverity = function (value) { this.ruleSeverity = value; }
n/a
toJson = function () { return { endPosition: this.endPosition.toJson(), failure: this.failure, fix: this.fix, name: this.fileName, ruleName: this.ruleName, ruleSeverity: this.ruleSeverity.toUpperCase(), startPosition: this.startPosition.toJson(), }; }
n/a
function RuleFailurePosition(position, lineAndCharacter) { this.position = position; this.lineAndCharacter = lineAndCharacter; }
n/a
equals = function (ruleFailurePosition) { var ll = this.lineAndCharacter; var rr = ruleFailurePosition.lineAndCharacter; return this.position === ruleFailurePosition.position && ll.line === rr.line && ll.character === rr.character; }
n/a
getLineAndCharacter = function () { return this.lineAndCharacter; }
n/a
getPosition = function () { return this.position; }
n/a
toJson = function () { return { character: this.lineAndCharacter.character, line: this.lineAndCharacter.line, position: this.position, }; }
n/a
function RuleWalker(sourceFile, options) { var _this = _super.call(this) || this; _this.sourceFile = sourceFile; _this.failures = []; _this.options = options.ruleArguments; _this.limit = _this.sourceFile.getFullWidth(); _this.ruleName = options.ruleName; return _this; }
n/a
addFailure = function (failure) { this.failures.push(failure); }
n/a
addFailureAt = function (start, width, failure, fix) { this.addFailure(this.createFailure(start, width, failure, fix)); }
n/a
addFailureAtNode = function (node, failure, fix) { this.addFailureAt(node.getStart(this.sourceFile), node.getWidth(this.sourceFile), failure, fix); }
n/a
addFailureFromStartToEnd = function (start, end, failure, fix) { this.addFailureAt(start, end - start, failure, fix); }
n/a
appendText = function (start, text) { return this.createReplacement(start, 0, text); }
n/a
function RuleWalker(sourceFile, options) { var _this = _super.call(this) || this; _this.sourceFile = sourceFile; _this.failures = []; _this.options = options.ruleArguments; _this.limit = _this.sourceFile.getFullWidth(); _this.ruleName = options.ruleName; return _this; }
n/a
createFailure = function (start, width, failure, fix) { var from = (start > this.limit) ? this.limit : start; var to = ((start + width) > this.limit) ? this.limit : (start + width); return new rule_1.RuleFailure(this.sourceFile, from, to, failure, this.ruleName, fix); }
n/a
createReplacement = function (start, length, text) { return new rule_1.Replacement(start, length, text); }
n/a
deleteFromTo = function (start, end) { return this.createReplacement(start, end - start, ""); }
n/a
deleteText = function (start, length) { return this.createReplacement(start, length, ""); }
n/a
getFailures = function () { return this.failures; }
n/a
getLimit = function () { return this.limit; }
n/a
getLineAndCharacterOfPosition = function (position) { return this.sourceFile.getLineAndCharacterOfPosition(position); }
...
: fullText.substring(comment.pos + 2, comment.end - 2);
return _this.handleComment(commentText, comment);
});
return this.enableDisableRuleMap;
};
EnableDisableRulesWalker.prototype.getStartOfLinePosition = function (position, lineOffset) {
if (lineOffset === void 0) { lineOffset = 0; }
var line = ts.getLineAndCharacterOfPosition(this.sourceFile, position).line + lineOffset
;
var lineStarts = this.sourceFile.getLineStarts();
if (line >= lineStarts.length) {
// next line ends with eof or there is no next line
// undefined switches the rule until the end and avoids an extra array entry
return undefined;
}
return lineStarts[line];
...
getOptions = function () { return this.options; }
n/a
getRuleName = function () { return this.ruleName; }
n/a
getSourceFile = function () { return this.sourceFile; }
n/a
hasOption = function (option) { if (this.options) { return this.options.indexOf(option) !== -1; } else { return false; } }
n/a
function AbstractRule(options) { this.options = options; this.ruleName = options.ruleName; this.ruleArguments = options.ruleArguments; this.ruleSeverity = options.ruleSeverity; }
n/a
function OptionallyTypedRule() { return _super !== null && _super.apply(this, arguments) || this; }
n/a
function TypedRule() { return _super !== null && _super.apply(this, arguments) || this; }
n/a
function AbstractRule(options) { this.options = options; this.ruleName = options.ruleName; this.ruleArguments = options.ruleArguments; this.ruleSeverity = options.ruleSeverity; }
n/a
applyWithFunction = function (sourceFile, walkFn, options) { var ctx = new walker_1.WalkContext(sourceFile, this.ruleName, options); walkFn(ctx); return this.filterFailures(ctx.failures); }
n/a
applyWithWalker = function (walker) { walker.walk(walker.getSourceFile()); return this.filterFailures(walker.getFailures()); }
n/a
filterFailures = function (failures) { var result = []; var _loop_1 = function (failure) { // don't add failures for a rule if the failure intersects an interval where that rule is disabled if (!utils_1.doesIntersect(failure, this_1.options.disabledIntervals) && !result.some(function (f) { return f.equals(failure ); })) { result.push(failure); } }; var this_1 = this; for (var _i = 0, failures_1 = failures; _i < failures_1.length; _i++) { var failure = failures_1[_i]; _loop_1(failure); } return result; }
n/a
getOptions = function () { return this.options; }
n/a
isEnabled = function () { return this.ruleSeverity !== "off"; }
n/a
function OptionallyTypedRule() { return _super !== null && _super.apply(this, arguments) || this; }
n/a
function OptionallyTypedRule() { return _super !== null && _super.apply(this, arguments) || this; }
n/a
function TypedRule() { return _super !== null && _super.apply(this, arguments) || this; }
n/a
apply = function () { // if no program is given to the linter, throw an error throw new Error("The '" + this.ruleName + "' rule requires type checking"); }
n/a
function TypedRule() { return _super !== null && _super.apply(this, arguments) || this; }
n/a
function ScopeAwareRuleWalker(sourceFile, options) { var _this = _super.call(this, sourceFile, options) || this; // initialize with global scope if file is not a module _this.scopeStack = ts.isExternalModule(sourceFile) ? [] : [_this.createScope(sourceFile)]; return _this; }
n/a
function ScopeAwareRuleWalker(sourceFile, options) { var _this = _super.call(this, sourceFile, options) || this; // initialize with global scope if file is not a module _this.scopeStack = ts.isExternalModule(sourceFile) ? [] : [_this.createScope(sourceFile)]; return _this; }
n/a
getAllScopes = function () { return this.scopeStack; }
n/a
getCurrentDepth = function () { return this.scopeStack.length; }
n/a
getCurrentScope = function () { return this.scopeStack[this.scopeStack.length - 1]; }
n/a
isScopeBoundary = function (node) { return utils_1.isScopeBoundary(node); }
n/a
onScopeEnd = function () { return; }
n/a
onScopeStart = function () { return; }
n/a
visitNode = function (node) { var isNewScope = this.isScopeBoundary(node); if (isNewScope) { this.scopeStack.push(this.createScope(node)); this.onScopeStart(); } _super.prototype.visitNode.call(this, node); if (isNewScope) { this.onScopeEnd(); this.scopeStack.pop(); } }
n/a
function SyntaxWalker() { }
n/a
visitAnyKeyword = function (node) { this.walkChildren(node); }
n/a
visitArrayLiteralExpression = function (node) { this.walkChildren(node); }
n/a
visitArrayType = function (node) { this.walkChildren(node); }
n/a
visitArrowFunction = function (node) { this.walkChildren(node); }
n/a
visitBinaryExpression = function (node) { this.walkChildren(node); }
n/a
visitBindingElement = function (node) { this.walkChildren(node); }
n/a
visitBindingPattern = function (node) { this.walkChildren(node); }
n/a
visitBlock = function (node) { this.walkChildren(node); }
n/a
visitBreakStatement = function (node) { this.walkChildren(node); }
n/a
visitCallExpression = function (node) { this.walkChildren(node); }
n/a
visitCallSignature = function (node) { this.walkChildren(node); }
n/a
visitCaseClause = function (node) { this.walkChildren(node); }
n/a
visitCatchClause = function (node) { this.walkChildren(node); }
n/a
visitClassDeclaration = function (node) { this.walkChildren(node); }
n/a
visitClassExpression = function (node) { this.walkChildren(node); }
n/a
visitConditionalExpression = function (node) { this.walkChildren(node); }
n/a
visitConstructSignature = function (node) { this.walkChildren(node); }
n/a
visitConstructorDeclaration = function (node) { this.walkChildren(node); }
n/a
visitConstructorType = function (node) { this.walkChildren(node); }
n/a
visitContinueStatement = function (node) { this.walkChildren(node); }
n/a
visitDebuggerStatement = function (node) { this.walkChildren(node); }
n/a
visitDefaultClause = function (node) { this.walkChildren(node); }
n/a
visitDoStatement = function (node) { this.walkChildren(node); }
n/a
visitElementAccessExpression = function (node) { this.walkChildren(node); }
n/a
visitEndOfFileToken = function (node) { this.walkChildren(node); }
n/a
visitEnumDeclaration = function (node) { this.walkChildren(node); }
n/a
visitExportAssignment = function (node) { this.walkChildren(node); }
n/a
visitExpressionStatement = function (node) { this.walkChildren(node); }
n/a
visitForInStatement = function (node) { this.walkChildren(node); }
n/a
visitForOfStatement = function (node) { this.walkChildren(node); }
n/a
visitForStatement = function (node) { this.walkChildren(node); }
n/a
visitFunctionDeclaration = function (node) { this.walkChildren(node); }
n/a
visitFunctionExpression = function (node) { this.walkChildren(node); }
n/a
visitFunctionType = function (node) { this.walkChildren(node); }
n/a
visitGetAccessor = function (node) { this.walkChildren(node); }
n/a
visitIdentifier = function (node) { this.walkChildren(node); }
n/a
visitIfStatement = function (node) { this.walkChildren(node); }
n/a
visitImportDeclaration = function (node) { this.walkChildren(node); }
n/a
visitImportEqualsDeclaration = function (node) { this.walkChildren(node); }
n/a
visitIndexSignatureDeclaration = function (node) { this.walkChildren(node); }
n/a
visitInterfaceDeclaration = function (node) { this.walkChildren(node); }
n/a
visitJsxAttribute = function (node) { this.walkChildren(node); }
n/a
visitJsxElement = function (node) { this.walkChildren(node); }
n/a
visitJsxExpression = function (node) { this.walkChildren(node); }
n/a
visitJsxSelfClosingElement = function (node) { this.walkChildren(node); }
n/a
visitJsxSpreadAttribute = function (node) { this.walkChildren(node); }
n/a
visitLabeledStatement = function (node) { this.walkChildren(node); }
n/a
visitMethodDeclaration = function (node) { this.walkChildren(node); }
n/a
visitMethodSignature = function (node) { this.walkChildren(node); }
n/a
visitModuleDeclaration = function (node) { this.walkChildren(node); }
n/a
visitNamedImports = function (node) { this.walkChildren(node); }
n/a
visitNamespaceImport = function (node) { this.walkChildren(node); }
n/a
visitNewExpression = function (node) { this.walkChildren(node); }
n/a
visitNode = function (node) { switch (node.kind) { case ts.SyntaxKind.AnyKeyword: this.visitAnyKeyword(node); break; case ts.SyntaxKind.ArrayBindingPattern: this.visitBindingPattern(node); break; case ts.SyntaxKind.ArrayLiteralExpression: this.visitArrayLiteralExpression(node); break; case ts.SyntaxKind.ArrayType: this.visitArrayType(node); break; case ts.SyntaxKind.ArrowFunction: this.visitArrowFunction(node); break; case ts.SyntaxKind.BinaryExpression: this.visitBinaryExpression(node); break; case ts.SyntaxKind.BindingElement: this.visitBindingElement(node); break; case ts.SyntaxKind.Block: this.visitBlock(node); break; case ts.SyntaxKind.BreakStatement: this.visitBreakStatement(node); break; case ts.SyntaxKind.CallExpression: this.visitCallExpression(node); break; case ts.SyntaxKind.CallSignature: this.visitCallSignature(node); break; case ts.SyntaxKind.CaseClause: this.visitCaseClause(node); break; case ts.SyntaxKind.ClassDeclaration: this.visitClassDeclaration(node); break; case ts.SyntaxKind.ClassExpression: this.visitClassExpression(node); break; case ts.SyntaxKind.CatchClause: this.visitCatchClause(node); break; case ts.SyntaxKind.ConditionalExpression: this.visitConditionalExpression(node); break; case ts.SyntaxKind.ConstructSignature: this.visitConstructSignature(node); break; case ts.SyntaxKind.Constructor: this.visitConstructorDeclaration(node); break; case ts.SyntaxKind.ConstructorType: this.visitConstructorType(node); break; case ts.SyntaxKind.ContinueStatement: this.visitContinueStatement(node); break; case ts.SyntaxKind.DebuggerStatement: this.visitDebuggerStatement(node); break; case ts.SyntaxKind.DefaultClause: this.visitDefaultClause(node); break; case ts.SyntaxKind.DoStatement: this.visitDoStatement(node); break; case ts.SyntaxKind.ElementAccessExpression: this.visitElementAccessExpression(node); break; case ts.SyntaxKind.EndOfFileToken: this.visitEndOfFileToken(node); break; case ts.SyntaxKind.EnumDeclaration: this.visitEnumDeclaration(node); break; case ts.SyntaxKind.ExportAssignment: this.visitExportAssignment(node); break; case ts.SyntaxKind.ExpressionStatement: this.visitExpressionStatement(node); break; case ts.SyntaxKind.ForStatement: this.visitForStatement(node); break; case ts.SyntaxKind.ForInStatement: this.visitForInStatement(node); break; case ts.SyntaxKind.ForOfStatement: this.visitForOfStatement(node); break; case ts.SyntaxKind.FunctionDeclaration: this.visitFunctionDeclaration(node); break; case ts.SyntaxKind.FunctionExpression: this.visitFunctionExpression(node); break; case ts.SyntaxKind.FunctionType: this.visitFunctionType(node); break; case ts.SyntaxKind.GetAccessor: this.visitGetAccessor(node); break; case ts.SyntaxKind.Identifier: this.visitIdentifier(node); break; case ts.SyntaxKind.IfStatement: this.visitIfStatement(node); break; case ts.SyntaxKind.ImportDeclaration: this.visitImportDeclaration(node); ...
n/a
visitNonNullExpression = function (node) { this.walkChildren(node); }
n/a
visitNumericLiteral = function (node) { this.walkChildren(node); }
n/a
visitObjectLiteralExpression = function (node) { this.walkChildren(node); }
n/a
visitParameterDeclaration = function (node) { this.walkChildren(node); }
n/a
visitPostfixUnaryExpression = function (node) { this.walkChildren(node); }
n/a
visitPrefixUnaryExpression = function (node) { this.walkChildren(node); }
n/a
visitPropertyAccessExpression = function (node) { this.walkChildren(node); }
n/a
visitPropertyAssignment = function (node) { this.walkChildren(node); }
n/a
visitPropertyDeclaration = function (node) { this.walkChildren(node); }
n/a
visitPropertySignature = function (node) { this.walkChildren(node); }
n/a
visitRegularExpressionLiteral = function (node) { this.walkChildren(node); }
n/a
visitReturnStatement = function (node) { this.walkChildren(node); }
n/a
visitSetAccessor = function (node) { this.walkChildren(node); }
n/a
visitSourceFile = function (node) { this.walkChildren(node); }
n/a
visitStringLiteral = function (node) { this.walkChildren(node); }
n/a
visitSwitchStatement = function (node) { this.walkChildren(node); }
n/a
visitTemplateExpression = function (node) { this.walkChildren(node); }
n/a
visitThrowStatement = function (node) { this.walkChildren(node); }
n/a
visitTryStatement = function (node) { this.walkChildren(node); }
n/a
visitTupleType = function (node) { this.walkChildren(node); }
n/a
visitTypeAliasDeclaration = function (node) { this.walkChildren(node); }
n/a
visitTypeAssertionExpression = function (node) { this.walkChildren(node); }
n/a
visitTypeLiteral = function (node) { this.walkChildren(node); }
n/a
visitTypeReference = function (node) { this.walkChildren(node); }
n/a
visitVariableDeclaration = function (node) { this.walkChildren(node); }
n/a
visitVariableDeclarationList = function (node) { this.walkChildren(node); }
n/a
visitVariableStatement = function (node) { this.walkChildren(node); }
n/a
visitWhileStatement = function (node) { this.walkChildren(node); }
n/a
visitWithStatement = function (node) { this.walkChildren(node); }
n/a
walk = function (node) { this.visitNode(node); }
n/a
walkChildren = function (node) { var _this = this; ts.forEachChild(node, function (child) { return _this.visitNode(child); }); }
n/a
function consoleTestResultHandler(testResult) {
var didAllTestsPass = true;
for (var _i = 0, _a = Object.keys(testResult.results); _i < _a.length; _i++) {
var fileName = _a[_i];
var results = testResult.results[fileName];
process.stdout.write(fileName + ":");
/* tslint:disable:no-console */
if (results.skipped) {
console.log(colors.yellow(" Skipped, requires typescript " + results.requirement));
}
else {
var markupDiffResults = diff.diffLines(results.markupFromMarkup, results.markupFromLinter);
var fixesDiffResults = diff.diffLines(results.fixesFromLinter, results.fixesFromMarkup);
var didMarkupTestPass = !markupDiffResults.some(function (diff) { return !!diff.added || !!diff.removed; });
var didFixesTestPass = !fixesDiffResults.some(function (diff) { return !!diff.added || !!diff.removed; });
if (didMarkupTestPass && didFixesTestPass) {
console.log(colors.green(" Passed"));
}
else {
console.log(colors.red(" Failed!"));
didAllTestsPass = false;
if (!didMarkupTestPass) {
displayDiffResults(markupDiffResults, MARKUP_FILE_EXTENSION);
}
if (!didFixesTestPass) {
displayDiffResults(fixesDiffResults, FIXES_FILE_EXTENSION);
}
}
}
/* tslint:enable:no-console */
}
return didAllTestsPass;
}
n/a
function consoleTestResultsHandler(testResults) { var didAllTestsPass = true; for (var _i = 0, testResults_1 = testResults; _i < testResults_1.length; _i++) { var testResult = testResults_1[_i]; if (!consoleTestResultHandler(testResult)) { didAllTestsPass = false; } } return didAllTestsPass; }
...
}
var tslintJSON = JSON.stringify(configuration_1.DEFAULT_CONFIG, undefined, " ");
fs.writeFileSync(configuration_1.CONFIG_FILENAME, tslintJSON);
return onComplete(0);
}
if (this.options.test) {
var results = test_1.runTests((this.options.files || []).map(Runner.trimSingleQuotes), this.options.rulesDirectory);
var didAllTestsPass = test_1.consoleTestResultsHandler(results);
return onComplete(didAllTestsPass ? 0 : 1);
}
// when provided, it should point to an existing location
if (this.options.config && !fs.existsSync(this.options.config)) {
console.error("Invalid option for configuration: " + this.options.config);
return onComplete(1);
}
...
function runTest(testDirectory, rulesDirectory) { // needed to get colors to show up when passing through Grunt colors.enabled = true; var filesToLint = glob.sync(path.join(testDirectory, "**/*" + MARKUP_FILE_EXTENSION)); var tslintConfig = Linter.findConfiguration(path.join(testDirectory, "tslint.json"), "").results; var tsConfig = path.join(testDirectory, "tsconfig.json"); var compilerOptions = { allowJs: true }; if (fs.existsSync(tsConfig)) { var _a = ts.readConfigFile(tsConfig, ts.sys.readFile), config = _a.config, error = _a.error; if (error) { throw new Error(JSON.stringify(error)); } var parseConfigHost = { fileExists: fs.existsSync, readDirectory: ts.sys.readDirectory, readFile: function (file) { return fs.readFileSync(file, "utf8"); }, useCaseSensitiveFileNames: true, }; compilerOptions = ts.parseJsonConfigFileContent(config, parseConfigHost, testDirectory).options; } var results = { directory: testDirectory, results: {} }; var _loop_1 = function (fileToLint) { var fileBasename = path.basename(fileToLint, MARKUP_FILE_EXTENSION); var fileCompileName = fileBasename.replace(/\.lint$/, ""); var fileText = fs.readFileSync(fileToLint, "utf8"); var tsVersionRequirement = parse.getTypescriptVersionRequirement(fileText); if (tsVersionRequirement) { var tsVersion = new semver.SemVer(ts.version); // remove prerelease suffix when matching to allow testing with nightly builds if (!semver.satisfies(tsVersion.major + "." + tsVersion.minor + "." + tsVersion.patch, tsVersionRequirement)) { results.results[fileToLint] = { requirement: tsVersionRequirement, skipped: true, }; return "continue"; } // remove the first line from the file before continuing var lineBreak = fileText.search(/\n/); if (lineBreak === -1) { fileText = ""; } else { fileText = fileText.substr(lineBreak + 1); } } var fileTextWithoutMarkup = parse.removeErrorMarkup(fileText); var errorsFromMarkup = parse.parseErrorsFromMarkup(fileText); var program = void 0; if (tslintConfig !== undefined && tslintConfig.linterOptions && tslintConfig.linterOptions.typeCheck) { var compilerHost = { fileExists: function () { return true; }, getCanonicalFileName: function (filename) { return filename; }, getCurrentDirectory: function () { return ""; }, getDefaultLibFileName: function () { return ts.getDefaultLibFileName(compilerOptions); }, getDirectories: function (_path) { return []; }, getNewLine: function () { return "\n"; }, getSourceFile: function (filenameToGet) { var target = compilerOptions.target === undefined ? ts.ScriptTarget.ES5 : compilerOptions.target; if (filenameToGet === ts.getDefaultLibFileName(compilerOptions)) { var fileContent = fs.readFileSync(ts.getDefaultLibFilePath(compilerOptions)).toString(); return ts.createSourceFile(filenameToGet, fileContent, target); } else if (filenameToGet === fileCompileName) { return ts.createSourceFile(fileBasename, fileTextWithoutMarkup, target, true); } else if (fs.existsSync(path.resolve(path.dirname(fileToLint), filenameToGet))) { var text = fs.readFileSync(path.resolve(path.dirname(fileToLint), filenameToGet), { encoding: "utf-8" }); return ts.createSourceFile(filenameToGet, text, target, true); } throw new Error("Couldn't get source file '" + filenameToGet + "'"); ...
n/a
function runTests(patterns, rulesDirectory) { var files = []; for (var _i = 0, patterns_1 = patterns; _i < patterns_1.length; _i++) { var pattern = patterns_1[_i]; files.push.apply(files, glob.sync(pattern + "/tslint.json")); } return files.map(function (directory) { return runTest(path.dirname(directory), rulesDirectory); }); }
...
return onComplete(1);
}
var tslintJSON = JSON.stringify(configuration_1.DEFAULT_CONFIG, undefined, " ");
fs.writeFileSync(configuration_1.CONFIG_FILENAME, tslintJSON);
return onComplete(0);
}
if (this.options.test) {
var results = test_1.runTests((this.options.files || []).map(Runner.trimSingleQuotes
), this.options.rulesDirectory);
var didAllTestsPass = test_1.consoleTestResultsHandler(results);
return onComplete(didAllTestsPass ? 0 : 1);
}
// when provided, it should point to an existing location
if (this.options.config && !fs.existsSync(this.options.config)) {
console.error("Invalid option for configuration: " + this.options.config);
return onComplete(1);
...
function arrayify(arg) { if (Array.isArray(arg)) { return arg; } else if (arg != null) { return [arg]; } else { return []; } }
...
function findRule(name, rulesDirectories) {
var camelizedName = transformName(name);
var Rule;
// first check for core rules
Rule = loadCachedRule(CORE_RULES_DIRECTORY, camelizedName);
if (Rule == null) {
// then check for rules within the first level of rulesDirectory
for (var _i = 0, _a = utils_1.arrayify(rulesDirectories); _i < _a.length; _i
++) {
var dir = _a[_i];
Rule = loadCachedRule(dir, camelizedName, true);
if (Rule != null) {
break;
}
}
}
...
function arraysAreEqual(a, b, eq) { return a === b || !!a && !!b && a.length === b.length && a.every(function (x, idx) { return eq(x, b[idx]); }); }
n/a
function camelize(stringWithHyphens) { return stringWithHyphens.replace(/-(.)/g, function (_, nextLetter) { return nextLetter.toUpperCase(); }); }
...
var CORE_FORMATTERS_DIRECTORY = path.resolve(moduleDirectory, ".", "formatters");
function findFormatter(name, formattersDirectory) {
if (typeof name === "function") {
return name;
}
else if (typeof name === "string") {
name = name.trim();
var camelizedName = utils_1.camelize(name + "Formatter");
// first check for core formatters
var Formatter = loadFormatter(CORE_FORMATTERS_DIRECTORY, camelizedName);
if (Formatter != null) {
return Formatter;
}
// then check for rules within the first level of rulesDirectory
if (formattersDirectory) {
...
function dedent(strings) { var values = []; for (var _i = 1; _i < arguments.length; _i++) { values[_i - 1] = arguments[_i]; } var fullString = strings.reduce(function (accumulator, str, i) { return accumulator + values[i - 1] + str; }); // match all leading spaces/tabs at the start of each line var match = fullString.match(/^[ \t]*(?=\S)/gm); if (!match) { // e.g. if the string is empty or all whitespace. return fullString; } // find the smallest indent, we don't want to remove all leading whitespace var indent = Math.min.apply(Math, match.map(function (el) { return el.length; })); var regexp = new RegExp("^[ \\t]{" + indent + "}", "gm"); fullString = indent > 0 ? fullString.replace(regexp, "") : fullString; return fullString; }
...
error_1.showWarningOnce(Rule.metadata.ruleName + " is deprecated. " + Rule.metadata.deprecationMessage
);
}
}
}
}
}
if (notFoundRules.length > 0) {
var warning = (_a = ["\n Could not find implementations for the following rules specified in the configuration
:\n ", "\n Try upgrading TSLint and/or ensuring that you have all necessary custom rules installed.\n If TSLint was recently upgraded, you may have old rules configured which need to be cleaned up.\n "], _a.raw = ["\n Could not find implementations for the following rules specified in the configuration:\n ", "\n Try upgrading TSLint and/or ensuring that you have all necessary custom rules installed.\n If TSLint was recently upgraded, you may have old rules configured which need to be cleaned up.\n "], utils_1.dedent(_a, notFoundRules.join("\n ")));
console.warn(warning);
}
if (notAllowedInJsRules.length > 0) {
var warning = (_b = ["\n Following rules specified in configuration couldn't be applied to .js or .jsx
files:\n ", "\n Make sure to exclude them from \"jsRules\" section of your tslint.json.\n "], _b.raw = ["\n Following rules specified in configuration couldn't be applied to .js or .jsx files:\n ", "\n Make sure to exclude them from \"jsRules\" section of your tslint.json.\n "], utils_1.dedent(_b, notAllowedInJsRules.join("\n ")));
console.warn(warning);
}
if (rules.length === 0) {
...
function escapeRegExp(re) { return re.replace(/[.+*?|^$[\]{}()\\]/g, "\\$&"); }
n/a
function flatMap(inputs, getOutputs) { var out = []; for (var _i = 0, inputs_1 = inputs; _i < inputs_1.length; _i++) { var input = inputs_1[_i]; out.push.apply(out, getOutputs(input)); } return out; }
n/a
function mapDefined(inputs, getOutput) { var out = []; for (var _i = 0, inputs_2 = inputs; _i < inputs_2.length; _i++) { var input = inputs_2[_i]; var output = getOutput(input); if (output !== undefined) { out.push(output); } } return out; }
n/a
function objectify(arg) { if (typeof arg === "object" && arg != null) { return arg; } else { return {}; } }
n/a
function stripComments(content) {
/**
* First capturing group matches double quoted string
* Second matches single quotes string
* Third matches block comments
* Fourth matches line comments
*/
var regexp = /("(?:[^\\\"]*(?:\\.)?)*")|('(?:[^\\\']*(?:\\.)?)*')|(\/\*(?:\r?\n|.)*?\*\/)|(\/{2,}.*?(?:(?:\r?\n)|$))/g;
var result = content.replace(regexp, function (match, _m1, _m2, m3, m4) {
// Only one of m1, m2, m3, m4 matches
if (m3) {
// A block comment. Replace with nothing
return "";
}
else if (m4) {
// A line comment. If it ends in \r?\n then keep it.
var length = m4.length;
if (length > 2 && m4[length - 1] === "\n") {
return m4[length - 2] === "\r" ? "\r\n" : "\n";
}
else {
return "";
}
}
else {
// We match a string
return match;
}
});
return result;
}
n/a
function WalkContext(sourceFile, ruleName, options) { this.sourceFile = sourceFile; this.ruleName = ruleName; this.options = options; this.failures = []; }
n/a
addFailure = function (start, end, failure, fix) { var fileLength = this.sourceFile.end; this.failures.push(new rule_1.RuleFailure(this.sourceFile, Math.min(start, fileLength), Math.min(end, fileLength), failure, this.ruleName, fix)); }
n/a
addFailureAt = function (start, width, failure, fix) { this.addFailure(start, start + width, failure, fix); }
n/a
addFailureAtNode = function (node, failure, fix) { this.addFailure(node.getStart(this.sourceFile), node.getEnd(), failure, fix); }
n/a
function EnableDisableRulesWalker(sourceFile, ruleOptionsList) { this.sourceFile = sourceFile; this.enableDisableRuleMap = new Map(); this.enabledRules = []; for (var _i = 0, ruleOptionsList_1 = ruleOptionsList; _i < ruleOptionsList_1.length; _i++) { var ruleOptions = ruleOptionsList_1[_i]; if (ruleOptions.ruleSeverity !== "off") { this.enabledRules.push(ruleOptions.ruleName); this.enableDisableRuleMap.set(ruleOptions.ruleName, [{ isEnabled: true, position: 0, }]); } } }
n/a
function FatalError(message, innerError) { var _this = _super.call(this, message) || this; _this.message = message; _this.innerError = innerError; _this.name = FatalError.NAME; _this.stack = new Error().stack; return _this; }
n/a
function isError(possibleError) { return possibleError != null && possibleError.message !== undefined; }
n/a
function showWarningOnce(message) { if (!shownWarnings.has(message)) { console.warn(message); shownWarnings.add(message); } }
...
notAllowedInJsRules.push(ruleName);
}
else {
var ruleSpecificList = enableDisableRules || [];
ruleOptions.disabledIntervals = buildDisabledIntervalsFromSwitches(ruleSpecificList);
rules.push(new Rule(ruleOptions));
if (Rule.metadata && Rule.metadata.deprecationMessage) {
error_1.showWarningOnce(Rule.metadata.ruleName + " is deprecated
. " + Rule.metadata.deprecationMessage);
}
}
}
}
}
if (notFoundRules.length > 0) {
var warning = (_a = ["\n Could not find implementations for the following rules specified in the configuration
:\n ", "\n Try upgrading TSLint and/or ensuring that you have all necessary custom rules installed.\n If TSLint was recently upgraded, you may have old rules configured which need to be cleaned up.\n "], _a.raw = ["\n Could not find implementations for the following rules specified in the configuration:\n ", "\n Try upgrading TSLint and/or ensuring that you have all necessary custom rules installed.\n If TSLint was recently upgraded, you may have old rules configured which need to be cleaned up.\n "], utils_1.dedent(_a, notFoundRules.join("\n ")));
...
function findFormatter(name, formattersDirectory) { if (typeof name === "function") { return name; } else if (typeof name === "string") { name = name.trim(); var camelizedName = utils_1.camelize(name + "Formatter"); // first check for core formatters var Formatter = loadFormatter(CORE_FORMATTERS_DIRECTORY, camelizedName); if (Formatter != null) { return Formatter; } // then check for rules within the first level of rulesDirectory if (formattersDirectory) { Formatter = loadFormatter(formattersDirectory, camelizedName); if (Formatter) { return Formatter; } } // else try to resolve as module return loadFormatterModule(name); } else { // If an something else is passed as a name (e.g. object) throw new Error("Name of type " + typeof name + " is not supported."); } }
n/a
function findRule(name, rulesDirectories) { var camelizedName = transformName(name); var Rule; // first check for core rules Rule = loadCachedRule(CORE_RULES_DIRECTORY, camelizedName); if (Rule == null) { // then check for rules within the first level of rulesDirectory for (var _i = 0, _a = utils_1.arrayify(rulesDirectories); _i < _a.length; _i++) { var dir = _a[_i]; Rule = loadCachedRule(dir, camelizedName, true); if (Rule != null) { break; } } } return Rule; }
n/a
function loadRules(ruleOptionsList, enableDisableRuleMap, rulesDirectories, isJs) { var rules = []; var notFoundRules = []; var notAllowedInJsRules = []; for (var _i = 0, ruleOptionsList_1 = ruleOptionsList; _i < ruleOptionsList_1.length; _i++) { var ruleOptions = ruleOptionsList_1[_i]; var ruleName = ruleOptions.ruleName; var enableDisableRules = enableDisableRuleMap.get(ruleName); if (ruleOptions.ruleSeverity !== "off" || enableDisableRuleMap) { var Rule = findRule(ruleName, rulesDirectories); if (Rule == null) { notFoundRules.push(ruleName); } else { if (isJs && Rule.metadata && Rule.metadata.typescriptOnly) { notAllowedInJsRules.push(ruleName); } else { var ruleSpecificList = enableDisableRules || []; ruleOptions.disabledIntervals = buildDisabledIntervalsFromSwitches(ruleSpecificList); rules.push(new Rule(ruleOptions)); if (Rule.metadata && Rule.metadata.deprecationMessage) { error_1.showWarningOnce(Rule.metadata.ruleName + " is deprecated. " + Rule.metadata.deprecationMessage); } } } } } if (notFoundRules.length > 0) { var warning = (_a = ["\n Could not find implementations for the following rules specified in the configuration :\n ", "\n Try upgrading TSLint and/or ensuring that you have all necessary custom rules installed.\n If TSLint was recently upgraded, you may have old rules configured which need to be cleaned up.\n "], _a.raw = ["\n Could not find implementations for the following rules specified in the configuration:\n ", "\n Try upgrading TSLint and/or ensuring that you have all necessary custom rules installed.\n If TSLint was recently upgraded, you may have old rules configured which need to be cleaned up.\n "], utils_1.dedent(_a, notFoundRules.join("\n "))); console.warn(warning); } if (notAllowedInJsRules.length > 0) { var warning = (_b = ["\n Following rules specified in configuration couldn't be applied to .js or .jsx files:\n ", "\n Make sure to exclude them from \"jsRules\" section of your tslint.json.\n "], _b.raw = ["\n Following rules specified in configuration couldn't be applied to .js or .jsx files:\n ", "\n Make sure to exclude them from \"jsRules\" section of your tslint.json.\n "], utils_1.dedent(_b, notAllowedInJsRules.join("\n "))); console.warn(warning); } if (rules.length === 0) { console.warn("No valid rules have been specified"); } return rules; var _a, _b; }
n/a
function Runner(options, outputStream) { this.options = options; this.outputStream = outputStream; }
n/a