mirror of
https://github.com/nodejs/node.git
synced 2026-11-27 17:52:27 -05:00
tools: update to ESLint 3.2.2
PR-URL: https://github.com/nodejs/node/pull/7999 Reviewed-By: Colin Ihrig <cjihrig@gmail.com> Reviewed-By: Roman Reiss <me@silverwind.io> Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Johan Bergström <bugs@bergstroem.nu>
This commit is contained in:
1 parent
4a8b8048f2
commit
60ff991c09
701 files changed
+18465
-10648
No files matched your search
@@ -705,7 +705,7 @@ cpplint:
|
||||
@$(PYTHON) tools/cpplint.py $(CPPLINT_FILES)
|
||||
@$(PYTHON) tools/check-imports.py
|
||||
|
||||
ifneq ("","$(wildcard tools/eslint/bin/eslint.js)")
|
||||
ifneq ("","$(wildcard tools/eslint/lib/eslint.js)")
|
||||
lint: jslint cpplint
|
||||
CONFLICT_RE=^>>>>>>> [0-9A-Fa-f]+|^<<<<<<< [A-Za-z]+
|
||||
lint-ci: jslint-ci cpplint
|
||||
|
||||
@@ -126,9 +126,6 @@ These folks keep the project moving and are resources for help.
|
||||
* Henry Zhu ([@hzoo](https://github.com/hzoo))
|
||||
* Marat Dulin ([@mdevils](https://github.com/mdevils))
|
||||
* Alexej Yaroshevich ([@zxqfox](https://github.com/zxqfox))
|
||||
|
||||
### Issues Team
|
||||
|
||||
* Kevin Partington ([@platinumazure](https://github.com/platinumazure))
|
||||
* Vitor Balocco ([@vitorbal](https://github.com/vitorbal))
|
||||
|
||||
@@ -169,6 +166,8 @@ ESLint follows [semantic versioning](http://semver.org). However, due to the nat
|
||||
* An existing formatter is removed.
|
||||
* Part of the public API is removed or changed in an incompatible way.
|
||||
|
||||
According to our policy, any minor update may report more errors than the previous release (ex: from a bug fix). As such, we recommend using the tilde (`~`) in `package.json` e.g. `"eslint": "~3.1.0"` to guarantee the results of your builds.
|
||||
|
||||
## Frequently Asked Questions
|
||||
|
||||
### How is ESLint different from JSHint?
|
||||
@@ -187,7 +186,10 @@ Yes. Since we are solving the same problems, ESLint and JSCS teams have decided
|
||||
|
||||
### So, should I stop using JSCS and start using ESLint?
|
||||
|
||||
Not yet. We are still working to smooth the transition. You can see our progress [here](https://github.com/eslint/eslint/milestones/JSCS%20Compatibility). We’ll announce when all of the changes necessary to support JSCS users in ESLint are complete and will start encouraging JSCS users to switch to ESLint at that time. Meanwhile, we recommend you to upgrade to JSCS 3.0 and provide feedback to the team.
|
||||
Maybe, depending on how much you need it. [JSCS has reached end of life](http://eslint.org/blog/2016/07/jscs-end-of-life), but if it is working for you then there is no reason to move yet. We are still working to smooth the transition. You can see our progress [here](https://github.com/eslint/eslint/milestones/JSCS%20Compatibility). We’ll announce when all of the changes necessary to support JSCS users in ESLint are complete and will start encouraging JSCS users to switch to ESLint at that time.
|
||||
|
||||
If you are having issues with JSCS, you can try to move to ESLint. We are focusing our time and energy on JSCS compatibility issues.
|
||||
|
||||
|
||||
### Is ESLint just linting or does it also check style?
|
||||
|
||||
|
||||
@@ -1,80 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
/**
|
||||
* @fileoverview Main CLI that is run via the eslint command.
|
||||
* @author Nicholas C. Zakas
|
||||
*/
|
||||
|
||||
"use strict";
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Helpers
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
var exitCode = 0,
|
||||
useStdIn = (process.argv.indexOf("--stdin") > -1),
|
||||
init = (process.argv.indexOf("--init") > -1),
|
||||
debug = (process.argv.indexOf("--debug") > -1);
|
||||
|
||||
// must do this initialization *before* other requires in order to work
|
||||
if (debug) {
|
||||
require("debug").enable("eslint:*,-eslint:code-path");
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Requirements
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
// now we can safely include the other modules that use debug
|
||||
var concat = require("concat-stream"),
|
||||
cli = require("../lib/cli"),
|
||||
path = require("path"),
|
||||
fs = require("fs");
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Execution
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
process.on("uncaughtException", function(err){
|
||||
// lazy load
|
||||
var lodash = require("lodash");
|
||||
|
||||
if (typeof err.messageTemplate === "string" && err.messageTemplate.length > 0) {
|
||||
var template = lodash.template(fs.readFileSync(path.resolve(__dirname, "../messages/" + err.messageTemplate + ".txt"), "utf-8"));
|
||||
|
||||
console.log("\nOops! Something went wrong! :(");
|
||||
console.log("\n" + template(err.messageData || {}));
|
||||
} else {
|
||||
console.log(err.message);
|
||||
console.log(err.stack);
|
||||
}
|
||||
|
||||
process.exit(1);
|
||||
});
|
||||
|
||||
if (useStdIn) {
|
||||
process.stdin.pipe(concat({ encoding: "string" }, function(text) {
|
||||
try {
|
||||
exitCode = cli.execute(process.argv, text);
|
||||
} catch (ex) {
|
||||
console.error(ex.message);
|
||||
console.error(ex.stack);
|
||||
exitCode = 1;
|
||||
}
|
||||
}));
|
||||
} else if (init) {
|
||||
var configInit = require("../lib/config/config-initializer");
|
||||
configInit.initializeConfig(function(err) {
|
||||
if (err) {
|
||||
exitCode = 1;
|
||||
console.error(err.message);
|
||||
console.error(err.stack);
|
||||
} else {
|
||||
exitCode = 0;
|
||||
}
|
||||
});
|
||||
} else {
|
||||
exitCode = cli.execute(process.argv);
|
||||
}
|
||||
|
||||
process.exitCode = exitCode;
|
||||
@@ -0,0 +1,35 @@
|
||||
{
|
||||
"categories": [
|
||||
{ "name": "Possible Errors", "description": "These rules relate to possible syntax or logic errors in JavaScript code:" },
|
||||
{ "name": "Best Practices", "description": "These rules relate to better ways of doing things to help you avoid problems:" },
|
||||
{ "name": "Strict Mode", "description": "These rules relate to strict mode directives:" },
|
||||
{ "name": "Variables", "description": "These rules relate to variable declarations:" },
|
||||
{ "name": "Node.js and CommonJS", "description": "These rules relate to code running in Node.js, or in browsers with CommonJS:" },
|
||||
{ "name": "Stylistic Issues", "description": "These rules relate to style guidelines, and are therefore quite subjective:" },
|
||||
{ "name": "ECMAScript 6", "description": "These rules relate to ES6, also known as ES2015:" }
|
||||
],
|
||||
"removed": {
|
||||
"name": "Removed",
|
||||
"description": "These rules from older versions of ESLint have been replaced by newer rules:",
|
||||
"rules": [
|
||||
{ "removed": "generator-star", "replacedBy": ["generator-star-spacing"] },
|
||||
{ "removed": "global-strict", "replacedBy": ["strict"] },
|
||||
{ "removed": "no-arrow-condition", "replacedBy": ["no-confusing-arrow", "no-constant-condition"] },
|
||||
{ "removed": "no-comma-dangle", "replacedBy": ["comma-dangle"] },
|
||||
{ "removed": "no-empty-class", "replacedBy": ["no-empty-character-class"] },
|
||||
{ "removed": "no-empty-label", "replacedBy": ["no-labels"] },
|
||||
{ "removed": "no-extra-strict", "replacedBy": ["strict"] },
|
||||
{ "removed": "no-reserved-keys", "replacedBy": ["quote-props"] },
|
||||
{ "removed": "no-space-before-semi", "replacedBy": ["semi-spacing"] },
|
||||
{ "removed": "no-wrap-func", "replacedBy": ["no-extra-parens"] },
|
||||
{ "removed": "space-after-function-name", "replacedBy": ["space-before-function-paren"] },
|
||||
{ "removed": "space-after-keywords", "replacedBy": ["keyword-spacing"] },
|
||||
{ "removed": "space-before-function-parentheses", "replacedBy": ["space-before-function-paren"] },
|
||||
{ "removed": "space-before-keywords", "replacedBy": ["keyword-spacing"] },
|
||||
{ "removed": "space-in-brackets", "replacedBy": ["object-curly-spacing", "array-bracket-spacing"] },
|
||||
{ "removed": "space-return-throw-case", "replacedBy": ["keyword-spacing"] },
|
||||
{ "removed": "space-unary-word-ops", "replacedBy": ["space-unary-ops"] },
|
||||
{ "removed": "spaced-line-comment", "replacedBy": ["spaced-comment"] }
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,7 @@
|
||||
// Requirements
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
var globals = require("globals");
|
||||
let globals = require("globals");
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Public Interface
|
||||
|
||||
@@ -9,16 +9,18 @@
|
||||
// Requirements
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
var fs = require("fs"),
|
||||
let fs = require("fs"),
|
||||
path = require("path");
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Helpers
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
var ruleFiles = fs.readdirSync(path.resolve(__dirname, "../lib/rules"));
|
||||
var enabledRules = ruleFiles.reduce(function(result, filename) {
|
||||
result[path.basename(filename, ".js")] = "error";
|
||||
let ruleFiles = fs.readdirSync(path.resolve(__dirname, "../lib/rules"));
|
||||
let enabledRules = ruleFiles.reduce(function(result, filename) {
|
||||
if (path.extname(filename) === ".js") {
|
||||
result[path.basename(filename, ".js")] = "error";
|
||||
}
|
||||
return result;
|
||||
}, {});
|
||||
|
||||
|
||||
@@ -99,6 +99,7 @@
|
||||
"no-spaced-func": "off",
|
||||
"no-sparse-arrays": "error",
|
||||
"no-sync": "off",
|
||||
"no-tabs": "off",
|
||||
"no-ternary": "off",
|
||||
"no-trailing-spaces": "off",
|
||||
"no-this-before-super": "error",
|
||||
@@ -174,6 +175,7 @@
|
||||
"max-params": "off",
|
||||
"max-statements": "off",
|
||||
"max-statements-per-line": "off",
|
||||
"multiline-ternary": "off",
|
||||
"new-cap": "off",
|
||||
"new-parens": "off",
|
||||
"newline-after-var": "off",
|
||||
|
||||
@@ -9,18 +9,19 @@
|
||||
// Requirements
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
var esutils = require("esutils");
|
||||
let esutils = require("esutils");
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Helpers
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
var anyFunctionPattern = /^(?:Function(?:Declaration|Expression)|ArrowFunctionExpression)$/;
|
||||
var arrayOrTypedArrayPattern = /Array$/;
|
||||
var arrayMethodPattern = /^(?:every|filter|find|findIndex|forEach|map|some)$/;
|
||||
var bindOrCallOrApplyPattern = /^(?:bind|call|apply)$/;
|
||||
var breakableTypePattern = /^(?:(?:Do)?While|For(?:In|Of)?|Switch)Statement$/;
|
||||
var thisTagPattern = /^[\s\*]*@this/m;
|
||||
let anyFunctionPattern = /^(?:Function(?:Declaration|Expression)|ArrowFunctionExpression)$/;
|
||||
let anyLoopPattern = /^(?:DoWhile|For|ForIn|ForOf|While)Statement$/;
|
||||
let arrayOrTypedArrayPattern = /Array$/;
|
||||
let arrayMethodPattern = /^(?:every|filter|find|findIndex|forEach|map|some)$/;
|
||||
let bindOrCallOrApplyPattern = /^(?:bind|call|apply)$/;
|
||||
let breakableTypePattern = /^(?:(?:Do)?While|For(?:In|Of)?|Switch)Statement$/;
|
||||
let thisTagPattern = /^[\s\*]*@this/m;
|
||||
|
||||
/**
|
||||
* Checks reference if is non initializer and writable.
|
||||
@@ -31,7 +32,7 @@ var thisTagPattern = /^[\s\*]*@this/m;
|
||||
* @private
|
||||
*/
|
||||
function isModifyingReference(reference, index, references) {
|
||||
var identifier = reference.identifier,
|
||||
let identifier = reference.identifier,
|
||||
modifyingDifferentIdentifier;
|
||||
|
||||
/*
|
||||
@@ -159,7 +160,7 @@ function isMethodWhichHasThisArg(node) {
|
||||
* @returns {boolean} Whether or not the node has a `@this` tag in its comments.
|
||||
*/
|
||||
function hasJSDocThisTag(node, sourceCode) {
|
||||
var jsdocComment = sourceCode.getJSDocComment(node);
|
||||
let jsdocComment = sourceCode.getJSDocComment(node);
|
||||
|
||||
if (jsdocComment && thisTagPattern.test(jsdocComment.value)) {
|
||||
return true;
|
||||
@@ -182,7 +183,7 @@ function hasJSDocThisTag(node, sourceCode) {
|
||||
* @private
|
||||
*/
|
||||
function isParenthesised(sourceCode, node) {
|
||||
var previousToken = sourceCode.getTokenBefore(node),
|
||||
let previousToken = sourceCode.getTokenBefore(node),
|
||||
nextToken = sourceCode.getTokenAfter(node);
|
||||
|
||||
return Boolean(previousToken && nextToken) &&
|
||||
@@ -284,7 +285,7 @@ module.exports = {
|
||||
* @returns {boolean} `true` if the node is an ESLint directive comment
|
||||
*/
|
||||
isDirectiveComment: function(node) {
|
||||
var comment = node.value.trim();
|
||||
let comment = node.value.trim();
|
||||
|
||||
return (
|
||||
node.type === "Line" && comment.indexOf("eslint-") === 0 ||
|
||||
@@ -317,10 +318,10 @@ module.exports = {
|
||||
* @returns {escope.Variable|null} A found variable or `null`.
|
||||
*/
|
||||
getVariableByName: function(initScope, name) {
|
||||
var scope = initScope;
|
||||
let scope = initScope;
|
||||
|
||||
while (scope) {
|
||||
var variable = scope.set.get(name);
|
||||
let variable = scope.set.get(name);
|
||||
|
||||
if (variable) {
|
||||
return variable;
|
||||
@@ -359,7 +360,7 @@ module.exports = {
|
||||
}
|
||||
|
||||
while (node) {
|
||||
var parent = node.parent;
|
||||
let parent = node.parent;
|
||||
|
||||
switch (parent.type) {
|
||||
|
||||
@@ -378,14 +379,15 @@ module.exports = {
|
||||
// // setup...
|
||||
// return function foo() { ... };
|
||||
// })();
|
||||
case "ReturnStatement":
|
||||
var func = getUpperFunction(parent);
|
||||
case "ReturnStatement": {
|
||||
const func = getUpperFunction(parent);
|
||||
|
||||
if (func === null || !isCallee(func)) {
|
||||
return true;
|
||||
}
|
||||
node = func.parent;
|
||||
break;
|
||||
}
|
||||
|
||||
// e.g.
|
||||
// var obj = { foo() { ... } };
|
||||
@@ -551,5 +553,37 @@ module.exports = {
|
||||
// no default
|
||||
}
|
||||
return 18;
|
||||
},
|
||||
|
||||
/**
|
||||
* Checks whether a given node is a loop node or not.
|
||||
* The following types are loop nodes:
|
||||
*
|
||||
* - DoWhileStatement
|
||||
* - ForInStatement
|
||||
* - ForOfStatement
|
||||
* - ForStatement
|
||||
* - WhileStatement
|
||||
*
|
||||
* @param {ASTNode|null} node - A node to check.
|
||||
* @returns {boolean} `true` if the node is a loop node.
|
||||
*/
|
||||
isLoop: function(node) {
|
||||
return Boolean(node && anyLoopPattern.test(node.type));
|
||||
},
|
||||
|
||||
/**
|
||||
* Checks whether a given node is a function node or not.
|
||||
* The following types are function nodes:
|
||||
*
|
||||
* - ArrowFunctionExpression
|
||||
* - FunctionDeclaration
|
||||
* - FunctionExpression
|
||||
*
|
||||
* @param {ASTNode|null} node - A node to check.
|
||||
* @returns {boolean} `true` if the node is a function node.
|
||||
*/
|
||||
isFunction: function(node) {
|
||||
return Boolean(node && anyFunctionPattern.test(node.type));
|
||||
}
|
||||
};
|
||||
@@ -15,7 +15,7 @@
|
||||
// Requirements
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
var fs = require("fs"),
|
||||
let fs = require("fs"),
|
||||
path = require("path"),
|
||||
|
||||
lodash = require("lodash"),
|
||||
@@ -44,16 +44,25 @@ var fs = require("fs"),
|
||||
/**
|
||||
* The options to configure a CLI engine with.
|
||||
* @typedef {Object} CLIEngineOptions
|
||||
* @property {boolean} allowInlineConfig Enable or disable inline configuration comments.
|
||||
* @property {boolean|Object} baseConfig Base config object. True enables recommend rules and environments.
|
||||
* @property {boolean} cache Enable result caching.
|
||||
* @property {string} cacheLocation The cache file to use instead of .eslintcache.
|
||||
* @property {string} configFile The configuration file to use.
|
||||
* @property {boolean|object} baseConfig Base config object. True enables recommend rules and environments.
|
||||
* @property {boolean} ignore False disables use of .eslintignore.
|
||||
* @property {string[]} rulePaths An array of directories to load custom rules from.
|
||||
* @property {boolean} useEslintrc False disables looking for .eslintrc
|
||||
* @property {string} cwd The value to use for the current working directory.
|
||||
* @property {string[]} envs An array of environments to load.
|
||||
* @property {string[]} globals An array of global variables to declare.
|
||||
* @property {string[]} extensions An array of file extensions to check.
|
||||
* @property {Object<string,*>} rules An object of rules to use.
|
||||
* @property {boolean} fix Execute in autofix mode.
|
||||
* @property {string[]} globals An array of global variables to declare.
|
||||
* @property {boolean} ignore False disables use of .eslintignore.
|
||||
* @property {string} ignorePath The ignore file to use instead of .eslintignore.
|
||||
* @property {string} ignorePattern A glob pattern of files to ignore.
|
||||
* @property {boolean} useEslintrc False disables looking for .eslintrc
|
||||
* @property {string} parser The name of the parser to use.
|
||||
* @property {Object} parserOptions An object of parserOption settings to use.
|
||||
* @property {string[]} plugins An array of plugins to load.
|
||||
* @property {Object<string,*>} rules An object of rules to use.
|
||||
* @property {string[]} rulePaths An array of directories to load custom rules from.
|
||||
*/
|
||||
|
||||
/**
|
||||
@@ -129,7 +138,7 @@ function calculateStatsPerRun(results) {
|
||||
*/
|
||||
function multipassFix(text, config, options) {
|
||||
|
||||
var messages = [],
|
||||
let messages = [],
|
||||
fixedResult,
|
||||
fixed = false,
|
||||
passNumber = 0,
|
||||
@@ -203,7 +212,7 @@ function processText(text, configHelper, filename, fix, allowInlineConfig) {
|
||||
// clear all existing settings for a new file
|
||||
eslint.reset();
|
||||
|
||||
var filePath,
|
||||
let filePath,
|
||||
config,
|
||||
messages,
|
||||
stats,
|
||||
@@ -227,7 +236,7 @@ function processText(text, configHelper, filename, fix, allowInlineConfig) {
|
||||
|
||||
loadedPlugins = Plugins.getAll();
|
||||
|
||||
for (var plugin in loadedPlugins) {
|
||||
for (let plugin in loadedPlugins) {
|
||||
if (loadedPlugins[plugin].processors && Object.keys(loadedPlugins[plugin].processors).indexOf(fileExtension) >= 0) {
|
||||
processor = loadedPlugins[plugin].processors[fileExtension];
|
||||
break;
|
||||
@@ -236,8 +245,8 @@ function processText(text, configHelper, filename, fix, allowInlineConfig) {
|
||||
|
||||
if (processor) {
|
||||
debug("Using processor");
|
||||
var parsedBlocks = processor.preprocess(text, filename);
|
||||
var unprocessedMessages = [];
|
||||
let parsedBlocks = processor.preprocess(text, filename);
|
||||
let unprocessedMessages = [];
|
||||
|
||||
parsedBlocks.forEach(function(block) {
|
||||
unprocessedMessages.push(eslint.verify(block, config, {
|
||||
@@ -268,7 +277,7 @@ function processText(text, configHelper, filename, fix, allowInlineConfig) {
|
||||
|
||||
stats = calculateStatsPerFile(messages);
|
||||
|
||||
var result = {
|
||||
let result = {
|
||||
filePath: filename,
|
||||
messages: messages,
|
||||
errorCount: stats.errorCount,
|
||||
@@ -293,7 +302,7 @@ function processText(text, configHelper, filename, fix, allowInlineConfig) {
|
||||
*/
|
||||
function processFile(filename, configHelper, options) {
|
||||
|
||||
var text = fs.readFileSync(path.resolve(filename), "utf8"),
|
||||
let text = fs.readFileSync(path.resolve(filename), "utf8"),
|
||||
result = processText(text, configHelper, filename, options.fix, options.allowInlineConfig);
|
||||
|
||||
return result;
|
||||
@@ -308,10 +317,10 @@ function processFile(filename, configHelper, options) {
|
||||
* @private
|
||||
*/
|
||||
function createIgnoreResult(filePath, baseDir) {
|
||||
var message;
|
||||
var isHidden = /^\./.test(path.basename(filePath));
|
||||
var isInNodeModules = baseDir && /^node_modules/.test(path.relative(baseDir, filePath));
|
||||
var isInBowerComponents = baseDir && /^bower_components/.test(path.relative(baseDir, filePath));
|
||||
let message;
|
||||
let isHidden = /^\./.test(path.basename(filePath));
|
||||
let isInNodeModules = baseDir && /^node_modules/.test(path.relative(baseDir, filePath));
|
||||
let isInBowerComponents = baseDir && /^bower_components/.test(path.relative(baseDir, filePath));
|
||||
|
||||
if (isHidden) {
|
||||
message = "File ignored by default. Use a negated ignore pattern (like \"--ignore-pattern \'!<relative/path/to/filename>\'\") to override.";
|
||||
@@ -340,7 +349,7 @@ function createIgnoreResult(filePath, baseDir) {
|
||||
|
||||
/**
|
||||
* Checks if the given message is an error message.
|
||||
* @param {object} message The message to check.
|
||||
* @param {Object} message The message to check.
|
||||
* @returns {boolean} Whether or not the message is an error message.
|
||||
* @private
|
||||
*/
|
||||
@@ -368,8 +377,8 @@ function getCacheFile(cacheFile, cwd) {
|
||||
*/
|
||||
cacheFile = path.normalize(cacheFile);
|
||||
|
||||
var resolvedCacheFile = path.resolve(cwd, cacheFile);
|
||||
var looksLikeADirectory = cacheFile[cacheFile.length - 1 ] === path.sep;
|
||||
let resolvedCacheFile = path.resolve(cwd, cacheFile);
|
||||
let looksLikeADirectory = cacheFile[cacheFile.length - 1 ] === path.sep;
|
||||
|
||||
/**
|
||||
* return the name for the cache file in case the provided parameter is a directory
|
||||
@@ -379,7 +388,7 @@ function getCacheFile(cacheFile, cwd) {
|
||||
return path.join(resolvedCacheFile, ".cache_" + hash(cwd));
|
||||
}
|
||||
|
||||
var fileStats;
|
||||
let fileStats;
|
||||
|
||||
try {
|
||||
fileStats = fs.lstatSync(resolvedCacheFile);
|
||||
@@ -446,7 +455,7 @@ function CLIEngine(options) {
|
||||
*/
|
||||
this.options = options;
|
||||
|
||||
var cacheFile = getCacheFile(this.options.cacheLocation || this.options.cacheFile, this.options.cwd);
|
||||
let cacheFile = getCacheFile(this.options.cacheLocation || this.options.cacheFile, this.options.cwd);
|
||||
|
||||
/**
|
||||
* Cache used to avoid operating on files that haven't changed since the
|
||||
@@ -458,7 +467,7 @@ function CLIEngine(options) {
|
||||
|
||||
// load in additional rules
|
||||
if (this.options.rulePaths) {
|
||||
var cwd = this.options.cwd;
|
||||
let cwd = this.options.cwd;
|
||||
|
||||
this.options.rulePaths.forEach(function(rulesdir) {
|
||||
debug("Loading rules from " + rulesdir);
|
||||
@@ -480,7 +489,7 @@ function CLIEngine(options) {
|
||||
*/
|
||||
CLIEngine.getFormatter = function(format) {
|
||||
|
||||
var formatterPath;
|
||||
let formatterPath;
|
||||
|
||||
// default is stylish
|
||||
format = format || "stylish";
|
||||
@@ -493,7 +502,7 @@ CLIEngine.getFormatter = function(format) {
|
||||
|
||||
// if there's a slash, then it's a file
|
||||
if (format.indexOf("/") > -1) {
|
||||
var cwd = this.options ? this.options.cwd : process.cwd();
|
||||
let cwd = this.options ? this.options.cwd : process.cwd();
|
||||
|
||||
formatterPath = path.resolve(cwd, format);
|
||||
} else {
|
||||
@@ -518,10 +527,10 @@ CLIEngine.getFormatter = function(format) {
|
||||
* @returns {LintResult[]} The filtered results.
|
||||
*/
|
||||
CLIEngine.getErrorResults = function(results) {
|
||||
var filtered = [];
|
||||
let filtered = [];
|
||||
|
||||
results.forEach(function(result) {
|
||||
var filteredMessages = result.messages.filter(isErrorMessage);
|
||||
let filteredMessages = result.messages.filter(isErrorMessage);
|
||||
|
||||
if (filteredMessages.length > 0) {
|
||||
filtered.push({
|
||||
@@ -579,7 +588,7 @@ CLIEngine.prototype = {
|
||||
* @returns {Object} The results for all files that were linted.
|
||||
*/
|
||||
executeOnFiles: function(patterns) {
|
||||
var results = [],
|
||||
let results = [],
|
||||
options = this.options,
|
||||
fileCache = this._fileCache,
|
||||
configHelper = new Config(options),
|
||||
@@ -594,7 +603,7 @@ CLIEngine.prototype = {
|
||||
* @returns {string} the hash of the config
|
||||
*/
|
||||
function hashOfConfigFor(filename) {
|
||||
var config = configHelper.getConfig(filename);
|
||||
let config = configHelper.getConfig(filename);
|
||||
|
||||
if (!prevConfig) {
|
||||
prevConfig = {};
|
||||
@@ -609,7 +618,7 @@ CLIEngine.prototype = {
|
||||
*/
|
||||
prevConfig.config = config;
|
||||
|
||||
var eslintVersion = pkg.version;
|
||||
let eslintVersion = pkg.version;
|
||||
|
||||
prevConfig.hash = hash(eslintVersion + "_" + stringify(config));
|
||||
}
|
||||
@@ -625,7 +634,8 @@ CLIEngine.prototype = {
|
||||
* @returns {void}
|
||||
*/
|
||||
function executeOnFile(filename, warnIgnored) {
|
||||
var hashOfConfig;
|
||||
let hashOfConfig,
|
||||
descriptor;
|
||||
|
||||
if (warnIgnored) {
|
||||
results.push(createIgnoreResult(filename, options.cwd));
|
||||
@@ -639,12 +649,12 @@ CLIEngine.prototype = {
|
||||
* with the metadata and the flag that determines if
|
||||
* the file has changed
|
||||
*/
|
||||
var descriptor = fileCache.getFileDescriptor(filename);
|
||||
var meta = descriptor.meta || {};
|
||||
descriptor = fileCache.getFileDescriptor(filename);
|
||||
let meta = descriptor.meta || {};
|
||||
|
||||
hashOfConfig = hashOfConfigFor(filename);
|
||||
|
||||
var changed = descriptor.changed || meta.hashOfConfig !== hashOfConfig;
|
||||
let changed = descriptor.changed || meta.hashOfConfig !== hashOfConfig;
|
||||
|
||||
if (!changed) {
|
||||
debug("Skipping file since hasn't changed: " + filename);
|
||||
@@ -666,7 +676,7 @@ CLIEngine.prototype = {
|
||||
|
||||
debug("Processing " + filename);
|
||||
|
||||
var res = processFile(filename, configHelper, options);
|
||||
let res = processFile(filename, configHelper, options);
|
||||
|
||||
if (options.cache) {
|
||||
|
||||
@@ -732,7 +742,7 @@ CLIEngine.prototype = {
|
||||
*/
|
||||
executeOnText: function(text, filename, warnIgnored) {
|
||||
|
||||
var results = [],
|
||||
let results = [],
|
||||
stats,
|
||||
options = this.options,
|
||||
configHelper = new Config(options),
|
||||
@@ -742,8 +752,11 @@ CLIEngine.prototype = {
|
||||
if (filename && !path.isAbsolute(filename)) {
|
||||
filename = path.resolve(options.cwd, filename);
|
||||
}
|
||||
if (filename && warnIgnored && ignoredPaths.contains(filename)) {
|
||||
results.push(createIgnoreResult(filename, options.cwd));
|
||||
|
||||
if (filename && ignoredPaths.contains(filename)) {
|
||||
if (warnIgnored) {
|
||||
results.push(createIgnoreResult(filename, options.cwd));
|
||||
}
|
||||
} else {
|
||||
results.push(processText(text, configHelper, filename, options.fix, options.allowInlineConfig));
|
||||
}
|
||||
@@ -765,7 +778,7 @@ CLIEngine.prototype = {
|
||||
* @returns {Object} A configuration object for the file.
|
||||
*/
|
||||
getConfigForFile: function(filePath) {
|
||||
var configHelper = new Config(this.options);
|
||||
let configHelper = new Config(this.options);
|
||||
|
||||
return configHelper.getConfig(filePath);
|
||||
},
|
||||
@@ -776,8 +789,8 @@ CLIEngine.prototype = {
|
||||
* @returns {boolean} Whether or not the given path is ignored.
|
||||
*/
|
||||
isPathIgnored: function(filePath) {
|
||||
var ignoredPaths;
|
||||
var resolvedPath = path.resolve(this.options.cwd, filePath);
|
||||
let ignoredPaths;
|
||||
let resolvedPath = path.resolve(this.options.cwd, filePath);
|
||||
|
||||
ignoredPaths = new IgnoredPaths(this.options);
|
||||
return ignoredPaths.contains(resolvedPath);
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
// Requirements
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
var fs = require("fs"),
|
||||
let fs = require("fs"),
|
||||
path = require("path"),
|
||||
|
||||
debug = require("debug"),
|
||||
@@ -70,7 +70,7 @@ function translateOptions(cliOptions) {
|
||||
* @private
|
||||
*/
|
||||
function printResults(engine, results, format, outputFile) {
|
||||
var formatter,
|
||||
let formatter,
|
||||
output,
|
||||
filePath;
|
||||
|
||||
@@ -116,7 +116,7 @@ function printResults(engine, results, format, outputFile) {
|
||||
* Encapsulates all CLI behavior for eslint. Makes it easier to test as well as
|
||||
* for other Node.js programs to effectively run the CLI.
|
||||
*/
|
||||
var cli = {
|
||||
let cli = {
|
||||
|
||||
/**
|
||||
* Executes the CLI based on an array of arguments that is passed in.
|
||||
@@ -126,7 +126,7 @@ var cli = {
|
||||
*/
|
||||
execute: function(args, text) {
|
||||
|
||||
var currentOptions,
|
||||
let currentOptions,
|
||||
files,
|
||||
report,
|
||||
engine,
|
||||
@@ -172,7 +172,7 @@ var cli = {
|
||||
return 1;
|
||||
}
|
||||
|
||||
var fileConfig = engine.getConfigForFile(files[0]);
|
||||
let fileConfig = engine.getConfigForFile(files[0]);
|
||||
|
||||
log.info(JSON.stringify(fileConfig, null, " "));
|
||||
return 0;
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
// Requirements
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
var assert = require("assert"),
|
||||
let assert = require("assert"),
|
||||
CodePath = require("./code-path"),
|
||||
CodePathSegment = require("./code-path-segment"),
|
||||
IdGenerator = require("./id-generator"),
|
||||
@@ -38,7 +38,7 @@ function isCaseNode(node) {
|
||||
* @returns {boolean} `true` if the node is a test of a choice statement.
|
||||
*/
|
||||
function isForkingByTrueOrFalse(node) {
|
||||
var parent = node.parent;
|
||||
let parent = node.parent;
|
||||
|
||||
switch (parent.type) {
|
||||
case "ConditionalExpression":
|
||||
@@ -83,7 +83,7 @@ function getBooleanValueIfSimpleConstant(node) {
|
||||
* @returns {boolean} `true` if the node is a reference.
|
||||
*/
|
||||
function isIdentifierReference(node) {
|
||||
var parent = node.parent;
|
||||
let parent = node.parent;
|
||||
|
||||
switch (parent.type) {
|
||||
case "LabeledStatement":
|
||||
@@ -135,12 +135,12 @@ function isIdentifierReference(node) {
|
||||
* @returns {void}
|
||||
*/
|
||||
function forwardCurrentToHead(analyzer, node) {
|
||||
var codePath = analyzer.codePath;
|
||||
var state = CodePath.getState(codePath);
|
||||
var currentSegments = state.currentSegments;
|
||||
var headSegments = state.headSegments;
|
||||
var end = Math.max(currentSegments.length, headSegments.length);
|
||||
var i, currentSegment, headSegment;
|
||||
let codePath = analyzer.codePath;
|
||||
let state = CodePath.getState(codePath);
|
||||
let currentSegments = state.currentSegments;
|
||||
let headSegments = state.headSegments;
|
||||
let end = Math.max(currentSegments.length, headSegments.length);
|
||||
let i, currentSegment, headSegment;
|
||||
|
||||
// Fires leaving events.
|
||||
for (i = 0; i < end; ++i) {
|
||||
@@ -191,11 +191,11 @@ function forwardCurrentToHead(analyzer, node) {
|
||||
* @returns {void}
|
||||
*/
|
||||
function leaveFromCurrentSegment(analyzer, node) {
|
||||
var state = CodePath.getState(analyzer.codePath);
|
||||
var currentSegments = state.currentSegments;
|
||||
let state = CodePath.getState(analyzer.codePath);
|
||||
let currentSegments = state.currentSegments;
|
||||
|
||||
for (var i = 0; i < currentSegments.length; ++i) {
|
||||
var currentSegment = currentSegments[i];
|
||||
for (let i = 0; i < currentSegments.length; ++i) {
|
||||
let currentSegment = currentSegments[i];
|
||||
|
||||
debug.dump("onCodePathSegmentEnd " + currentSegment.id);
|
||||
if (currentSegment.reachable) {
|
||||
@@ -221,9 +221,9 @@ function leaveFromCurrentSegment(analyzer, node) {
|
||||
* @returns {void}
|
||||
*/
|
||||
function preprocess(analyzer, node) {
|
||||
var codePath = analyzer.codePath;
|
||||
var state = CodePath.getState(codePath);
|
||||
var parent = node.parent;
|
||||
let codePath = analyzer.codePath;
|
||||
let state = CodePath.getState(codePath);
|
||||
let parent = node.parent;
|
||||
|
||||
switch (parent.type) {
|
||||
case "LogicalExpression":
|
||||
@@ -328,9 +328,9 @@ function preprocess(analyzer, node) {
|
||||
* @returns {void}
|
||||
*/
|
||||
function processCodePathToEnter(analyzer, node) {
|
||||
var codePath = analyzer.codePath;
|
||||
var state = codePath && CodePath.getState(codePath);
|
||||
var parent = node.parent;
|
||||
let codePath = analyzer.codePath;
|
||||
let state = codePath && CodePath.getState(codePath);
|
||||
let parent = node.parent;
|
||||
|
||||
switch (node.type) {
|
||||
case "Program":
|
||||
@@ -419,9 +419,9 @@ function processCodePathToEnter(analyzer, node) {
|
||||
* @returns {void}
|
||||
*/
|
||||
function processCodePathToExit(analyzer, node) {
|
||||
var codePath = analyzer.codePath;
|
||||
var state = CodePath.getState(codePath);
|
||||
var dontForward = false;
|
||||
let codePath = analyzer.codePath;
|
||||
let state = CodePath.getState(codePath);
|
||||
let dontForward = false;
|
||||
|
||||
switch (node.type) {
|
||||
case "IfStatement":
|
||||
@@ -536,8 +536,8 @@ function postprocess(analyzer, node) {
|
||||
case "Program":
|
||||
case "FunctionDeclaration":
|
||||
case "FunctionExpression":
|
||||
case "ArrowFunctionExpression":
|
||||
var codePath = analyzer.codePath;
|
||||
case "ArrowFunctionExpression": {
|
||||
let codePath = analyzer.codePath;
|
||||
|
||||
// Mark the current path as the final node.
|
||||
CodePath.getState(codePath).makeFinal();
|
||||
@@ -555,6 +555,7 @@ function postprocess(analyzer, node) {
|
||||
debug.dumpState(node, CodePath.getState(codePath), true);
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
default:
|
||||
break;
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
// Requirements
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
var debug = require("./debug-helpers");
|
||||
let debug = require("./debug-helpers");
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Helpers
|
||||
@@ -22,11 +22,11 @@ var debug = require("./debug-helpers");
|
||||
* @returns {CodePathSegment[]} The replaced array.
|
||||
*/
|
||||
function flattenUnusedSegments(segments) {
|
||||
var done = Object.create(null);
|
||||
var retv = [];
|
||||
let done = Object.create(null);
|
||||
let retv = [];
|
||||
|
||||
for (var i = 0; i < segments.length; ++i) {
|
||||
var segment = segments[i];
|
||||
for (let i = 0; i < segments.length; ++i) {
|
||||
let segment = segments[i];
|
||||
|
||||
// Ignores duplicated.
|
||||
if (done[segment.id]) {
|
||||
@@ -35,8 +35,8 @@ function flattenUnusedSegments(segments) {
|
||||
|
||||
// Use previous segments if unused.
|
||||
if (!segment.internal.used) {
|
||||
for (var j = 0; j < segment.allPrevSegments.length; ++j) {
|
||||
var prevSegment = segment.allPrevSegments[j];
|
||||
for (let j = 0; j < segment.allPrevSegments.length; ++j) {
|
||||
let prevSegment = segment.allPrevSegments[j];
|
||||
|
||||
if (!done[prevSegment.id]) {
|
||||
done[prevSegment.id] = true;
|
||||
@@ -175,7 +175,7 @@ CodePathSegment.newNext = function(id, allPrevSegments) {
|
||||
* @returns {CodePathSegment} The created segment.
|
||||
*/
|
||||
CodePathSegment.newUnreachable = function(id, allPrevSegments) {
|
||||
var segment = new CodePathSegment(id, flattenUnusedSegments(allPrevSegments), false);
|
||||
let segment = new CodePathSegment(id, flattenUnusedSegments(allPrevSegments), false);
|
||||
|
||||
// In `if (a) return a; foo();` case, the unreachable segment preceded by
|
||||
// the return statement is not used but must not be remove.
|
||||
@@ -211,11 +211,11 @@ CodePathSegment.markUsed = function(segment) {
|
||||
}
|
||||
segment.internal.used = true;
|
||||
|
||||
var i;
|
||||
let i;
|
||||
|
||||
if (segment.reachable) {
|
||||
for (i = 0; i < segment.allPrevSegments.length; ++i) {
|
||||
var prevSegment = segment.allPrevSegments[i];
|
||||
let prevSegment = segment.allPrevSegments[i];
|
||||
|
||||
prevSegment.allNextSegments.push(segment);
|
||||
prevSegment.nextSegments.push(segment);
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
// Requirements
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
var CodePathSegment = require("./code-path-segment"),
|
||||
let CodePathSegment = require("./code-path-segment"),
|
||||
ForkContext = require("./fork-context");
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
@@ -30,8 +30,8 @@ var CodePathSegment = require("./code-path-segment"),
|
||||
* @returns {void}
|
||||
*/
|
||||
function addToReturnedOrThrown(dest, others, all, segments) {
|
||||
for (var i = 0; i < segments.length; ++i) {
|
||||
var segment = segments[i];
|
||||
for (let i = 0; i < segments.length; ++i) {
|
||||
let segment = segments[i];
|
||||
|
||||
dest.push(segment);
|
||||
if (others.indexOf(segment) === -1) {
|
||||
@@ -52,7 +52,7 @@ function getContinueContext(state, label) {
|
||||
return state.loopContext;
|
||||
}
|
||||
|
||||
var context = state.loopContext;
|
||||
let context = state.loopContext;
|
||||
|
||||
while (context) {
|
||||
if (context.label === label) {
|
||||
@@ -73,7 +73,7 @@ function getContinueContext(state, label) {
|
||||
* @returns {LoopContext|SwitchContext} A context for a `break` statement.
|
||||
*/
|
||||
function getBreakContext(state, label) {
|
||||
var context = state.breakContext;
|
||||
let context = state.breakContext;
|
||||
|
||||
while (context) {
|
||||
if (label ? context.label === label : context.breakable) {
|
||||
@@ -93,7 +93,7 @@ function getBreakContext(state, label) {
|
||||
* @returns {TryContext|CodePathState} A context for a `return` statement.
|
||||
*/
|
||||
function getReturnContext(state) {
|
||||
var context = state.tryContext;
|
||||
let context = state.tryContext;
|
||||
|
||||
while (context) {
|
||||
if (context.hasFinalizer && context.position !== "finally") {
|
||||
@@ -112,7 +112,7 @@ function getReturnContext(state) {
|
||||
* @returns {TryContext|CodePathState} A context for a `throw` statement.
|
||||
*/
|
||||
function getThrowContext(state) {
|
||||
var context = state.tryContext;
|
||||
let context = state.tryContext;
|
||||
|
||||
while (context) {
|
||||
if (context.position === "try" ||
|
||||
@@ -149,9 +149,9 @@ function remove(xs, x) {
|
||||
* @returns {void}
|
||||
*/
|
||||
function removeConnection(prevSegments, nextSegments) {
|
||||
for (var i = 0; i < prevSegments.length; ++i) {
|
||||
var prevSegment = prevSegments[i];
|
||||
var nextSegment = nextSegments[i];
|
||||
for (let i = 0; i < prevSegments.length; ++i) {
|
||||
let prevSegment = prevSegments[i];
|
||||
let nextSegment = nextSegments[i];
|
||||
|
||||
remove(prevSegment.nextSegments, nextSegment);
|
||||
remove(prevSegment.allNextSegments, nextSegment);
|
||||
@@ -169,11 +169,11 @@ function removeConnection(prevSegments, nextSegments) {
|
||||
* @returns {void}
|
||||
*/
|
||||
function makeLooped(state, fromSegments, toSegments) {
|
||||
var end = Math.min(fromSegments.length, toSegments.length);
|
||||
let end = Math.min(fromSegments.length, toSegments.length);
|
||||
|
||||
for (var i = 0; i < end; ++i) {
|
||||
var fromSegment = fromSegments[i];
|
||||
var toSegment = toSegments[i];
|
||||
for (let i = 0; i < end; ++i) {
|
||||
let fromSegment = fromSegments[i];
|
||||
let toSegment = toSegments[i];
|
||||
|
||||
if (toSegment.reachable) {
|
||||
fromSegment.nextSegments.push(toSegment);
|
||||
@@ -225,7 +225,7 @@ function finalizeTestSegmentsOfFor(context, choiceContext, head) {
|
||||
* @constructor
|
||||
* @param {IdGenerator} idGenerator - An id generator to generate id for code
|
||||
* path segments.
|
||||
* @param {function} onLooped - A callback function to notify looping.
|
||||
* @param {Function} onLooped - A callback function to notify looping.
|
||||
*/
|
||||
function CodePathState(idGenerator, onLooped) {
|
||||
this.idGenerator = idGenerator;
|
||||
@@ -241,9 +241,9 @@ function CodePathState(idGenerator, onLooped) {
|
||||
this.initialSegment = this.forkContext.head[0];
|
||||
|
||||
// returnedSegments and thrownSegments push elements into finalSegments also.
|
||||
var final = this.finalSegments = [];
|
||||
var returned = this.returnedForkContext = [];
|
||||
var thrown = this.thrownForkContext = [];
|
||||
let final = this.finalSegments = [];
|
||||
let returned = this.returnedForkContext = [];
|
||||
let thrown = this.thrownForkContext = [];
|
||||
|
||||
returned.add = addToReturnedOrThrown.bind(null, returned, thrown, final);
|
||||
thrown.add = addToReturnedOrThrown.bind(null, thrown, returned, final);
|
||||
@@ -266,7 +266,7 @@ CodePathState.prototype = {
|
||||
* @type {ForkContext}
|
||||
*/
|
||||
get parentForkContext() {
|
||||
var current = this.forkContext;
|
||||
let current = this.forkContext;
|
||||
|
||||
return current && current.upper;
|
||||
},
|
||||
@@ -292,7 +292,7 @@ CodePathState.prototype = {
|
||||
* @returns {ForkContext} The last context.
|
||||
*/
|
||||
popForkContext: function() {
|
||||
var lastContext = this.forkContext;
|
||||
let lastContext = this.forkContext;
|
||||
|
||||
this.forkContext = lastContext.upper;
|
||||
this.forkContext.replaceHead(lastContext.makeNext(0, -1));
|
||||
@@ -370,12 +370,12 @@ CodePathState.prototype = {
|
||||
* @returns {ChoiceContext} The popped context.
|
||||
*/
|
||||
popChoiceContext: function() {
|
||||
var context = this.choiceContext;
|
||||
let context = this.choiceContext;
|
||||
|
||||
this.choiceContext = context.upper;
|
||||
|
||||
var forkContext = this.forkContext;
|
||||
var headSegments = forkContext.head;
|
||||
let forkContext = this.forkContext;
|
||||
let headSegments = forkContext.head;
|
||||
|
||||
switch (context.kind) {
|
||||
case "&&":
|
||||
@@ -396,7 +396,7 @@ CodePathState.prototype = {
|
||||
* test chunk.
|
||||
*/
|
||||
if (context.isForkingAsResult) {
|
||||
var parentContext = this.choiceContext;
|
||||
let parentContext = this.choiceContext;
|
||||
|
||||
parentContext.trueForkContext.addAll(context.trueForkContext);
|
||||
parentContext.falseForkContext.addAll(context.falseForkContext);
|
||||
@@ -443,7 +443,7 @@ CodePathState.prototype = {
|
||||
}
|
||||
|
||||
// Merges all paths.
|
||||
var prevForkContext = context.trueForkContext;
|
||||
let prevForkContext = context.trueForkContext;
|
||||
|
||||
prevForkContext.addAll(context.falseForkContext);
|
||||
forkContext.replaceHead(prevForkContext.makeNext(0, -1));
|
||||
@@ -458,8 +458,8 @@ CodePathState.prototype = {
|
||||
* @returns {void}
|
||||
*/
|
||||
makeLogicalRight: function() {
|
||||
var context = this.choiceContext;
|
||||
var forkContext = this.forkContext;
|
||||
let context = this.choiceContext;
|
||||
let forkContext = this.forkContext;
|
||||
|
||||
if (context.processed) {
|
||||
|
||||
@@ -467,7 +467,7 @@ CodePathState.prototype = {
|
||||
* This got segments already from the child choice context.
|
||||
* Creates the next path from own true/false fork context.
|
||||
*/
|
||||
var prevForkContext =
|
||||
let prevForkContext =
|
||||
context.kind === "&&" ? context.trueForkContext :
|
||||
/* kind === "||" */ context.falseForkContext;
|
||||
|
||||
@@ -502,8 +502,8 @@ CodePathState.prototype = {
|
||||
* @returns {void}
|
||||
*/
|
||||
makeIfConsequent: function() {
|
||||
var context = this.choiceContext;
|
||||
var forkContext = this.forkContext;
|
||||
let context = this.choiceContext;
|
||||
let forkContext = this.forkContext;
|
||||
|
||||
/*
|
||||
* If any result were not transferred from child contexts,
|
||||
@@ -529,8 +529,8 @@ CodePathState.prototype = {
|
||||
* @returns {void}
|
||||
*/
|
||||
makeIfAlternate: function() {
|
||||
var context = this.choiceContext;
|
||||
var forkContext = this.forkContext;
|
||||
let context = this.choiceContext;
|
||||
let forkContext = this.forkContext;
|
||||
|
||||
/*
|
||||
* The head segments are the path of the `if` block.
|
||||
@@ -583,12 +583,12 @@ CodePathState.prototype = {
|
||||
* @returns {void}
|
||||
*/
|
||||
popSwitchContext: function() {
|
||||
var context = this.switchContext;
|
||||
let context = this.switchContext;
|
||||
|
||||
this.switchContext = context.upper;
|
||||
|
||||
var forkContext = this.forkContext;
|
||||
var brokenForkContext = this.popBreakContext().brokenForkContext;
|
||||
let forkContext = this.forkContext;
|
||||
let brokenForkContext = this.popBreakContext().brokenForkContext;
|
||||
|
||||
if (context.countForks === 0) {
|
||||
|
||||
@@ -605,10 +605,10 @@ CodePathState.prototype = {
|
||||
return;
|
||||
}
|
||||
|
||||
var lastSegments = forkContext.head;
|
||||
let lastSegments = forkContext.head;
|
||||
|
||||
this.forkBypassPath();
|
||||
var lastCaseSegments = forkContext.head;
|
||||
let lastCaseSegments = forkContext.head;
|
||||
|
||||
/*
|
||||
* `brokenForkContext` is used to make the next segment.
|
||||
@@ -640,7 +640,7 @@ CodePathState.prototype = {
|
||||
}
|
||||
|
||||
// Pops the segment context stack until the entry segment.
|
||||
for (var i = 0; i < context.countForks; ++i) {
|
||||
for (let i = 0; i < context.countForks; ++i) {
|
||||
this.forkContext = this.forkContext.upper;
|
||||
}
|
||||
|
||||
@@ -659,7 +659,7 @@ CodePathState.prototype = {
|
||||
* @returns {void}
|
||||
*/
|
||||
makeSwitchCaseBody: function(isEmpty, isDefault) {
|
||||
var context = this.switchContext;
|
||||
let context = this.switchContext;
|
||||
|
||||
if (!context.hasCase) {
|
||||
return;
|
||||
@@ -670,8 +670,8 @@ CodePathState.prototype = {
|
||||
* The parent fork context has two segments.
|
||||
* Those are from the current case and the body of the previous case.
|
||||
*/
|
||||
var parentForkContext = this.forkContext;
|
||||
var forkContext = this.pushForkContext();
|
||||
let parentForkContext = this.forkContext;
|
||||
let forkContext = this.pushForkContext();
|
||||
|
||||
forkContext.add(parentForkContext.makeNext(0, -1));
|
||||
|
||||
@@ -731,7 +731,7 @@ CodePathState.prototype = {
|
||||
* @returns {void}
|
||||
*/
|
||||
popTryContext: function() {
|
||||
var context = this.tryContext;
|
||||
let context = this.tryContext;
|
||||
|
||||
this.tryContext = context.upper;
|
||||
|
||||
@@ -747,19 +747,19 @@ CodePathState.prototype = {
|
||||
* block.
|
||||
*/
|
||||
|
||||
var returned = context.returnedForkContext;
|
||||
var thrown = context.thrownForkContext;
|
||||
let returned = context.returnedForkContext;
|
||||
let thrown = context.thrownForkContext;
|
||||
|
||||
if (returned.empty && thrown.empty) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Separate head to normal paths and leaving paths.
|
||||
var headSegments = this.forkContext.head;
|
||||
let headSegments = this.forkContext.head;
|
||||
|
||||
this.forkContext = this.forkContext.upper;
|
||||
var normalSegments = headSegments.slice(0, headSegments.length / 2 | 0);
|
||||
var leavingSegments = headSegments.slice(headSegments.length / 2 | 0);
|
||||
let normalSegments = headSegments.slice(0, headSegments.length / 2 | 0);
|
||||
let leavingSegments = headSegments.slice(headSegments.length / 2 | 0);
|
||||
|
||||
// Forwards the leaving path to upper contexts.
|
||||
if (!returned.empty) {
|
||||
@@ -785,9 +785,9 @@ CodePathState.prototype = {
|
||||
* @returns {void}
|
||||
*/
|
||||
makeCatchBlock: function() {
|
||||
var context = this.tryContext;
|
||||
var forkContext = this.forkContext;
|
||||
var thrown = context.thrownForkContext;
|
||||
let context = this.tryContext;
|
||||
let forkContext = this.forkContext;
|
||||
let thrown = context.thrownForkContext;
|
||||
|
||||
// Update state.
|
||||
context.position = "catch";
|
||||
@@ -796,7 +796,7 @@ CodePathState.prototype = {
|
||||
|
||||
// Merge thrown paths.
|
||||
thrown.add(forkContext.head);
|
||||
var thrownSegments = thrown.makeNext(0, -1);
|
||||
let thrownSegments = thrown.makeNext(0, -1);
|
||||
|
||||
// Fork to a bypass and the merged thrown path.
|
||||
this.pushForkContext();
|
||||
@@ -814,11 +814,11 @@ CodePathState.prototype = {
|
||||
* @returns {void}
|
||||
*/
|
||||
makeFinallyBlock: function() {
|
||||
var context = this.tryContext;
|
||||
var forkContext = this.forkContext;
|
||||
var returned = context.returnedForkContext;
|
||||
var thrown = context.thrownForkContext;
|
||||
var headOfLeavingSegments = forkContext.head;
|
||||
let context = this.tryContext;
|
||||
let forkContext = this.forkContext;
|
||||
let returned = context.returnedForkContext;
|
||||
let thrown = context.thrownForkContext;
|
||||
let headOfLeavingSegments = forkContext.head;
|
||||
|
||||
// Update state.
|
||||
if (context.position === "catch") {
|
||||
@@ -843,11 +843,11 @@ CodePathState.prototype = {
|
||||
* Create a parallel segment from merging returned and thrown.
|
||||
* This segment will leave at the end of this finally block.
|
||||
*/
|
||||
var segments = forkContext.makeNext(-1, -1);
|
||||
var j;
|
||||
let segments = forkContext.makeNext(-1, -1);
|
||||
let j;
|
||||
|
||||
for (var i = 0; i < forkContext.count; ++i) {
|
||||
var prevSegsOfLeavingSegment = [headOfLeavingSegments[i]];
|
||||
for (let i = 0; i < forkContext.count; ++i) {
|
||||
let prevSegsOfLeavingSegment = [headOfLeavingSegments[i]];
|
||||
|
||||
for (j = 0; j < returned.segmentsList.length; ++j) {
|
||||
prevSegsOfLeavingSegment.push(returned.segmentsList[j][i]);
|
||||
@@ -872,13 +872,13 @@ CodePathState.prototype = {
|
||||
* @returns {void}
|
||||
*/
|
||||
makeFirstThrowablePathInTryBlock: function() {
|
||||
var forkContext = this.forkContext;
|
||||
let forkContext = this.forkContext;
|
||||
|
||||
if (!forkContext.reachable) {
|
||||
return;
|
||||
}
|
||||
|
||||
var context = getThrowContext(this);
|
||||
let context = getThrowContext(this);
|
||||
|
||||
if (context === this ||
|
||||
context.position !== "try" ||
|
||||
@@ -905,8 +905,8 @@ CodePathState.prototype = {
|
||||
* @returns {void}
|
||||
*/
|
||||
pushLoopContext: function(type, label) {
|
||||
var forkContext = this.forkContext;
|
||||
var breakContext = this.pushBreakContext(true, label);
|
||||
let forkContext = this.forkContext;
|
||||
let breakContext = this.pushBreakContext(true, label);
|
||||
|
||||
switch (type) {
|
||||
case "WhileStatement":
|
||||
@@ -977,13 +977,13 @@ CodePathState.prototype = {
|
||||
* @returns {void}
|
||||
*/
|
||||
popLoopContext: function() {
|
||||
var context = this.loopContext;
|
||||
let context = this.loopContext;
|
||||
|
||||
this.loopContext = context.upper;
|
||||
|
||||
var forkContext = this.forkContext;
|
||||
var brokenForkContext = this.popBreakContext().brokenForkContext;
|
||||
var choiceContext;
|
||||
let forkContext = this.forkContext;
|
||||
let brokenForkContext = this.popBreakContext().brokenForkContext;
|
||||
let choiceContext;
|
||||
|
||||
// Creates a looped path.
|
||||
switch (context.type) {
|
||||
@@ -996,7 +996,7 @@ CodePathState.prototype = {
|
||||
context.continueDestSegments);
|
||||
break;
|
||||
|
||||
case "DoWhileStatement":
|
||||
case "DoWhileStatement": {
|
||||
choiceContext = this.popChoiceContext();
|
||||
|
||||
if (!choiceContext.processed) {
|
||||
@@ -1008,15 +1008,16 @@ CodePathState.prototype = {
|
||||
}
|
||||
|
||||
// `true` paths go to looping.
|
||||
var segmentsList = choiceContext.trueForkContext.segmentsList;
|
||||
const segmentsList = choiceContext.trueForkContext.segmentsList;
|
||||
|
||||
for (var i = 0; i < segmentsList.length; ++i) {
|
||||
for (let i = 0; i < segmentsList.length; ++i) {
|
||||
makeLooped(
|
||||
this,
|
||||
segmentsList[i],
|
||||
context.entrySegments);
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case "ForInStatement":
|
||||
case "ForOfStatement":
|
||||
@@ -1047,9 +1048,9 @@ CodePathState.prototype = {
|
||||
* @returns {void}
|
||||
*/
|
||||
makeWhileTest: function(test) {
|
||||
var context = this.loopContext;
|
||||
var forkContext = this.forkContext;
|
||||
var testSegments = forkContext.makeNext(0, -1);
|
||||
let context = this.loopContext;
|
||||
let forkContext = this.forkContext;
|
||||
let testSegments = forkContext.makeNext(0, -1);
|
||||
|
||||
// Update state.
|
||||
context.test = test;
|
||||
@@ -1063,9 +1064,9 @@ CodePathState.prototype = {
|
||||
* @returns {void}
|
||||
*/
|
||||
makeWhileBody: function() {
|
||||
var context = this.loopContext;
|
||||
var choiceContext = this.choiceContext;
|
||||
var forkContext = this.forkContext;
|
||||
let context = this.loopContext;
|
||||
let choiceContext = this.choiceContext;
|
||||
let forkContext = this.forkContext;
|
||||
|
||||
if (!choiceContext.processed) {
|
||||
choiceContext.trueForkContext.add(forkContext.head);
|
||||
@@ -1085,9 +1086,9 @@ CodePathState.prototype = {
|
||||
* @returns {void}
|
||||
*/
|
||||
makeDoWhileBody: function() {
|
||||
var context = this.loopContext;
|
||||
var forkContext = this.forkContext;
|
||||
var bodySegments = forkContext.makeNext(-1, -1);
|
||||
let context = this.loopContext;
|
||||
let forkContext = this.forkContext;
|
||||
let bodySegments = forkContext.makeNext(-1, -1);
|
||||
|
||||
// Update state.
|
||||
context.entrySegments = bodySegments;
|
||||
@@ -1101,15 +1102,15 @@ CodePathState.prototype = {
|
||||
* @returns {void}
|
||||
*/
|
||||
makeDoWhileTest: function(test) {
|
||||
var context = this.loopContext;
|
||||
var forkContext = this.forkContext;
|
||||
let context = this.loopContext;
|
||||
let forkContext = this.forkContext;
|
||||
|
||||
context.test = test;
|
||||
|
||||
// Creates paths of `continue` statements.
|
||||
if (!context.continueForkContext.empty) {
|
||||
context.continueForkContext.add(forkContext.head);
|
||||
var testSegments = context.continueForkContext.makeNext(0, -1);
|
||||
let testSegments = context.continueForkContext.makeNext(0, -1);
|
||||
|
||||
forkContext.replaceHead(testSegments);
|
||||
}
|
||||
@@ -1122,10 +1123,10 @@ CodePathState.prototype = {
|
||||
* @returns {void}
|
||||
*/
|
||||
makeForTest: function(test) {
|
||||
var context = this.loopContext;
|
||||
var forkContext = this.forkContext;
|
||||
var endOfInitSegments = forkContext.head;
|
||||
var testSegments = forkContext.makeNext(-1, -1);
|
||||
let context = this.loopContext;
|
||||
let forkContext = this.forkContext;
|
||||
let endOfInitSegments = forkContext.head;
|
||||
let testSegments = forkContext.makeNext(-1, -1);
|
||||
|
||||
// Update state.
|
||||
context.test = test;
|
||||
@@ -1140,9 +1141,9 @@ CodePathState.prototype = {
|
||||
* @returns {void}
|
||||
*/
|
||||
makeForUpdate: function() {
|
||||
var context = this.loopContext;
|
||||
var choiceContext = this.choiceContext;
|
||||
var forkContext = this.forkContext;
|
||||
let context = this.loopContext;
|
||||
let choiceContext = this.choiceContext;
|
||||
let forkContext = this.forkContext;
|
||||
|
||||
// Make the next paths of the test.
|
||||
if (context.testSegments) {
|
||||
@@ -1155,7 +1156,7 @@ CodePathState.prototype = {
|
||||
}
|
||||
|
||||
// Update state.
|
||||
var updateSegments = forkContext.makeDisconnected(-1, -1);
|
||||
let updateSegments = forkContext.makeDisconnected(-1, -1);
|
||||
|
||||
context.continueDestSegments = context.updateSegments = updateSegments;
|
||||
forkContext.replaceHead(updateSegments);
|
||||
@@ -1167,9 +1168,9 @@ CodePathState.prototype = {
|
||||
* @returns {void}
|
||||
*/
|
||||
makeForBody: function() {
|
||||
var context = this.loopContext;
|
||||
var choiceContext = this.choiceContext;
|
||||
var forkContext = this.forkContext;
|
||||
let context = this.loopContext;
|
||||
let choiceContext = this.choiceContext;
|
||||
let forkContext = this.forkContext;
|
||||
|
||||
// Update state.
|
||||
if (context.updateSegments) {
|
||||
@@ -1191,7 +1192,7 @@ CodePathState.prototype = {
|
||||
context.endOfInitSegments = forkContext.head;
|
||||
}
|
||||
|
||||
var bodySegments = context.endOfTestSegments;
|
||||
let bodySegments = context.endOfTestSegments;
|
||||
|
||||
if (!bodySegments) {
|
||||
|
||||
@@ -1199,7 +1200,7 @@ CodePathState.prototype = {
|
||||
* If there is not the `test` part, the `body` path comes from the
|
||||
* `init` part and the `update` part.
|
||||
*/
|
||||
var prevForkContext = ForkContext.newEmpty(forkContext);
|
||||
let prevForkContext = ForkContext.newEmpty(forkContext);
|
||||
|
||||
prevForkContext.add(context.endOfInitSegments);
|
||||
if (context.endOfUpdateSegments) {
|
||||
@@ -1219,9 +1220,9 @@ CodePathState.prototype = {
|
||||
* @returns {void}
|
||||
*/
|
||||
makeForInOfLeft: function() {
|
||||
var context = this.loopContext;
|
||||
var forkContext = this.forkContext;
|
||||
var leftSegments = forkContext.makeDisconnected(-1, -1);
|
||||
let context = this.loopContext;
|
||||
let forkContext = this.forkContext;
|
||||
let leftSegments = forkContext.makeDisconnected(-1, -1);
|
||||
|
||||
// Update state.
|
||||
context.prevSegments = forkContext.head;
|
||||
@@ -1236,12 +1237,12 @@ CodePathState.prototype = {
|
||||
* @returns {void}
|
||||
*/
|
||||
makeForInOfRight: function() {
|
||||
var context = this.loopContext;
|
||||
var forkContext = this.forkContext;
|
||||
var temp = ForkContext.newEmpty(forkContext);
|
||||
let context = this.loopContext;
|
||||
let forkContext = this.forkContext;
|
||||
let temp = ForkContext.newEmpty(forkContext);
|
||||
|
||||
temp.add(context.prevSegments);
|
||||
var rightSegments = temp.makeNext(-1, -1);
|
||||
let rightSegments = temp.makeNext(-1, -1);
|
||||
|
||||
// Update state.
|
||||
context.endOfLeftSegments = forkContext.head;
|
||||
@@ -1255,12 +1256,12 @@ CodePathState.prototype = {
|
||||
* @returns {void}
|
||||
*/
|
||||
makeForInOfBody: function() {
|
||||
var context = this.loopContext;
|
||||
var forkContext = this.forkContext;
|
||||
var temp = ForkContext.newEmpty(forkContext);
|
||||
let context = this.loopContext;
|
||||
let forkContext = this.forkContext;
|
||||
let temp = ForkContext.newEmpty(forkContext);
|
||||
|
||||
temp.add(context.endOfLeftSegments);
|
||||
var bodySegments = temp.makeNext(-1, -1);
|
||||
let bodySegments = temp.makeNext(-1, -1);
|
||||
|
||||
// Make a path: `right` -> `left`.
|
||||
makeLooped(this, forkContext.head, context.leftSegments);
|
||||
@@ -1280,7 +1281,7 @@ CodePathState.prototype = {
|
||||
* @param {boolean} breakable - The flag to indicate it can break by
|
||||
* an unlabeled BreakStatement.
|
||||
* @param {string|null} label - The label of this context.
|
||||
* @returns {object} The new context.
|
||||
* @returns {Object} The new context.
|
||||
*/
|
||||
pushBreakContext: function(breakable, label) {
|
||||
this.breakContext = {
|
||||
@@ -1295,17 +1296,17 @@ CodePathState.prototype = {
|
||||
/**
|
||||
* Removes the top item of the break context stack.
|
||||
*
|
||||
* @returns {object} The removed context.
|
||||
* @returns {Object} The removed context.
|
||||
*/
|
||||
popBreakContext: function() {
|
||||
var context = this.breakContext;
|
||||
var forkContext = this.forkContext;
|
||||
let context = this.breakContext;
|
||||
let forkContext = this.forkContext;
|
||||
|
||||
this.breakContext = context.upper;
|
||||
|
||||
// Process this context here for other than switches and loops.
|
||||
if (!context.breakable) {
|
||||
var brokenForkContext = context.brokenForkContext;
|
||||
let brokenForkContext = context.brokenForkContext;
|
||||
|
||||
if (!brokenForkContext.empty) {
|
||||
brokenForkContext.add(forkContext.head);
|
||||
@@ -1326,13 +1327,13 @@ CodePathState.prototype = {
|
||||
* @returns {void}
|
||||
*/
|
||||
makeBreak: function(label) {
|
||||
var forkContext = this.forkContext;
|
||||
let forkContext = this.forkContext;
|
||||
|
||||
if (!forkContext.reachable) {
|
||||
return;
|
||||
}
|
||||
|
||||
var context = getBreakContext(this, label);
|
||||
let context = getBreakContext(this, label);
|
||||
|
||||
/* istanbul ignore else: foolproof (syntax error) */
|
||||
if (context) {
|
||||
@@ -1352,13 +1353,13 @@ CodePathState.prototype = {
|
||||
* @returns {void}
|
||||
*/
|
||||
makeContinue: function(label) {
|
||||
var forkContext = this.forkContext;
|
||||
let forkContext = this.forkContext;
|
||||
|
||||
if (!forkContext.reachable) {
|
||||
return;
|
||||
}
|
||||
|
||||
var context = getContinueContext(this, label);
|
||||
let context = getContinueContext(this, label);
|
||||
|
||||
/* istanbul ignore else: foolproof (syntax error) */
|
||||
if (context) {
|
||||
@@ -1387,7 +1388,7 @@ CodePathState.prototype = {
|
||||
* @returns {void}
|
||||
*/
|
||||
makeReturn: function() {
|
||||
var forkContext = this.forkContext;
|
||||
let forkContext = this.forkContext;
|
||||
|
||||
if (forkContext.reachable) {
|
||||
getReturnContext(this).returnedForkContext.add(forkContext.head);
|
||||
@@ -1404,7 +1405,7 @@ CodePathState.prototype = {
|
||||
* @returns {void}
|
||||
*/
|
||||
makeThrow: function() {
|
||||
var forkContext = this.forkContext;
|
||||
let forkContext = this.forkContext;
|
||||
|
||||
if (forkContext.reachable) {
|
||||
getThrowContext(this).thrownForkContext.add(forkContext.head);
|
||||
@@ -1417,7 +1418,7 @@ CodePathState.prototype = {
|
||||
* @returns {void}
|
||||
*/
|
||||
makeFinal: function() {
|
||||
var segments = this.currentSegments;
|
||||
let segments = this.currentSegments;
|
||||
|
||||
if (segments.length > 0 && segments[0].reachable) {
|
||||
this.returnedForkContext.add(segments);
|
||||
|
||||
@@ -9,8 +9,8 @@
|
||||
// Requirements
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
var CodePathState = require("./code-path-state");
|
||||
var IdGenerator = require("./id-generator");
|
||||
let CodePathState = require("./code-path-state");
|
||||
let IdGenerator = require("./id-generator");
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Public Interface
|
||||
@@ -22,7 +22,7 @@ var IdGenerator = require("./id-generator");
|
||||
* @constructor
|
||||
* @param {string} id - An identifier.
|
||||
* @param {CodePath|null} upper - The code path of the upper function scope.
|
||||
* @param {function} onLooped - A callback function to notify looping.
|
||||
* @param {Function} onLooped - A callback function to notify looping.
|
||||
*/
|
||||
function CodePath(id, upper, onLooped) {
|
||||
|
||||
@@ -117,10 +117,10 @@ CodePath.prototype = {
|
||||
* - `controller.skip()` - Skip the following segments in this branch.
|
||||
* - `controller.break()` - Skip all following segments.
|
||||
*
|
||||
* @param {object} [options] - Omittable.
|
||||
* @param {Object} [options] - Omittable.
|
||||
* @param {CodePathSegment} [options.first] - The first segment to traverse.
|
||||
* @param {CodePathSegment} [options.last] - The last segment to traverse.
|
||||
* @param {function} callback - A callback function.
|
||||
* @param {Function} callback - A callback function.
|
||||
* @returns {void}
|
||||
*/
|
||||
traverseSegments: function(options, callback) {
|
||||
@@ -130,18 +130,18 @@ CodePath.prototype = {
|
||||
}
|
||||
|
||||
options = options || {};
|
||||
var startSegment = options.first || this.internal.initialSegment;
|
||||
var lastSegment = options.last;
|
||||
let startSegment = options.first || this.internal.initialSegment;
|
||||
let lastSegment = options.last;
|
||||
|
||||
var item = null;
|
||||
var index = 0;
|
||||
var end = 0;
|
||||
var segment = null;
|
||||
var visited = Object.create(null);
|
||||
var stack = [[startSegment, 0]];
|
||||
var skippedSegment = null;
|
||||
var broken = false;
|
||||
var controller = {
|
||||
let item = null;
|
||||
let index = 0;
|
||||
let end = 0;
|
||||
let segment = null;
|
||||
let visited = Object.create(null);
|
||||
let stack = [[startSegment, 0]];
|
||||
let skippedSegment = null;
|
||||
let broken = false;
|
||||
let controller = {
|
||||
skip: function() {
|
||||
if (stack.length <= 1) {
|
||||
broken = true;
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
// Requirements
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
var debug = require("debug")("eslint:code-path");
|
||||
let debug = require("debug")("eslint:code-path");
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Helpers
|
||||
@@ -54,8 +54,8 @@ module.exports = {
|
||||
* @returns {void}
|
||||
*/
|
||||
dumpState: !debug.enabled ? debug : /* istanbul ignore next */ function(node, state, leaving) {
|
||||
for (var i = 0; i < state.currentSegments.length; ++i) {
|
||||
var segInternal = state.currentSegments[i].internal;
|
||||
for (let i = 0; i < state.currentSegments.length; ++i) {
|
||||
let segInternal = state.currentSegments[i].internal;
|
||||
|
||||
if (leaving) {
|
||||
segInternal.exitNodes.push(node);
|
||||
@@ -80,7 +80,7 @@ module.exports = {
|
||||
* @see http://www.webgraphviz.com
|
||||
*/
|
||||
dumpDot: !debug.enabled ? debug : /* istanbul ignore next */ function(codePath) {
|
||||
var text =
|
||||
let text =
|
||||
"\n" +
|
||||
"digraph {\n" +
|
||||
"node[shape=box,style=\"rounded,filled\",fillcolor=white];\n" +
|
||||
@@ -93,11 +93,11 @@ module.exports = {
|
||||
text += "thrown[label=\"✘\",shape=circle,width=0.3,height=0.3,fixedsize];\n";
|
||||
}
|
||||
|
||||
var traceMap = Object.create(null);
|
||||
var arrows = this.makeDotArrows(codePath, traceMap);
|
||||
let traceMap = Object.create(null);
|
||||
let arrows = this.makeDotArrows(codePath, traceMap);
|
||||
|
||||
for (var id in traceMap) { // eslint-disable-line guard-for-in
|
||||
var segment = traceMap[id];
|
||||
for (let id in traceMap) { // eslint-disable-line guard-for-in
|
||||
let segment = traceMap[id];
|
||||
|
||||
text += id + "[";
|
||||
|
||||
@@ -140,26 +140,26 @@ module.exports = {
|
||||
* The DOT code can be visialized with Graphvis.
|
||||
*
|
||||
* @param {CodePath} codePath - A code path to make DOT.
|
||||
* @param {object} traceMap - Optional. A map to check whether or not segments had been done.
|
||||
* @param {Object} traceMap - Optional. A map to check whether or not segments had been done.
|
||||
* @returns {string} A DOT code of the code path.
|
||||
*/
|
||||
makeDotArrows: function(codePath, traceMap) {
|
||||
var stack = [[codePath.initialSegment, 0]];
|
||||
var done = traceMap || Object.create(null);
|
||||
var lastId = codePath.initialSegment.id;
|
||||
var text = "initial->" + codePath.initialSegment.id;
|
||||
let stack = [[codePath.initialSegment, 0]];
|
||||
let done = traceMap || Object.create(null);
|
||||
let lastId = codePath.initialSegment.id;
|
||||
let text = "initial->" + codePath.initialSegment.id;
|
||||
|
||||
while (stack.length > 0) {
|
||||
var item = stack.pop();
|
||||
var segment = item[0];
|
||||
var index = item[1];
|
||||
let item = stack.pop();
|
||||
let segment = item[0];
|
||||
let index = item[1];
|
||||
|
||||
if (done[segment.id] && index === 0) {
|
||||
continue;
|
||||
}
|
||||
done[segment.id] = segment;
|
||||
|
||||
var nextSegment = segment.allNextSegments[index];
|
||||
let nextSegment = segment.allNextSegments[index];
|
||||
|
||||
if (!nextSegment) {
|
||||
continue;
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
// Requirements
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
var assert = require("assert"),
|
||||
let assert = require("assert"),
|
||||
CodePathSegment = require("./code-path-segment");
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
@@ -40,11 +40,11 @@ function isReachable(segment) {
|
||||
* @param {ForkContext} context - An instance.
|
||||
* @param {number} begin - The first index of the previous segments.
|
||||
* @param {number} end - The last index of the previous segments.
|
||||
* @param {function} create - A factory function of new segments.
|
||||
* @param {Function} create - A factory function of new segments.
|
||||
* @returns {CodePathSegment[]} New segments.
|
||||
*/
|
||||
function makeSegments(context, begin, end, create) {
|
||||
var list = context.segmentsList;
|
||||
let list = context.segmentsList;
|
||||
|
||||
if (begin < 0) {
|
||||
begin = list.length + begin;
|
||||
@@ -53,12 +53,12 @@ function makeSegments(context, begin, end, create) {
|
||||
end = list.length + end;
|
||||
}
|
||||
|
||||
var segments = [];
|
||||
let segments = [];
|
||||
|
||||
for (var i = 0; i < context.count; ++i) {
|
||||
var allPrevSegments = [];
|
||||
for (let i = 0; i < context.count; ++i) {
|
||||
let allPrevSegments = [];
|
||||
|
||||
for (var j = begin; j <= end; ++j) {
|
||||
for (let j = begin; j <= end; ++j) {
|
||||
allPrevSegments.push(list[j][i]);
|
||||
}
|
||||
|
||||
@@ -80,9 +80,9 @@ function makeSegments(context, begin, end, create) {
|
||||
*/
|
||||
function mergeExtraSegments(context, segments) {
|
||||
while (segments.length > context.count) {
|
||||
var merged = [];
|
||||
let merged = [];
|
||||
|
||||
for (var i = 0, length = segments.length / 2 | 0; i < length; ++i) {
|
||||
for (let i = 0, length = segments.length / 2 | 0; i < length; ++i) {
|
||||
merged.push(CodePathSegment.newNext(
|
||||
context.idGenerator.next(),
|
||||
[segments[i], segments[i + length]]
|
||||
@@ -120,7 +120,7 @@ ForkContext.prototype = {
|
||||
* @type {CodePathSegment[]}
|
||||
*/
|
||||
get head() {
|
||||
var list = this.segmentsList;
|
||||
let list = this.segmentsList;
|
||||
|
||||
return list.length === 0 ? [] : list[list.length - 1];
|
||||
},
|
||||
@@ -138,7 +138,7 @@ ForkContext.prototype = {
|
||||
* @type {boolean}
|
||||
*/
|
||||
get reachable() {
|
||||
var segments = this.head;
|
||||
let segments = this.head;
|
||||
|
||||
return segments.length > 0 && segments.some(isReachable);
|
||||
},
|
||||
@@ -214,9 +214,9 @@ ForkContext.prototype = {
|
||||
addAll: function(context) {
|
||||
assert(context.count === this.count);
|
||||
|
||||
var source = context.segmentsList;
|
||||
let source = context.segmentsList;
|
||||
|
||||
for (var i = 0; i < source.length; ++i) {
|
||||
for (let i = 0; i < source.length; ++i) {
|
||||
this.segmentsList.push(source[i]);
|
||||
}
|
||||
},
|
||||
@@ -238,7 +238,7 @@ ForkContext.prototype = {
|
||||
* @returns {ForkContext} New fork context.
|
||||
*/
|
||||
ForkContext.newRoot = function(idGenerator) {
|
||||
var context = new ForkContext(idGenerator, null, 1);
|
||||
let context = new ForkContext(idGenerator, null, 1);
|
||||
|
||||
context.add([CodePathSegment.newRoot(idGenerator.next())]);
|
||||
|
||||
|
||||
+10
-10
@@ -9,7 +9,7 @@
|
||||
// Requirements
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
var path = require("path"),
|
||||
let path = require("path"),
|
||||
ConfigOps = require("./config/config-ops"),
|
||||
ConfigFile = require("./config/config-file"),
|
||||
Plugins = require("./config/plugins"),
|
||||
@@ -23,7 +23,7 @@ var path = require("path"),
|
||||
// Constants
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
var PERSONAL_CONFIG_DIR = userHome || null;
|
||||
let PERSONAL_CONFIG_DIR = userHome || null;
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Helpers
|
||||
@@ -48,7 +48,7 @@ function isObject(item) {
|
||||
* @private
|
||||
*/
|
||||
function loadConfig(configToLoad) {
|
||||
var config = {},
|
||||
let config = {},
|
||||
filePath = "";
|
||||
|
||||
if (configToLoad) {
|
||||
@@ -75,7 +75,7 @@ function loadConfig(configToLoad) {
|
||||
* @private
|
||||
*/
|
||||
function getPersonalConfig() {
|
||||
var config,
|
||||
let config,
|
||||
filename;
|
||||
|
||||
if (PERSONAL_CONFIG_DIR) {
|
||||
@@ -106,7 +106,7 @@ function hasRules(options) {
|
||||
* @returns {Object} The local config object, or an empty object if there is no local config.
|
||||
*/
|
||||
function getLocalConfig(thisConfig, directory) {
|
||||
var found,
|
||||
let found,
|
||||
i,
|
||||
localConfig,
|
||||
localConfigFile,
|
||||
@@ -162,10 +162,10 @@ function getLocalConfig(thisConfig, directory) {
|
||||
|
||||
if (personalConfig) {
|
||||
config = ConfigOps.merge(config, personalConfig);
|
||||
} else if (!hasRules(thisConfig.options)) {
|
||||
} else if (!hasRules(thisConfig.options) && !thisConfig.options.baseConfig) {
|
||||
|
||||
// No config file, no manual configuration, and no rules, so error.
|
||||
var noConfigError = new Error("No ESLint configuration found.");
|
||||
let noConfigError = new Error("No ESLint configuration found.");
|
||||
|
||||
noConfigError.messageTemplate = "no-config-found";
|
||||
noConfigError.messageData = {
|
||||
@@ -191,7 +191,7 @@ function getLocalConfig(thisConfig, directory) {
|
||||
* @param {Object} options Options to be passed in
|
||||
*/
|
||||
function Config(options) {
|
||||
var useConfig;
|
||||
let useConfig;
|
||||
|
||||
options = options || {};
|
||||
|
||||
@@ -217,7 +217,7 @@ function Config(options) {
|
||||
* If user declares "foo", convert to "foo:false".
|
||||
*/
|
||||
this.globals = (options.globals || []).reduce(function(globals, def) {
|
||||
var parts = def.split(":");
|
||||
let parts = def.split(":");
|
||||
|
||||
globals[parts[0]] = (parts.length > 1 && parts[1] === "true");
|
||||
|
||||
@@ -244,7 +244,7 @@ function Config(options) {
|
||||
* @returns {Object} config object
|
||||
*/
|
||||
Config.prototype.getConfig = function(filePath) {
|
||||
var config,
|
||||
let config,
|
||||
userConfig,
|
||||
directory = filePath ? path.dirname(filePath) : this.options.cwd;
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
// Requirements
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
var lodash = require("lodash"),
|
||||
let lodash = require("lodash"),
|
||||
debug = require("debug"),
|
||||
eslint = require("../eslint"),
|
||||
configRule = require("./config-rule"),
|
||||
@@ -20,7 +20,7 @@ var lodash = require("lodash"),
|
||||
// Data
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
var MAX_CONFIG_COMBINATIONS = 17, // 16 combinations + 1 for severity only
|
||||
let MAX_CONFIG_COMBINATIONS = 17, // 16 combinations + 1 for severity only
|
||||
RECOMMENDED_CONFIG_NAME = "eslint:recommended";
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
@@ -89,7 +89,7 @@ Registry.prototype = {
|
||||
* @returns {void}
|
||||
*/
|
||||
populateFromCoreRules: function() {
|
||||
var rulesConfig = configRule.createCoreRuleConfigs();
|
||||
let rulesConfig = configRule.createCoreRuleConfigs();
|
||||
|
||||
this.rules = makeRegistryItems(rulesConfig);
|
||||
},
|
||||
@@ -109,7 +109,7 @@ Registry.prototype = {
|
||||
* @returns {Object[]} "rules" configurations to use for linting
|
||||
*/
|
||||
buildRuleSets: function() {
|
||||
var idx = 0,
|
||||
let idx = 0,
|
||||
ruleIds = Object.keys(this.rules),
|
||||
ruleSets = [];
|
||||
|
||||
@@ -122,7 +122,7 @@ Registry.prototype = {
|
||||
* @param {string} rule The ruleId to add.
|
||||
* @returns {void}
|
||||
*/
|
||||
var addRuleToRuleSet = function(rule) {
|
||||
let addRuleToRuleSet = function(rule) {
|
||||
|
||||
/*
|
||||
* This check ensures that there is a rule configuration and that
|
||||
@@ -130,7 +130,7 @@ Registry.prototype = {
|
||||
* If it has too many configs, we will only use the most basic of
|
||||
* the possible configurations.
|
||||
*/
|
||||
var hasFewCombos = (this.rules[rule].length <= MAX_CONFIG_COMBINATIONS);
|
||||
let hasFewCombos = (this.rules[rule].length <= MAX_CONFIG_COMBINATIONS);
|
||||
|
||||
if (this.rules[rule][idx] && (hasFewCombos || this.rules[rule][idx].specificity <= 2)) {
|
||||
|
||||
@@ -170,12 +170,12 @@ Registry.prototype = {
|
||||
* @returns {void}
|
||||
*/
|
||||
stripFailingConfigs: function() {
|
||||
var ruleIds = Object.keys(this.rules),
|
||||
let ruleIds = Object.keys(this.rules),
|
||||
newRegistry = new Registry();
|
||||
|
||||
newRegistry.rules = lodash.assign({}, this.rules);
|
||||
ruleIds.forEach(function(ruleId) {
|
||||
var errorFreeItems = newRegistry.rules[ruleId].filter(function(registryItem) {
|
||||
let errorFreeItems = newRegistry.rules[ruleId].filter(function(registryItem) {
|
||||
return (registryItem.errorCount === 0);
|
||||
});
|
||||
|
||||
@@ -195,7 +195,7 @@ Registry.prototype = {
|
||||
* @returns {void}
|
||||
*/
|
||||
stripExtraConfigs: function() {
|
||||
var ruleIds = Object.keys(this.rules),
|
||||
let ruleIds = Object.keys(this.rules),
|
||||
newRegistry = new Registry();
|
||||
|
||||
newRegistry.rules = lodash.assign({}, this.rules);
|
||||
@@ -216,11 +216,11 @@ Registry.prototype = {
|
||||
* @returns {Registry} A registry of failing rules.
|
||||
*/
|
||||
getFailingRulesRegistry: function() {
|
||||
var ruleIds = Object.keys(this.rules),
|
||||
let ruleIds = Object.keys(this.rules),
|
||||
failingRegistry = new Registry();
|
||||
|
||||
ruleIds.forEach(function(ruleId) {
|
||||
var failingConfigs = this.rules[ruleId].filter(function(registryItem) {
|
||||
let failingConfigs = this.rules[ruleId].filter(function(registryItem) {
|
||||
return (registryItem.errorCount > 0);
|
||||
});
|
||||
|
||||
@@ -239,7 +239,7 @@ Registry.prototype = {
|
||||
* @returns {Object} An eslint config with rules section populated
|
||||
*/
|
||||
createConfig: function() {
|
||||
var ruleIds = Object.keys(this.rules),
|
||||
let ruleIds = Object.keys(this.rules),
|
||||
config = {rules: {}};
|
||||
|
||||
ruleIds.forEach(function(ruleId) {
|
||||
@@ -258,7 +258,7 @@ Registry.prototype = {
|
||||
* @returns {Registry} A registry of rules
|
||||
*/
|
||||
filterBySpecificity: function(specificity) {
|
||||
var ruleIds = Object.keys(this.rules),
|
||||
let ruleIds = Object.keys(this.rules),
|
||||
newRegistry = new Registry();
|
||||
|
||||
newRegistry.rules = lodash.assign({}, this.rules);
|
||||
@@ -280,7 +280,7 @@ Registry.prototype = {
|
||||
* @returns {Registry} New registry with errorCount populated
|
||||
*/
|
||||
lintSourceCode: function(sourceCodes, config, cb) {
|
||||
var totalFilesLinting,
|
||||
let totalFilesLinting,
|
||||
lintConfig,
|
||||
ruleSets,
|
||||
ruleSetIdx,
|
||||
@@ -307,7 +307,7 @@ Registry.prototype = {
|
||||
|
||||
ruleSets.forEach(function(ruleSet) {
|
||||
lintConfig = lodash.assign({}, config, {rules: ruleSet});
|
||||
var lintResults = eslint.verify(sourceCodes[filename], lintConfig);
|
||||
let lintResults = eslint.verify(sourceCodes[filename], lintConfig);
|
||||
|
||||
lintResults.forEach(function(result) {
|
||||
|
||||
@@ -344,11 +344,11 @@ Registry.prototype = {
|
||||
* @returns {Object} config object using `"extends": "eslint:recommended"`
|
||||
*/
|
||||
function extendFromRecommended(config) {
|
||||
var newConfig = lodash.assign({}, config);
|
||||
let newConfig = lodash.assign({}, config);
|
||||
|
||||
ConfigOps.normalizeToStrings(newConfig);
|
||||
|
||||
var recRules = Object.keys(recConfig.rules).filter(function(ruleId) {
|
||||
let recRules = Object.keys(recConfig.rules).filter(function(ruleId) {
|
||||
return ConfigOps.isErrorSeverity(recConfig.rules[ruleId]);
|
||||
});
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
// Requirements
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
var debug = require("debug"),
|
||||
let debug = require("debug"),
|
||||
fs = require("fs"),
|
||||
path = require("path"),
|
||||
ConfigOps = require("./config-ops"),
|
||||
@@ -48,7 +48,7 @@ function sortByKey(a, b) {
|
||||
// Private
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
var CONFIG_FILES = [
|
||||
let CONFIG_FILES = [
|
||||
".eslintrc.js",
|
||||
".eslintrc.yaml",
|
||||
".eslintrc.yml",
|
||||
@@ -57,7 +57,7 @@ var CONFIG_FILES = [
|
||||
"package.json"
|
||||
];
|
||||
|
||||
var resolver = new ModuleResolver();
|
||||
let resolver = new ModuleResolver();
|
||||
|
||||
debug = debug("eslint:config-file");
|
||||
|
||||
@@ -94,7 +94,7 @@ function loadYAMLConfigFile(filePath) {
|
||||
debug("Loading YAML config file: " + filePath);
|
||||
|
||||
// lazy load YAML to improve performance when not used
|
||||
var yaml = require("js-yaml");
|
||||
let yaml = require("js-yaml");
|
||||
|
||||
try {
|
||||
|
||||
@@ -137,7 +137,7 @@ function loadLegacyConfigFile(filePath) {
|
||||
debug("Loading config file: " + filePath);
|
||||
|
||||
// lazy load YAML to improve performance when not used
|
||||
var yaml = require("js-yaml");
|
||||
let yaml = require("js-yaml");
|
||||
|
||||
try {
|
||||
return yaml.safeLoad(stripComments(readFile(filePath))) || /* istanbul ignore next */ {};
|
||||
@@ -192,7 +192,7 @@ function loadPackageJSONConfigFile(filePath) {
|
||||
* @private
|
||||
*/
|
||||
function loadConfigFile(file) {
|
||||
var config,
|
||||
let config,
|
||||
filePath = file.filePath;
|
||||
|
||||
switch (path.extname(filePath)) {
|
||||
@@ -236,7 +236,7 @@ function loadConfigFile(file) {
|
||||
function writeJSONConfigFile(config, filePath) {
|
||||
debug("Writing JSON config file: " + filePath);
|
||||
|
||||
var content = stringify(config, {cmp: sortByKey, space: 4});
|
||||
let content = stringify(config, {cmp: sortByKey, space: 4});
|
||||
|
||||
fs.writeFileSync(filePath, content, "utf8");
|
||||
}
|
||||
@@ -252,9 +252,9 @@ function writeYAMLConfigFile(config, filePath) {
|
||||
debug("Writing YAML config file: " + filePath);
|
||||
|
||||
// lazy load YAML to improve performance when not used
|
||||
var yaml = require("js-yaml");
|
||||
let yaml = require("js-yaml");
|
||||
|
||||
var content = yaml.safeDump(config, {sortKeys: true});
|
||||
let content = yaml.safeDump(config, {sortKeys: true});
|
||||
|
||||
fs.writeFileSync(filePath, content, "utf8");
|
||||
}
|
||||
@@ -269,7 +269,7 @@ function writeYAMLConfigFile(config, filePath) {
|
||||
function writeJSConfigFile(config, filePath) {
|
||||
debug("Writing JS config file: " + filePath);
|
||||
|
||||
var content = "module.exports = " + stringify(config, {cmp: sortByKey, space: 4}) + ";";
|
||||
let content = "module.exports = " + stringify(config, {cmp: sortByKey, space: 4}) + ";";
|
||||
|
||||
fs.writeFileSync(filePath, content, "utf8");
|
||||
}
|
||||
@@ -313,7 +313,7 @@ function write(config, filePath) {
|
||||
function getBaseDir(configFilePath) {
|
||||
|
||||
// calculates the path of the project including ESLint as dependency
|
||||
var projectPath = path.resolve(__dirname, "../../../");
|
||||
let projectPath = path.resolve(__dirname, "../../../");
|
||||
|
||||
if (configFilePath && pathIsInside(configFilePath, projectPath)) {
|
||||
|
||||
@@ -336,7 +336,7 @@ function getBaseDir(configFilePath) {
|
||||
* @private
|
||||
*/
|
||||
function getLookupPath(configFilePath) {
|
||||
var basedir = getBaseDir(configFilePath);
|
||||
let basedir = getBaseDir(configFilePath);
|
||||
|
||||
return path.join(basedir, "node_modules");
|
||||
}
|
||||
@@ -352,7 +352,7 @@ function getLookupPath(configFilePath) {
|
||||
* @private
|
||||
*/
|
||||
function applyExtends(config, filePath, relativeTo) {
|
||||
var configExtends = config.extends;
|
||||
let configExtends = config.extends;
|
||||
|
||||
// normalize into an array for easier handling
|
||||
if (!Array.isArray(config.extends)) {
|
||||
@@ -431,7 +431,7 @@ function normalizePackageName(name, prefix) {
|
||||
* it's a scoped package
|
||||
* package name is "eslint-config", or just a username
|
||||
*/
|
||||
var scopedPackageShortcutRegex = new RegExp("^(@[^\/]+)(?:\/(?:" + prefix + ")?)?$"),
|
||||
let scopedPackageShortcutRegex = new RegExp("^(@[^\/]+)(?:\/(?:" + prefix + ")?)?$"),
|
||||
scopedPackageNameRegex = new RegExp("^" + prefix + "(-|$)");
|
||||
|
||||
if (scopedPackageShortcutRegex.test(name)) {
|
||||
@@ -463,11 +463,11 @@ function resolve(filePath, relativeTo) {
|
||||
if (isFilePath(filePath)) {
|
||||
return { filePath: path.resolve(relativeTo || "", filePath) };
|
||||
} else {
|
||||
var normalizedPackageName;
|
||||
let normalizedPackageName;
|
||||
|
||||
if (filePath.indexOf("plugin:") === 0) {
|
||||
var packagePath = filePath.substr(7, filePath.lastIndexOf("/") - 7);
|
||||
var configName = filePath.substr(filePath.lastIndexOf("/") + 1, filePath.length - filePath.lastIndexOf("/") - 1);
|
||||
let packagePath = filePath.substr(7, filePath.lastIndexOf("/") - 7);
|
||||
let configName = filePath.substr(filePath.lastIndexOf("/") + 1, filePath.length - filePath.lastIndexOf("/") - 1);
|
||||
|
||||
normalizedPackageName = normalizePackageName(packagePath, "eslint-plugin");
|
||||
debug("Attempting to resolve " + normalizedPackageName);
|
||||
@@ -493,7 +493,7 @@ function resolve(filePath, relativeTo) {
|
||||
* @private
|
||||
*/
|
||||
function load(filePath, applyEnvironments, relativeTo) {
|
||||
var resolvedPath = resolve(filePath, relativeTo),
|
||||
let resolvedPath = resolve(filePath, relativeTo),
|
||||
dirname = path.dirname(resolvedPath.filePath),
|
||||
lookupPath = getLookupPath(dirname),
|
||||
config = loadConfigFile(resolvedPath);
|
||||
@@ -565,9 +565,9 @@ module.exports = {
|
||||
*/
|
||||
getFilenameForDirectory: function(directory) {
|
||||
|
||||
var filename;
|
||||
let filename;
|
||||
|
||||
for (var i = 0, len = CONFIG_FILES.length; i < len; i++) {
|
||||
for (let i = 0, len = CONFIG_FILES.length; i < len; i++) {
|
||||
filename = path.join(directory, CONFIG_FILES[i]);
|
||||
if (fs.existsSync(filename)) {
|
||||
return filename;
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
// Requirements
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
var util = require("util"),
|
||||
let util = require("util"),
|
||||
debug = require("debug"),
|
||||
lodash = require("lodash"),
|
||||
inquirer = require("inquirer"),
|
||||
@@ -38,7 +38,7 @@ debug = debug("eslint:config-initializer");
|
||||
function writeFile(config, format) {
|
||||
|
||||
// default is .js
|
||||
var extname = ".js";
|
||||
let extname = ".js";
|
||||
|
||||
if (format === "YAML") {
|
||||
extname = ".yml";
|
||||
@@ -60,7 +60,7 @@ function writeFile(config, format) {
|
||||
* @returns {void}
|
||||
*/
|
||||
function installModules(config) {
|
||||
var modules = [],
|
||||
let modules = [],
|
||||
installStatus,
|
||||
modulesToInstall;
|
||||
|
||||
@@ -86,7 +86,7 @@ function installModules(config) {
|
||||
|
||||
// Install packages which aren't already installed
|
||||
modulesToInstall = Object.keys(installStatus).filter(function(module) {
|
||||
var notInstalled = installStatus[module] === false;
|
||||
let notInstalled = installStatus[module] === false;
|
||||
|
||||
if (module === "eslint" && notInstalled) {
|
||||
log.info("Local ESLint installation not found.");
|
||||
@@ -113,10 +113,10 @@ function installModules(config) {
|
||||
* @returns {Object} config object with configured rules
|
||||
*/
|
||||
function configureRules(answers, config) {
|
||||
var BAR_TOTAL = 20,
|
||||
let BAR_TOTAL = 20,
|
||||
BAR_SOURCE_CODE_TOTAL = 4;
|
||||
|
||||
var newConfig = lodash.assign({}, config),
|
||||
let newConfig = lodash.assign({}, config),
|
||||
bar,
|
||||
patterns,
|
||||
sourceCodes,
|
||||
@@ -163,7 +163,7 @@ function configureRules(answers, config) {
|
||||
debug("\nRegistry: " + util.inspect(registry.rules, {depth: null}));
|
||||
|
||||
// Create a list of recommended rules, because we don't want to disable them
|
||||
var recRules = Object.keys(recConfig.rules).filter(function(ruleId) {
|
||||
let recRules = Object.keys(recConfig.rules).filter(function(ruleId) {
|
||||
return ConfigOps.isErrorSeverity(recConfig.rules[ruleId]);
|
||||
});
|
||||
|
||||
@@ -202,12 +202,12 @@ function configureRules(answers, config) {
|
||||
bar.update(BAR_TOTAL);
|
||||
|
||||
// Log out some stats to let the user know what happened
|
||||
var finalRuleIds = Object.keys(newConfig.rules),
|
||||
let finalRuleIds = Object.keys(newConfig.rules),
|
||||
totalRules = finalRuleIds.length;
|
||||
var enabledRules = finalRuleIds.filter(function(ruleId) {
|
||||
let enabledRules = finalRuleIds.filter(function(ruleId) {
|
||||
return (newConfig.rules[ruleId] !== 0);
|
||||
}).length;
|
||||
var resultMessage = [
|
||||
let resultMessage = [
|
||||
"\nEnabled " + enabledRules + " out of " + totalRules,
|
||||
"rules based on " + fileQty,
|
||||
"file" + ((fileQty === 1) ? "." : "s.")
|
||||
@@ -225,7 +225,7 @@ function configureRules(answers, config) {
|
||||
* @returns {Object} config object
|
||||
*/
|
||||
function processAnswers(answers) {
|
||||
var config = {rules: {}, env: {}};
|
||||
let config = {rules: {}, env: {}};
|
||||
|
||||
if (answers.es6) {
|
||||
config.env.es6 = true;
|
||||
@@ -275,10 +275,10 @@ function processAnswers(answers) {
|
||||
* @returns {Object} config object
|
||||
*/
|
||||
function getConfigForStyleGuide(guide) {
|
||||
var guides = {
|
||||
let guides = {
|
||||
google: {extends: "google"},
|
||||
airbnb: {extends: "airbnb", plugins: ["react"]},
|
||||
standard: {extends: "standard", plugins: ["standard"]}
|
||||
standard: {extends: "standard", plugins: ["standard", "promise"]}
|
||||
};
|
||||
|
||||
if (!guides[guide]) {
|
||||
@@ -293,11 +293,11 @@ function getConfigForStyleGuide(guide) {
|
||||
/* istanbul ignore next: no need to test inquirer*/
|
||||
/**
|
||||
* Ask use a few questions on command prompt
|
||||
* @param {function} callback callback function when file has been written
|
||||
* @param {Function} callback callback function when file has been written
|
||||
* @returns {void}
|
||||
*/
|
||||
function promptUser(callback) {
|
||||
var config;
|
||||
let config;
|
||||
|
||||
inquirer.prompt([
|
||||
{
|
||||
@@ -419,7 +419,7 @@ function promptUser(callback) {
|
||||
// early exit if you are using automatic style generation
|
||||
if (earlyAnswers.source === "auto") {
|
||||
try {
|
||||
var combinedAnswers = lodash.assign({}, earlyAnswers, secondAnswers);
|
||||
let combinedAnswers = lodash.assign({}, earlyAnswers, secondAnswers);
|
||||
|
||||
config = processAnswers(combinedAnswers);
|
||||
installModules(config);
|
||||
@@ -469,7 +469,7 @@ function promptUser(callback) {
|
||||
}
|
||||
], function(answers) {
|
||||
try {
|
||||
var totalAnswers = lodash.assign({}, earlyAnswers, secondAnswers, answers);
|
||||
let totalAnswers = lodash.assign({}, earlyAnswers, secondAnswers, answers);
|
||||
|
||||
config = processAnswers(totalAnswers);
|
||||
installModules(config);
|
||||
@@ -488,7 +488,7 @@ function promptUser(callback) {
|
||||
// Public Interface
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
var init = {
|
||||
let init = {
|
||||
getConfigForStyleGuide: getConfigForStyleGuide,
|
||||
processAnswers: processAnswers,
|
||||
initializeConfig: /* istanbul ignore next */ function(callback) {
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
// Requirements
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
var lodash = require("lodash"),
|
||||
let lodash = require("lodash"),
|
||||
debug = require("debug"),
|
||||
Environments = require("./environments");
|
||||
|
||||
@@ -19,7 +19,7 @@ var lodash = require("lodash"),
|
||||
|
||||
debug = debug("eslint:config-ops");
|
||||
|
||||
var RULE_SEVERITY_STRINGS = ["off", "warn", "error"],
|
||||
let RULE_SEVERITY_STRINGS = ["off", "warn", "error"],
|
||||
RULE_SEVERITY = RULE_SEVERITY_STRINGS.reduce(function(map, value, index) {
|
||||
map[value] = index;
|
||||
return map;
|
||||
@@ -53,7 +53,7 @@ module.exports = {
|
||||
*/
|
||||
createEnvironmentConfig: function(env) {
|
||||
|
||||
var envConfig = this.createEmptyConfig();
|
||||
let envConfig = this.createEmptyConfig();
|
||||
|
||||
if (env) {
|
||||
|
||||
@@ -62,7 +62,7 @@ module.exports = {
|
||||
Object.keys(env).filter(function(name) {
|
||||
return env[name];
|
||||
}).forEach(function(name) {
|
||||
var environment = Environments.get(name);
|
||||
let environment = Environments.get(name);
|
||||
|
||||
if (environment) {
|
||||
debug("Creating config for environment " + name);
|
||||
@@ -134,8 +134,8 @@ module.exports = {
|
||||
* (https://github.com/KyleAMathews/deepmerge)
|
||||
* and modified to meet our needs.
|
||||
*/
|
||||
var array = Array.isArray(src) || Array.isArray(target);
|
||||
var dst = array && [] || {};
|
||||
let array = Array.isArray(src) || Array.isArray(target);
|
||||
let dst = array && [] || {};
|
||||
|
||||
combine = !!combine;
|
||||
isRule = !!isRule;
|
||||
@@ -202,7 +202,7 @@ module.exports = {
|
||||
|
||||
if (config.rules) {
|
||||
Object.keys(config.rules).forEach(function(ruleId) {
|
||||
var ruleConfig = config.rules[ruleId];
|
||||
let ruleConfig = config.rules[ruleId];
|
||||
|
||||
if (typeof ruleConfig === "string") {
|
||||
config.rules[ruleId] = RULE_SEVERITY[ruleConfig.toLowerCase()] || 0;
|
||||
@@ -224,7 +224,7 @@ module.exports = {
|
||||
|
||||
if (config.rules) {
|
||||
Object.keys(config.rules).forEach(function(ruleId) {
|
||||
var ruleConfig = config.rules[ruleId];
|
||||
let ruleConfig = config.rules[ruleId];
|
||||
|
||||
if (typeof ruleConfig === "number") {
|
||||
config.rules[ruleId] = RULE_SEVERITY_STRINGS[ruleConfig] || RULE_SEVERITY_STRINGS[0];
|
||||
@@ -242,7 +242,7 @@ module.exports = {
|
||||
*/
|
||||
isErrorSeverity: function(ruleConfig) {
|
||||
|
||||
var severity = Array.isArray(ruleConfig) ? ruleConfig[0] : ruleConfig;
|
||||
let severity = Array.isArray(ruleConfig) ? ruleConfig[0] : ruleConfig;
|
||||
|
||||
if (typeof severity === "string") {
|
||||
severity = RULE_SEVERITY[severity.toLowerCase()] || 0;
|
||||
@@ -257,7 +257,7 @@ module.exports = {
|
||||
* @returns {boolean} `true` if the configuration has valid severity.
|
||||
*/
|
||||
isValidSeverity: function(ruleConfig) {
|
||||
var severity = Array.isArray(ruleConfig) ? ruleConfig[0] : ruleConfig;
|
||||
let severity = Array.isArray(ruleConfig) ? ruleConfig[0] : ruleConfig;
|
||||
|
||||
if (typeof severity === "string") {
|
||||
severity = severity.toLowerCase();
|
||||
@@ -267,7 +267,7 @@ module.exports = {
|
||||
|
||||
/**
|
||||
* Checks whether every rule of a given config has valid severity or not.
|
||||
* @param {object} config - The configuration for rules.
|
||||
* @param {Object} config - The configuration for rules.
|
||||
* @returns {boolean} `true` if the configuration has valid severity.
|
||||
*/
|
||||
isEverySeverityValid: function(config) {
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
// Requirements
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
var rules = require("../rules"),
|
||||
let rules = require("../rules"),
|
||||
loadRules = require("../load-rules");
|
||||
|
||||
|
||||
@@ -41,7 +41,7 @@ function explodeArray(xs) {
|
||||
* @returns {array} A mixture of the elements of the first and second arrays.
|
||||
*/
|
||||
function combineArrays(arr1, arr2) {
|
||||
var res = [];
|
||||
let res = [];
|
||||
|
||||
if (arr1.length === 0) {
|
||||
return explodeArray(arr2);
|
||||
@@ -78,8 +78,8 @@ function combineArrays(arr1, arr2) {
|
||||
* @returns {Array[]} Array of arrays of objects grouped by property
|
||||
*/
|
||||
function groupByProperty(objects) {
|
||||
var groupedObj = objects.reduce(function(accumulator, obj) {
|
||||
var prop = Object.keys(obj)[0];
|
||||
let groupedObj = objects.reduce(function(accumulator, obj) {
|
||||
let prop = Object.keys(obj)[0];
|
||||
|
||||
accumulator[prop] = accumulator[prop] ? accumulator[prop].concat(obj) : [obj];
|
||||
return accumulator;
|
||||
@@ -144,7 +144,7 @@ function groupByProperty(objects) {
|
||||
* @returns {Object[]} Combined objects for each combination of input properties and values
|
||||
*/
|
||||
function combinePropertyObjects(objArr1, objArr2) {
|
||||
var res = [];
|
||||
let res = [];
|
||||
|
||||
if (objArr1.length === 0) {
|
||||
return objArr2;
|
||||
@@ -154,9 +154,9 @@ function combinePropertyObjects(objArr1, objArr2) {
|
||||
}
|
||||
objArr1.forEach(function(obj1) {
|
||||
objArr2.forEach(function(obj2) {
|
||||
var combinedObj = {};
|
||||
var obj1Props = Object.keys(obj1);
|
||||
var obj2Props = Object.keys(obj2);
|
||||
let combinedObj = {};
|
||||
let obj1Props = Object.keys(obj1);
|
||||
let obj2Props = Object.keys(obj2);
|
||||
|
||||
obj1Props.forEach(function(prop1) {
|
||||
combinedObj[prop1] = obj1[prop1];
|
||||
@@ -229,12 +229,12 @@ RuleConfigSet.prototype = {
|
||||
* @returns {void}
|
||||
*/
|
||||
addObject: function(obj) {
|
||||
var objectConfigSet = {
|
||||
let objectConfigSet = {
|
||||
objectConfigs: [],
|
||||
add: function(property, values) {
|
||||
var optionObj;
|
||||
let optionObj;
|
||||
|
||||
for (var idx = 0; idx < values.length; idx++) {
|
||||
for (let idx = 0; idx < values.length; idx++) {
|
||||
optionObj = {};
|
||||
optionObj[property] = values[idx];
|
||||
this.objectConfigs.push(optionObj);
|
||||
@@ -274,7 +274,7 @@ RuleConfigSet.prototype = {
|
||||
* @returns {array[]} Valid rule configurations
|
||||
*/
|
||||
function generateConfigsFromSchema(schema) {
|
||||
var configSet = new RuleConfigSet();
|
||||
let configSet = new RuleConfigSet();
|
||||
|
||||
if (Array.isArray(schema)) {
|
||||
schema.forEach(function(opt) {
|
||||
@@ -301,11 +301,11 @@ function generateConfigsFromSchema(schema) {
|
||||
* @returns {rulesConfig} Hash of rule names and arrays of possible configurations
|
||||
*/
|
||||
function createCoreRuleConfigs() {
|
||||
var ruleList = loadRules();
|
||||
let ruleList = loadRules();
|
||||
|
||||
return Object.keys(ruleList).reduce(function(accumulator, id) {
|
||||
var rule = rules.get(id);
|
||||
var schema = (typeof rule === "function") ? rule.schema : rule.meta.schema;
|
||||
let rule = rules.get(id);
|
||||
let schema = (typeof rule === "function") ? rule.schema : rule.meta.schema;
|
||||
|
||||
accumulator[id] = generateConfigsFromSchema(schema);
|
||||
return accumulator;
|
||||
|
||||
@@ -9,12 +9,12 @@
|
||||
// Requirements
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
var rules = require("../rules"),
|
||||
let rules = require("../rules"),
|
||||
Environments = require("./environments"),
|
||||
schemaValidator = require("is-my-json-valid"),
|
||||
util = require("util");
|
||||
|
||||
var validators = {
|
||||
let validators = {
|
||||
rules: Object.create(null)
|
||||
};
|
||||
|
||||
@@ -25,10 +25,10 @@ var validators = {
|
||||
/**
|
||||
* Gets a complete options schema for a rule.
|
||||
* @param {string} id The rule's unique name.
|
||||
* @returns {object} JSON Schema for the rule's options.
|
||||
* @returns {Object} JSON Schema for the rule's options.
|
||||
*/
|
||||
function getRuleOptionsSchema(id) {
|
||||
var rule = rules.get(id),
|
||||
let rule = rules.get(id),
|
||||
schema = rule && rule.schema || rule && rule.meta && rule.meta.schema;
|
||||
|
||||
// Given a tuple of schemas, insert warning level at the beginning
|
||||
@@ -61,7 +61,7 @@ function getRuleOptionsSchema(id) {
|
||||
* @returns {void}
|
||||
*/
|
||||
function validateRuleOptions(id, options, source) {
|
||||
var validateRule = validators.rules[id],
|
||||
let validateRule = validators.rules[id],
|
||||
message,
|
||||
severity,
|
||||
localOptions,
|
||||
@@ -119,7 +119,7 @@ function validateRuleOptions(id, options, source) {
|
||||
|
||||
/**
|
||||
* Validates an environment object
|
||||
* @param {object} environment The environment config object to validate.
|
||||
* @param {Object} environment The environment config object to validate.
|
||||
* @param {string} source The location to report with any errors.
|
||||
* @returns {void}
|
||||
*/
|
||||
@@ -137,7 +137,7 @@ function validateEnvironment(environment, source) {
|
||||
if (typeof environment === "object") {
|
||||
Object.keys(environment).forEach(function(env) {
|
||||
if (!Environments.get(env)) {
|
||||
var message = [
|
||||
let message = [
|
||||
source, ":\n",
|
||||
"\tEnvironment key \"", env, "\" is unknown\n"
|
||||
];
|
||||
@@ -152,7 +152,7 @@ function validateEnvironment(environment, source) {
|
||||
|
||||
/**
|
||||
* Validates an entire config object.
|
||||
* @param {object} config The config object to validate.
|
||||
* @param {Object} config The config object to validate.
|
||||
* @param {string} source The location to report with any errors.
|
||||
* @returns {void}
|
||||
*/
|
||||
|
||||
@@ -8,13 +8,13 @@
|
||||
// Requirements
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
var envs = require("../../conf/environments");
|
||||
let envs = require("../../conf/environments");
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Private
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
var environments = Object.create(null);
|
||||
let environments = new Map();
|
||||
|
||||
/**
|
||||
* Loads the default environments.
|
||||
@@ -23,7 +23,7 @@ var environments = Object.create(null);
|
||||
*/
|
||||
function load() {
|
||||
Object.keys(envs).forEach(function(envName) {
|
||||
environments[envName] = envs[envName];
|
||||
environments.set(envName, envs[envName]);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -36,15 +36,15 @@ load();
|
||||
|
||||
module.exports = {
|
||||
|
||||
load: load,
|
||||
load,
|
||||
|
||||
/**
|
||||
* Gets the environment with the given name.
|
||||
* @param {string} name The name of the environment to retrieve.
|
||||
* @returns {Object?} The environment object or null if not found.
|
||||
*/
|
||||
get: function(name) {
|
||||
return environments[name] || null;
|
||||
get(name) {
|
||||
return environments.get(name) || null;
|
||||
},
|
||||
|
||||
/**
|
||||
@@ -53,8 +53,8 @@ module.exports = {
|
||||
* @param {Object} env The environment settings.
|
||||
* @returns {void}
|
||||
*/
|
||||
define: function(name, env) {
|
||||
environments[name] = env;
|
||||
define(name, env) {
|
||||
environments.set(name, env);
|
||||
},
|
||||
|
||||
/**
|
||||
@@ -63,7 +63,7 @@ module.exports = {
|
||||
* @param {string} pluginName The name of the plugin.
|
||||
* @returns {void}
|
||||
*/
|
||||
importPlugin: function(plugin, pluginName) {
|
||||
importPlugin(plugin, pluginName) {
|
||||
if (plugin.environments) {
|
||||
Object.keys(plugin.environments).forEach(function(envName) {
|
||||
this.define(pluginName + "/" + envName, plugin.environments[envName]);
|
||||
@@ -75,8 +75,8 @@ module.exports = {
|
||||
* Resets all environments. Only use for tests!
|
||||
* @returns {void}
|
||||
*/
|
||||
testReset: function() {
|
||||
environments = Object.create(null);
|
||||
testReset() {
|
||||
environments = new Map();
|
||||
load();
|
||||
}
|
||||
};
|
||||
@@ -8,7 +8,7 @@
|
||||
// Requirements
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
var debug = require("debug"),
|
||||
let debug = require("debug"),
|
||||
Environments = require("./environments"),
|
||||
rules = require("../rules");
|
||||
|
||||
@@ -18,9 +18,9 @@ var debug = require("debug"),
|
||||
|
||||
debug = debug("eslint:plugins");
|
||||
|
||||
var plugins = Object.create(null);
|
||||
let plugins = Object.create(null);
|
||||
|
||||
var PLUGIN_NAME_PREFIX = "eslint-plugin-",
|
||||
let PLUGIN_NAME_PREFIX = "eslint-plugin-",
|
||||
NAMESPACE_REGEX = /^@.*\//i;
|
||||
|
||||
/**
|
||||
@@ -67,7 +67,7 @@ module.exports = {
|
||||
* @returns {void}
|
||||
*/
|
||||
define: function(pluginName, plugin) {
|
||||
var pluginNameWithoutNamespace = removeNamespace(pluginName),
|
||||
let pluginNameWithoutNamespace = removeNamespace(pluginName),
|
||||
pluginNameWithoutPrefix = removePrefix(pluginNameWithoutNamespace);
|
||||
|
||||
plugins[pluginNameWithoutPrefix] = plugin;
|
||||
@@ -104,7 +104,7 @@ module.exports = {
|
||||
* @throws {Error} If the plugin cannot be loaded.
|
||||
*/
|
||||
load: function(pluginName) {
|
||||
var pluginNamespace = getNamespace(pluginName),
|
||||
let pluginNamespace = getNamespace(pluginName),
|
||||
pluginNameWithoutNamespace = removeNamespace(pluginName),
|
||||
pluginNameWithoutPrefix = removePrefix(pluginNameWithoutNamespace),
|
||||
plugin = null;
|
||||
|
||||
+68
-61
@@ -9,7 +9,7 @@
|
||||
// Requirements
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
var assert = require("assert"),
|
||||
let assert = require("assert"),
|
||||
EventEmitter = require("events").EventEmitter,
|
||||
escope = require("escope"),
|
||||
levn = require("levn"),
|
||||
@@ -41,19 +41,16 @@ var assert = require("assert"),
|
||||
* @returns {Object} Result map object of names and boolean values
|
||||
*/
|
||||
function parseBooleanConfig(string, comment) {
|
||||
var items = {};
|
||||
let items = {};
|
||||
|
||||
// Collapse whitespace around : to make parsing easier
|
||||
string = string.replace(/\s*:\s*/g, ":");
|
||||
|
||||
// Collapse whitespace around ,
|
||||
string = string.replace(/\s*,\s*/g, ",");
|
||||
// Collapse whitespace around `:` and `,` to make parsing easier
|
||||
string = string.replace(/\s*([:,])\s*/g, "$1");
|
||||
|
||||
string.split(/\s|,+/).forEach(function(name) {
|
||||
if (!name) {
|
||||
return;
|
||||
}
|
||||
var pos = name.indexOf(":"),
|
||||
let pos = name.indexOf(":"),
|
||||
value;
|
||||
|
||||
if (pos !== -1) {
|
||||
@@ -78,7 +75,7 @@ function parseBooleanConfig(string, comment) {
|
||||
* @returns {Object} Result map object
|
||||
*/
|
||||
function parseJsonConfig(string, location, messages) {
|
||||
var items = {};
|
||||
let items = {};
|
||||
|
||||
// Parses a JSON-like comment by the same way as parsing CLI option.
|
||||
try {
|
||||
@@ -125,7 +122,7 @@ function parseJsonConfig(string, location, messages) {
|
||||
* @returns {Object} Result map of values and true values
|
||||
*/
|
||||
function parseListConfig(string) {
|
||||
var items = {};
|
||||
let items = {};
|
||||
|
||||
// Collapse whitespace around ,
|
||||
string = string.replace(/\s*,\s*/g, ",");
|
||||
@@ -150,7 +147,7 @@ function parseListConfig(string) {
|
||||
* @returns {void}
|
||||
*/
|
||||
function addDeclaredGlobals(program, globalScope, config) {
|
||||
var declaredGlobals = {},
|
||||
let declaredGlobals = {},
|
||||
exportedGlobals = {},
|
||||
explicitGlobals = {},
|
||||
builtin = Environments.get("builtin");
|
||||
@@ -159,7 +156,7 @@ function addDeclaredGlobals(program, globalScope, config) {
|
||||
|
||||
Object.keys(config.env).forEach(function(name) {
|
||||
if (config.env[name]) {
|
||||
var env = Environments.get(name),
|
||||
let env = Environments.get(name),
|
||||
environmentGlobals = env && env.globals;
|
||||
|
||||
if (environmentGlobals) {
|
||||
@@ -173,7 +170,7 @@ function addDeclaredGlobals(program, globalScope, config) {
|
||||
lodash.assign(explicitGlobals, config.astGlobals);
|
||||
|
||||
Object.keys(declaredGlobals).forEach(function(name) {
|
||||
var variable = globalScope.set.get(name);
|
||||
let variable = globalScope.set.get(name);
|
||||
|
||||
if (!variable) {
|
||||
variable = new escope.Variable(name, globalScope);
|
||||
@@ -185,7 +182,7 @@ function addDeclaredGlobals(program, globalScope, config) {
|
||||
});
|
||||
|
||||
Object.keys(explicitGlobals).forEach(function(name) {
|
||||
var variable = globalScope.set.get(name);
|
||||
let variable = globalScope.set.get(name);
|
||||
|
||||
if (!variable) {
|
||||
variable = new escope.Variable(name, globalScope);
|
||||
@@ -199,7 +196,7 @@ function addDeclaredGlobals(program, globalScope, config) {
|
||||
|
||||
// mark all exported variables as such
|
||||
Object.keys(exportedGlobals).forEach(function(name) {
|
||||
var variable = globalScope.set.get(name);
|
||||
let variable = globalScope.set.get(name);
|
||||
|
||||
if (variable) {
|
||||
variable.eslintUsed = true;
|
||||
@@ -212,8 +209,8 @@ function addDeclaredGlobals(program, globalScope, config) {
|
||||
* references and remove the ones that were added by configuration.
|
||||
*/
|
||||
globalScope.through = globalScope.through.filter(function(reference) {
|
||||
var name = reference.identifier.name;
|
||||
var variable = globalScope.set.get(name);
|
||||
let name = reference.identifier.name;
|
||||
let variable = globalScope.set.get(name);
|
||||
|
||||
if (variable) {
|
||||
|
||||
@@ -267,7 +264,7 @@ function disableReporting(reportingConfig, start, rulesToDisable) {
|
||||
* @returns {void}
|
||||
*/
|
||||
function enableReporting(reportingConfig, start, rulesToEnable) {
|
||||
var i;
|
||||
let i;
|
||||
|
||||
if (rulesToEnable.length) {
|
||||
rulesToEnable.forEach(function(rule) {
|
||||
@@ -281,7 +278,7 @@ function enableReporting(reportingConfig, start, rulesToEnable) {
|
||||
} else {
|
||||
|
||||
// find all previous disabled locations if they was started as list of rules
|
||||
var prevStart;
|
||||
let prevStart;
|
||||
|
||||
for (i = reportingConfig.length - 1; i >= 0; i--) {
|
||||
if (prevStart && prevStart !== reportingConfig[i].start) {
|
||||
@@ -305,22 +302,22 @@ function enableReporting(reportingConfig, start, rulesToEnable) {
|
||||
* @param {Object} config The existing configuration data.
|
||||
* @param {Object[]} reportingConfig The existing reporting configuration data.
|
||||
* @param {Object[]} messages The messages queue.
|
||||
* @returns {object} Modified config object
|
||||
* @returns {Object} Modified config object
|
||||
*/
|
||||
function modifyConfigsFromComments(filename, ast, config, reportingConfig, messages) {
|
||||
|
||||
var commentConfig = {
|
||||
let commentConfig = {
|
||||
exported: {},
|
||||
astGlobals: {},
|
||||
rules: {},
|
||||
env: {}
|
||||
};
|
||||
var commentRules = {};
|
||||
let commentRules = {};
|
||||
|
||||
ast.comments.forEach(function(comment) {
|
||||
|
||||
var value = comment.value.trim();
|
||||
var match = /^(eslint(-\w+){0,3}|exported|globals?)(\s|$)/.exec(value);
|
||||
let value = comment.value.trim();
|
||||
let match = /^(eslint(-\w+){0,3}|exported|globals?)(\s|$)/.exec(value);
|
||||
|
||||
if (match) {
|
||||
value = value.substring(match.index + match[1].length);
|
||||
@@ -348,16 +345,17 @@ function modifyConfigsFromComments(filename, ast, config, reportingConfig, messa
|
||||
enableReporting(reportingConfig, comment.loc.start, Object.keys(parseListConfig(value)));
|
||||
break;
|
||||
|
||||
case "eslint":
|
||||
var items = parseJsonConfig(value, comment.loc, messages);
|
||||
case "eslint": {
|
||||
const items = parseJsonConfig(value, comment.loc, messages);
|
||||
|
||||
Object.keys(items).forEach(function(name) {
|
||||
var ruleValue = items[name];
|
||||
let ruleValue = items[name];
|
||||
|
||||
validator.validateRuleOptions(name, ruleValue, filename + " line " + comment.loc.start.line);
|
||||
commentRules[name] = ruleValue;
|
||||
});
|
||||
break;
|
||||
}
|
||||
|
||||
// no default
|
||||
}
|
||||
@@ -375,7 +373,7 @@ function modifyConfigsFromComments(filename, ast, config, reportingConfig, messa
|
||||
|
||||
// apply environment configs
|
||||
Object.keys(commentConfig.env).forEach(function(name) {
|
||||
var env = Environments.get(name);
|
||||
let env = Environments.get(name);
|
||||
|
||||
if (env) {
|
||||
commentConfig = ConfigOps.merge(commentConfig, env);
|
||||
@@ -395,9 +393,9 @@ function modifyConfigsFromComments(filename, ast, config, reportingConfig, messa
|
||||
*/
|
||||
function isDisabledByReportingConfig(reportingConfig, ruleId, location) {
|
||||
|
||||
for (var i = 0, c = reportingConfig.length; i < c; i++) {
|
||||
for (let i = 0, c = reportingConfig.length; i < c; i++) {
|
||||
|
||||
var ignore = reportingConfig[i];
|
||||
let ignore = reportingConfig[i];
|
||||
|
||||
if ((!ignore.rule || ignore.rule === ruleId) &&
|
||||
(location.line > ignore.start.line || (location.line === ignore.start.line && location.column >= ignore.start.column)) &&
|
||||
@@ -419,13 +417,13 @@ function prepareConfig(config) {
|
||||
config.globals = config.globals || config.global || {};
|
||||
delete config.global;
|
||||
|
||||
var copiedRules = {},
|
||||
let copiedRules = {},
|
||||
parserOptions = {},
|
||||
preparedConfig;
|
||||
|
||||
if (typeof config.rules === "object") {
|
||||
Object.keys(config.rules).forEach(function(k) {
|
||||
var rule = config.rules[k];
|
||||
let rule = config.rules[k];
|
||||
|
||||
if (rule === null) {
|
||||
throw new Error("Invalid config for rule '" + k + "'\.");
|
||||
@@ -441,7 +439,7 @@ function prepareConfig(config) {
|
||||
// merge in environment parserOptions
|
||||
if (typeof config.env === "object") {
|
||||
Object.keys(config.env).forEach(function(envName) {
|
||||
var env = Environments.get(envName);
|
||||
let env = Environments.get(envName);
|
||||
|
||||
if (config.env[envName] && env && env.parserOptions) {
|
||||
parserOptions = ConfigOps.merge(parserOptions, env.parserOptions);
|
||||
@@ -484,8 +482,8 @@ function createStubRule(message) {
|
||||
|
||||
/**
|
||||
* Creates a fake rule object
|
||||
* @param {object} context context object for each rule
|
||||
* @returns {object} collection of node to listen on
|
||||
* @param {Object} context context object for each rule
|
||||
* @returns {Object} collection of node to listen on
|
||||
*/
|
||||
function createRuleModule(context) {
|
||||
return {
|
||||
@@ -509,7 +507,7 @@ function createStubRule(message) {
|
||||
*/
|
||||
function getRuleReplacementMessage(ruleId) {
|
||||
if (ruleId in replacements.rules) {
|
||||
var newRules = replacements.rules[ruleId];
|
||||
let newRules = replacements.rules[ruleId];
|
||||
|
||||
return "Rule \'" + ruleId + "\' was removed and replaced by: " + newRules.join(", ");
|
||||
}
|
||||
@@ -517,15 +515,15 @@ function getRuleReplacementMessage(ruleId) {
|
||||
return null;
|
||||
}
|
||||
|
||||
var eslintEnvPattern = /\/\*\s*eslint-env\s(.+?)\*\//g;
|
||||
let eslintEnvPattern = /\/\*\s*eslint-env\s(.+?)\*\//g;
|
||||
|
||||
/**
|
||||
* Checks whether or not there is a comment which has "eslint-env *" in a given text.
|
||||
* @param {string} text - A source code text to check.
|
||||
* @returns {object|null} A result of parseListConfig() with "eslint-env *" comment.
|
||||
* @returns {Object|null} A result of parseListConfig() with "eslint-env *" comment.
|
||||
*/
|
||||
function findEslintEnv(text) {
|
||||
var match, retv;
|
||||
let match, retv;
|
||||
|
||||
eslintEnvPattern.lastIndex = 0;
|
||||
|
||||
@@ -565,7 +563,7 @@ function stripUnicodeBOM(text) {
|
||||
*/
|
||||
module.exports = (function() {
|
||||
|
||||
var api = Object.create(new EventEmitter()),
|
||||
let api = Object.create(new EventEmitter()),
|
||||
messages = [],
|
||||
currentConfig = null,
|
||||
currentScopes = null,
|
||||
@@ -587,7 +585,7 @@ module.exports = (function() {
|
||||
*/
|
||||
function parse(text, config) {
|
||||
|
||||
var parser,
|
||||
let parser,
|
||||
parserOptions = {
|
||||
loc: true,
|
||||
range: true,
|
||||
@@ -629,8 +627,8 @@ module.exports = (function() {
|
||||
} catch (ex) {
|
||||
|
||||
// If the message includes a leading line number, strip it:
|
||||
var message = ex.message.replace(/^line \d+:/i, "").trim();
|
||||
var source = (ex.lineNumber) ? SourceCode.splitLines(text)[ex.lineNumber - 1] : null;
|
||||
let message = ex.message.replace(/^line \d+:/i, "").trim();
|
||||
let source = (ex.lineNumber) ? SourceCode.splitLines(text)[ex.lineNumber - 1] : null;
|
||||
|
||||
messages.push({
|
||||
ruleId: null,
|
||||
@@ -721,7 +719,7 @@ module.exports = (function() {
|
||||
*/
|
||||
api.verify = function(textOrSourceCode, config, filenameOrOptions, saveState) {
|
||||
|
||||
var ast,
|
||||
let ast,
|
||||
shebang,
|
||||
ecmaFeatures,
|
||||
ecmaVersion,
|
||||
@@ -742,7 +740,7 @@ module.exports = (function() {
|
||||
}
|
||||
|
||||
// search and apply "eslint-env *".
|
||||
var envInFile = findEslintEnv(text || textOrSourceCode.text);
|
||||
let envInFile = findEslintEnv(text || textOrSourceCode.text);
|
||||
|
||||
if (envInFile) {
|
||||
if (!config || !config.env) {
|
||||
@@ -797,7 +795,7 @@ module.exports = (function() {
|
||||
Object.keys(config.rules).filter(function(key) {
|
||||
return getRuleSeverity(config.rules[key]) > 0;
|
||||
}).forEach(function(key) {
|
||||
var ruleCreator,
|
||||
let ruleCreator,
|
||||
severity,
|
||||
options,
|
||||
rule;
|
||||
@@ -805,7 +803,7 @@ module.exports = (function() {
|
||||
ruleCreator = rules.get(key);
|
||||
|
||||
if (!ruleCreator) {
|
||||
var replacementMsg = getRuleReplacementMessage(key);
|
||||
let replacementMsg = getRuleReplacementMessage(key);
|
||||
|
||||
if (replacementMsg) {
|
||||
ruleCreator = createStubRule(replacementMsg);
|
||||
@@ -819,7 +817,7 @@ module.exports = (function() {
|
||||
options = getRuleOptions(config.rules[key]);
|
||||
|
||||
try {
|
||||
var ruleContext = new RuleContext(
|
||||
let ruleContext = new RuleContext(
|
||||
key, api, severity, options,
|
||||
config.settings, config.parserOptions, config.parser, ruleCreator.meta);
|
||||
|
||||
@@ -865,7 +863,7 @@ module.exports = (function() {
|
||||
scopeMap = [];
|
||||
|
||||
currentScopes.forEach(function(scope, index) {
|
||||
var range = scope.block.range[0];
|
||||
let range = scope.block.range[0];
|
||||
|
||||
/*
|
||||
* Sometimes two scopes are returned for a given node. This is
|
||||
@@ -888,7 +886,7 @@ module.exports = (function() {
|
||||
}
|
||||
}
|
||||
|
||||
var eventGenerator = new NodeEventGenerator(api);
|
||||
let eventGenerator = new NodeEventGenerator(api);
|
||||
|
||||
eventGenerator = new CodePathAnalyzer(eventGenerator);
|
||||
eventGenerator = new CommentEventGenerator(eventGenerator, sourceCode);
|
||||
@@ -912,7 +910,7 @@ module.exports = (function() {
|
||||
|
||||
// sort by line and column
|
||||
messages.sort(function(a, b) {
|
||||
var lineDiff = a.line - b.line;
|
||||
let lineDiff = a.line - b.line;
|
||||
|
||||
if (lineDiff === 0) {
|
||||
return a.column - b.column;
|
||||
@@ -954,7 +952,10 @@ module.exports = (function() {
|
||||
location = node.loc.start;
|
||||
}
|
||||
|
||||
// else, assume location was provided, so node may be omitted
|
||||
// Store end location.
|
||||
let endLocation = location.end;
|
||||
|
||||
location = location.start || location;
|
||||
|
||||
if (isDisabledByReportingConfig(reportingConfig, ruleId, location)) {
|
||||
return;
|
||||
@@ -971,7 +972,7 @@ module.exports = (function() {
|
||||
});
|
||||
}
|
||||
|
||||
var problem = {
|
||||
let problem = {
|
||||
ruleId: ruleId,
|
||||
severity: severity,
|
||||
message: message,
|
||||
@@ -981,6 +982,12 @@ module.exports = (function() {
|
||||
source: sourceCode.lines[location.line - 1] || ""
|
||||
};
|
||||
|
||||
// Define endLine and endColumn if exists.
|
||||
if (endLocation) {
|
||||
problem.endLine = endLocation.line;
|
||||
problem.endColumn = endLocation.column + 1; // switch to 1-base instead of 0-base
|
||||
}
|
||||
|
||||
// ensure there's range and text properties, otherwise it's not a valid fix
|
||||
if (fix && Array.isArray(fix.range) && (typeof fix.text === "string")) {
|
||||
|
||||
@@ -1004,7 +1011,7 @@ module.exports = (function() {
|
||||
};
|
||||
|
||||
// methods that exist on SourceCode object
|
||||
var externalMethods = {
|
||||
let externalMethods = {
|
||||
getSource: "getText",
|
||||
getSourceLines: "getLines",
|
||||
getAllComments: "getAllComments",
|
||||
@@ -1026,7 +1033,7 @@ module.exports = (function() {
|
||||
|
||||
// copy over methods
|
||||
Object.keys(externalMethods).forEach(function(methodName) {
|
||||
var exMethodName = externalMethods[methodName];
|
||||
let exMethodName = externalMethods[methodName];
|
||||
|
||||
// All functions expected to have less arguments than 5.
|
||||
api[methodName] = function(a, b, c, d, e) {
|
||||
@@ -1050,14 +1057,14 @@ module.exports = (function() {
|
||||
* @returns {Object} An object representing the current node's scope.
|
||||
*/
|
||||
api.getScope = function() {
|
||||
var parents = traverser.parents(),
|
||||
let parents = traverser.parents(),
|
||||
scope = currentScopes[0];
|
||||
|
||||
// Don't do this for Program nodes - they have no parents
|
||||
if (parents.length) {
|
||||
|
||||
// if current node introduces a scope, add it to the list
|
||||
var current = traverser.current();
|
||||
let current = traverser.current();
|
||||
|
||||
if (currentConfig.parserOptions.ecmaVersion >= 6) {
|
||||
if (["BlockStatement", "SwitchStatement", "CatchClause", "FunctionDeclaration", "FunctionExpression", "ArrowFunctionExpression"].indexOf(current.type) >= 0) {
|
||||
@@ -1070,7 +1077,7 @@ module.exports = (function() {
|
||||
}
|
||||
|
||||
// Ascend the current node's parents
|
||||
for (var i = parents.length - 1; i >= 0; --i) {
|
||||
for (let i = parents.length - 1; i >= 0; --i) {
|
||||
|
||||
// Get the innermost scope
|
||||
scope = scopeManager.acquire(parents[i], true);
|
||||
@@ -1096,7 +1103,7 @@ module.exports = (function() {
|
||||
* false if not.
|
||||
*/
|
||||
api.markVariableAsUsed = function(name) {
|
||||
var scope = this.getScope(),
|
||||
let scope = this.getScope(),
|
||||
hasGlobalReturn = currentConfig.parserOptions.ecmaFeatures && currentConfig.parserOptions.ecmaFeatures.globalReturn,
|
||||
specialScope = hasGlobalReturn || currentConfig.parserOptions.sourceType === "module",
|
||||
variables,
|
||||
@@ -1140,13 +1147,13 @@ module.exports = (function() {
|
||||
* @param {Function} ruleModule Function from context to object mapping AST node types to event handlers
|
||||
* @returns {void}
|
||||
*/
|
||||
var defineRule = api.defineRule = function(ruleId, ruleModule) {
|
||||
let defineRule = api.defineRule = function(ruleId, ruleModule) {
|
||||
rules.define(ruleId, ruleModule);
|
||||
};
|
||||
|
||||
/**
|
||||
* Defines many new linting rules.
|
||||
* @param {object} rulesToDefine map from unique rule identifier to rule
|
||||
* @param {Object} rulesToDefine map from unique rule identifier to rule
|
||||
* @returns {void}
|
||||
*/
|
||||
api.defineRules = function(rulesToDefine) {
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
// Requirements
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
var fs = require("fs"),
|
||||
let fs = require("fs"),
|
||||
path = require("path");
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
@@ -55,11 +55,11 @@ function FileFinder(files, cwd) {
|
||||
* @returns {Object} Hashmap of filenames
|
||||
*/
|
||||
function normalizeDirectoryEntries(entries, directory, supportedConfigs) {
|
||||
var fileHash = {};
|
||||
let fileHash = {};
|
||||
|
||||
entries.forEach(function(entry) {
|
||||
if (supportedConfigs.indexOf(entry) >= 0) {
|
||||
var resolvedEntry = path.resolve(directory, entry);
|
||||
let resolvedEntry = path.resolve(directory, entry);
|
||||
|
||||
if (fs.statSync(resolvedEntry).isFile()) {
|
||||
fileHash[entry] = resolvedEntry;
|
||||
@@ -79,7 +79,7 @@ function normalizeDirectoryEntries(entries, directory, supportedConfigs) {
|
||||
* @returns {string[]} The file paths found.
|
||||
*/
|
||||
FileFinder.prototype.findAllInDirectoryAndParents = function(directory) {
|
||||
var cache = this.cache,
|
||||
let cache = this.cache,
|
||||
child,
|
||||
dirs,
|
||||
fileNames,
|
||||
@@ -106,10 +106,10 @@ FileFinder.prototype.findAllInDirectoryAndParents = function(directory) {
|
||||
dirs[searched++] = directory;
|
||||
cache[directory] = [];
|
||||
|
||||
var filesMap = normalizeDirectoryEntries(getDirectoryEntries(directory), directory, fileNames);
|
||||
let filesMap = normalizeDirectoryEntries(getDirectoryEntries(directory), directory, fileNames);
|
||||
|
||||
if (Object.keys(filesMap).length) {
|
||||
for (var k = 0; k < fileNames.length; k++) {
|
||||
for (let k = 0; k < fileNames.length; k++) {
|
||||
|
||||
if (filesMap[fileNames[k]]) {
|
||||
filePath = filesMap[fileNames[k]];
|
||||
|
||||
@@ -4,13 +4,15 @@
|
||||
*/
|
||||
"use strict";
|
||||
|
||||
let xmlEscape = require("../util/xml-escape");
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Helper Functions
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Returns the severity of warning or error
|
||||
* @param {object} message message object to examine
|
||||
* @param {Object} message message object to examine
|
||||
* @returns {string} severity level
|
||||
* @private
|
||||
*/
|
||||
@@ -22,44 +24,19 @@ function getMessageType(message) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the escaped value for a character
|
||||
* @param {string} s string to examine
|
||||
* @returns {string} severity level
|
||||
* @private
|
||||
*/
|
||||
function xmlEscape(s) {
|
||||
return ("" + s).replace(/[<>&"']/g, function(c) {
|
||||
switch (c) {
|
||||
case "<":
|
||||
return "<";
|
||||
case ">":
|
||||
return ">";
|
||||
case "&":
|
||||
return "&";
|
||||
case "\"":
|
||||
return """;
|
||||
case "'":
|
||||
return "'";
|
||||
default:
|
||||
throw new Error("unreachable");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Public Interface
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
module.exports = function(results) {
|
||||
|
||||
var output = "";
|
||||
let output = "";
|
||||
|
||||
output += "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
|
||||
output += "<checkstyle version=\"4.3\">";
|
||||
|
||||
results.forEach(function(result) {
|
||||
var messages = result.messages;
|
||||
let messages = result.messages;
|
||||
|
||||
output += "<file name=\"" + xmlEscape(result.filePath) + "\">";
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
|
||||
/**
|
||||
* Returns the severity of warning or error
|
||||
* @param {object} message message object to examine
|
||||
* @param {Object} message message object to examine
|
||||
* @returns {string} severity level
|
||||
* @private
|
||||
*/
|
||||
@@ -29,12 +29,12 @@ function getMessageType(message) {
|
||||
|
||||
module.exports = function(results) {
|
||||
|
||||
var output = "",
|
||||
let output = "",
|
||||
total = 0;
|
||||
|
||||
results.forEach(function(result) {
|
||||
|
||||
var messages = result.messages;
|
||||
let messages = result.messages;
|
||||
|
||||
total += messages.length;
|
||||
|
||||
|
||||
@@ -4,17 +4,17 @@
|
||||
*/
|
||||
"use strict";
|
||||
|
||||
var lodash = require("lodash");
|
||||
var fs = require("fs");
|
||||
var path = require("path");
|
||||
let lodash = require("lodash");
|
||||
let fs = require("fs");
|
||||
let path = require("path");
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Helpers
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
var pageTemplate = lodash.template(fs.readFileSync(path.join(__dirname, "html-template-page.html"), "utf-8"));
|
||||
var messageTemplate = lodash.template(fs.readFileSync(path.join(__dirname, "html-template-message.html"), "utf-8"));
|
||||
var resultTemplate = lodash.template(fs.readFileSync(path.join(__dirname, "html-template-result.html"), "utf-8"));
|
||||
let pageTemplate = lodash.template(fs.readFileSync(path.join(__dirname, "html-template-page.html"), "utf-8"));
|
||||
let messageTemplate = lodash.template(fs.readFileSync(path.join(__dirname, "html-template-message.html"), "utf-8"));
|
||||
let resultTemplate = lodash.template(fs.readFileSync(path.join(__dirname, "html-template-result.html"), "utf-8"));
|
||||
|
||||
/**
|
||||
* Given a word and a count, append an s if count is not one.
|
||||
@@ -33,8 +33,8 @@ function pluralize(word, count) {
|
||||
* @returns {string} The formatted string, pluralized where necessary
|
||||
*/
|
||||
function renderSummary(totalErrors, totalWarnings) {
|
||||
var totalProblems = totalErrors + totalWarnings;
|
||||
var renderedText = totalProblems + " " + pluralize("problem", totalProblems);
|
||||
let totalProblems = totalErrors + totalWarnings;
|
||||
let renderedText = totalProblems + " " + pluralize("problem", totalProblems);
|
||||
|
||||
if (totalProblems !== 0) {
|
||||
renderedText += " (" + totalErrors + " " + pluralize("error", totalErrors) + ", " + totalWarnings + " " + pluralize("warning", totalWarnings) + ")";
|
||||
@@ -71,7 +71,7 @@ function renderMessages(messages, parentIndex) {
|
||||
* @returns {string} HTML (table row) describing a message.
|
||||
*/
|
||||
return lodash.map(messages, function(message) {
|
||||
var lineNumber,
|
||||
let lineNumber,
|
||||
columnNumber;
|
||||
|
||||
lineNumber = message.line || 0;
|
||||
@@ -110,7 +110,7 @@ function renderResults(results) {
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
module.exports = function(results) {
|
||||
var totalErrors,
|
||||
let totalErrors,
|
||||
totalWarnings;
|
||||
|
||||
totalErrors = 0;
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
*/
|
||||
"use strict";
|
||||
|
||||
var lodash = require("lodash");
|
||||
let xmlEscape = require("../util/xml-escape");
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Public Interface
|
||||
@@ -12,21 +12,21 @@ var lodash = require("lodash");
|
||||
|
||||
module.exports = function(results) {
|
||||
|
||||
var output = "";
|
||||
let output = "";
|
||||
|
||||
output += "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
|
||||
output += "<jslint>";
|
||||
|
||||
results.forEach(function(result) {
|
||||
var messages = result.messages;
|
||||
let messages = result.messages;
|
||||
|
||||
output += "<file name=\"" + result.filePath + "\">";
|
||||
|
||||
messages.forEach(function(message) {
|
||||
output += "<issue line=\"" + message.line + "\" " +
|
||||
"char=\"" + message.column + "\" " +
|
||||
"evidence=\"" + lodash.escape(message.source || "") + "\" " +
|
||||
"reason=\"" + lodash.escape(message.message || "") +
|
||||
"evidence=\"" + xmlEscape(message.source || "") + "\" " +
|
||||
"reason=\"" + xmlEscape(message.message || "") +
|
||||
(message.ruleId ? " (" + message.ruleId + ")" : "") + "\" />";
|
||||
});
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
*/
|
||||
"use strict";
|
||||
|
||||
var lodash = require("lodash");
|
||||
let xmlEscape = require("../util/xml-escape");
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Helper Functions
|
||||
@@ -12,7 +12,7 @@ var lodash = require("lodash");
|
||||
|
||||
/**
|
||||
* Returns the severity of warning or error
|
||||
* @param {object} message message object to examine
|
||||
* @param {Object} message message object to examine
|
||||
* @returns {string} severity level
|
||||
* @private
|
||||
*/
|
||||
@@ -30,28 +30,28 @@ function getMessageType(message) {
|
||||
|
||||
module.exports = function(results) {
|
||||
|
||||
var output = "";
|
||||
let output = "";
|
||||
|
||||
output += "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
|
||||
output += "<testsuites>\n";
|
||||
|
||||
results.forEach(function(result) {
|
||||
|
||||
var messages = result.messages;
|
||||
let messages = result.messages;
|
||||
|
||||
if (messages.length) {
|
||||
output += "<testsuite package=\"org.eslint\" time=\"0\" tests=\"" + messages.length + "\" errors=\"" + messages.length + "\" name=\"" + result.filePath + "\">\n";
|
||||
}
|
||||
|
||||
messages.forEach(function(message) {
|
||||
var type = message.fatal ? "error" : "failure";
|
||||
let type = message.fatal ? "error" : "failure";
|
||||
|
||||
output += "<testcase time=\"0\" name=\"org.eslint." + (message.ruleId || "unknown") + "\">";
|
||||
output += "<" + type + " message=\"" + lodash.escape(message.message || "") + "\">";
|
||||
output += "<" + type + " message=\"" + xmlEscape(message.message || "") + "\">";
|
||||
output += "<![CDATA[";
|
||||
output += "line " + (message.line || 0) + ", col ";
|
||||
output += (message.column || 0) + ", " + getMessageType(message);
|
||||
output += " - " + lodash.escape(message.message || "");
|
||||
output += " - " + xmlEscape(message.message || "");
|
||||
output += (message.ruleId ? " (" + message.ruleId + ")" : "");
|
||||
output += "]]>";
|
||||
output += "</" + type + ">";
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
*/
|
||||
"use strict";
|
||||
|
||||
var chalk = require("chalk"),
|
||||
let chalk = require("chalk"),
|
||||
table = require("text-table");
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
@@ -27,14 +27,14 @@ function pluralize(word, count) {
|
||||
|
||||
module.exports = function(results) {
|
||||
|
||||
var output = "\n",
|
||||
let output = "\n",
|
||||
total = 0,
|
||||
errors = 0,
|
||||
warnings = 0,
|
||||
summaryColor = "yellow";
|
||||
|
||||
results.forEach(function(result) {
|
||||
var messages = result.messages;
|
||||
let messages = result.messages;
|
||||
|
||||
if (messages.length === 0) {
|
||||
return;
|
||||
@@ -45,7 +45,7 @@ module.exports = function(results) {
|
||||
|
||||
output += table(
|
||||
messages.map(function(message) {
|
||||
var messageType;
|
||||
let messageType;
|
||||
|
||||
if (message.fatal || message.severity === 2) {
|
||||
messageType = chalk.red("error");
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
// Requirements
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
var chalk,
|
||||
let chalk,
|
||||
table,
|
||||
pluralize;
|
||||
|
||||
@@ -26,7 +26,7 @@ pluralize = require("pluralize");
|
||||
* @returns {string} A text table.
|
||||
*/
|
||||
function drawTable(messages) {
|
||||
var rows;
|
||||
let rows;
|
||||
|
||||
rows = [];
|
||||
|
||||
@@ -43,7 +43,7 @@ function drawTable(messages) {
|
||||
]);
|
||||
|
||||
messages.forEach(function(message) {
|
||||
var messageType;
|
||||
let messageType;
|
||||
|
||||
if (message.fatal || message.severity === 2) {
|
||||
messageType = chalk.red("error");
|
||||
@@ -96,7 +96,7 @@ function drawTable(messages) {
|
||||
* @returns {string} A column of text tables.
|
||||
*/
|
||||
function drawReport(results) {
|
||||
var files;
|
||||
let files;
|
||||
|
||||
files = results.map(function(result) {
|
||||
if (!result.messages.length) {
|
||||
@@ -118,7 +118,7 @@ function drawReport(results) {
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
module.exports = function(report) {
|
||||
var result,
|
||||
let result,
|
||||
errorCount,
|
||||
warningCount;
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
*/
|
||||
"use strict";
|
||||
|
||||
var yaml = require("js-yaml");
|
||||
let yaml = require("js-yaml");
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Helper Functions
|
||||
@@ -12,8 +12,8 @@ var yaml = require("js-yaml");
|
||||
|
||||
/**
|
||||
* Returns a canonical error level string based upon the error message passed in.
|
||||
* @param {object} message Individual error message provided by eslint
|
||||
* @returns {String} Error level string
|
||||
* @param {Object} message Individual error message provided by eslint
|
||||
* @returns {string} Error level string
|
||||
*/
|
||||
function getMessageType(message) {
|
||||
if (message.fatal || message.severity === 2) {
|
||||
@@ -25,12 +25,12 @@ function getMessageType(message) {
|
||||
|
||||
/**
|
||||
* Takes in a JavaScript object and outputs a TAP diagnostics string
|
||||
* @param {object} diagnostic JavaScript object to be embedded as YAML into output.
|
||||
* @param {Object} diagnostic JavaScript object to be embedded as YAML into output.
|
||||
* @returns {string} diagnostics string with YAML embedded - TAP version 13 compliant
|
||||
*/
|
||||
function outputDiagnostics(diagnostic) {
|
||||
var prefix = " ";
|
||||
var output = prefix + "---\n";
|
||||
let prefix = " ";
|
||||
let output = prefix + "---\n";
|
||||
|
||||
output += prefix + yaml.safeDump(diagnostic).split("\n").join("\n" + prefix);
|
||||
output += "...\n";
|
||||
@@ -42,18 +42,18 @@ function outputDiagnostics(diagnostic) {
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
module.exports = function(results) {
|
||||
var output = "TAP version 13\n1.." + results.length + "\n";
|
||||
let output = "TAP version 13\n1.." + results.length + "\n";
|
||||
|
||||
results.forEach(function(result, id) {
|
||||
var messages = result.messages;
|
||||
var testResult = "ok";
|
||||
var diagnostics = {};
|
||||
let messages = result.messages;
|
||||
let testResult = "ok";
|
||||
let diagnostics = {};
|
||||
|
||||
if (messages.length > 0) {
|
||||
testResult = "not ok";
|
||||
|
||||
messages.forEach(function(message) {
|
||||
var diagnostic = {
|
||||
let diagnostic = {
|
||||
message: message.message,
|
||||
severity: getMessageType(message),
|
||||
data: {
|
||||
|
||||
@@ -10,8 +10,8 @@
|
||||
|
||||
/**
|
||||
* Returns a canonical error level string based upon the error message passed in.
|
||||
* @param {object} message Individual error message provided by eslint
|
||||
* @returns {String} Error level string
|
||||
* @param {Object} message Individual error message provided by eslint
|
||||
* @returns {string} Error level string
|
||||
*/
|
||||
function getMessageType(message) {
|
||||
if (message.fatal || message.severity === 2) {
|
||||
@@ -28,12 +28,12 @@ function getMessageType(message) {
|
||||
|
||||
module.exports = function(results) {
|
||||
|
||||
var output = "",
|
||||
let output = "",
|
||||
total = 0;
|
||||
|
||||
results.forEach(function(result) {
|
||||
|
||||
var messages = result.messages;
|
||||
let messages = result.messages;
|
||||
|
||||
total += messages.length;
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
|
||||
/**
|
||||
* Returns the severity of warning or error
|
||||
* @param {object} message message object to examine
|
||||
* @param {Object} message message object to examine
|
||||
* @returns {string} severity level
|
||||
* @private
|
||||
*/
|
||||
@@ -30,12 +30,12 @@ function getMessageType(message) {
|
||||
|
||||
module.exports = function(results) {
|
||||
|
||||
var output = "",
|
||||
let output = "",
|
||||
total = 0;
|
||||
|
||||
results.forEach(function(result) {
|
||||
|
||||
var messages = result.messages;
|
||||
let messages = result.messages;
|
||||
|
||||
total += messages.length;
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
// Requirements
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
var lodash = require("lodash"),
|
||||
let lodash = require("lodash"),
|
||||
fs = require("fs"),
|
||||
path = require("path"),
|
||||
debug = require("debug"),
|
||||
@@ -23,12 +23,12 @@ debug = debug("eslint:ignored-paths");
|
||||
// Constants
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
var ESLINT_IGNORE_FILENAME = ".eslintignore";
|
||||
var DEFAULT_IGNORE_DIRS = [
|
||||
let ESLINT_IGNORE_FILENAME = ".eslintignore";
|
||||
let DEFAULT_IGNORE_DIRS = [
|
||||
"node_modules/",
|
||||
"bower_components/"
|
||||
];
|
||||
var DEFAULT_OPTIONS = {
|
||||
let DEFAULT_OPTIONS = {
|
||||
dotfiles: false,
|
||||
cwd: process.cwd()
|
||||
};
|
||||
@@ -47,15 +47,15 @@ var DEFAULT_OPTIONS = {
|
||||
function findIgnoreFile(cwd) {
|
||||
cwd = cwd || DEFAULT_OPTIONS.cwd;
|
||||
|
||||
var ignoreFilePath = path.resolve(cwd, ESLINT_IGNORE_FILENAME);
|
||||
let ignoreFilePath = path.resolve(cwd, ESLINT_IGNORE_FILENAME);
|
||||
|
||||
return fs.existsSync(ignoreFilePath) ? ignoreFilePath : "";
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge options with defaults
|
||||
* @param {object} options Options to merge with DEFAULT_OPTIONS constant
|
||||
* @returns {object} Merged options
|
||||
* @param {Object} options Options to merge with DEFAULT_OPTIONS constant
|
||||
* @returns {Object} Merged options
|
||||
*/
|
||||
function mergeDefaultOptions(options) {
|
||||
options = (options || {});
|
||||
@@ -78,7 +78,7 @@ function IgnoredPaths(options) {
|
||||
|
||||
/**
|
||||
* add pattern to node-ignore instance
|
||||
* @param {object} ig, instance of node-ignore
|
||||
* @param {Object} ig, instance of node-ignore
|
||||
* @param {string} pattern, pattern do add to ig
|
||||
* @returns {array} raw ignore rules
|
||||
*/
|
||||
@@ -88,7 +88,7 @@ function IgnoredPaths(options) {
|
||||
|
||||
/**
|
||||
* add ignore file to node-ignore instance
|
||||
* @param {object} ig, instance of node-ignore
|
||||
* @param {Object} ig, instance of node-ignore
|
||||
* @param {string} filepath, file to add to ig
|
||||
* @returns {array} raw ignore rules
|
||||
*/
|
||||
@@ -124,7 +124,7 @@ function IgnoredPaths(options) {
|
||||
addPattern(this.ig.default, this.defaultPatterns);
|
||||
|
||||
if (options.ignore !== false) {
|
||||
var ignorePath;
|
||||
let ignorePath;
|
||||
|
||||
if (options.ignorePath) {
|
||||
debug("Using specific ignore file");
|
||||
@@ -174,9 +174,9 @@ function IgnoredPaths(options) {
|
||||
*/
|
||||
IgnoredPaths.prototype.contains = function(filepath, category) {
|
||||
|
||||
var result = false;
|
||||
var absolutePath = path.resolve(this.options.cwd, filepath);
|
||||
var relativePath = pathUtil.getRelativePath(absolutePath, this.options.cwd);
|
||||
let result = false;
|
||||
let absolutePath = path.resolve(this.options.cwd, filepath);
|
||||
let relativePath = pathUtil.getRelativePath(absolutePath, this.options.cwd);
|
||||
|
||||
if ((typeof category === "undefined") || (category === "default")) {
|
||||
result = result || (this.ig.default.filter([relativePath]).length === 0);
|
||||
@@ -195,13 +195,13 @@ IgnoredPaths.prototype.contains = function(filepath, category) {
|
||||
* @returns {string[]} list of glob ignore patterns
|
||||
*/
|
||||
IgnoredPaths.prototype.getIgnoredFoldersGlobPatterns = function() {
|
||||
var dirs = DEFAULT_IGNORE_DIRS;
|
||||
let dirs = DEFAULT_IGNORE_DIRS;
|
||||
|
||||
if (this.options.ignore) {
|
||||
|
||||
/* eslint-disable no-underscore-dangle */
|
||||
|
||||
var patterns = this.ig.custom._rules.filter(function(rule) {
|
||||
let patterns = this.ig.custom._rules.filter(function(rule) {
|
||||
return rule.negative;
|
||||
}).map(function(rule) {
|
||||
return rule.origin;
|
||||
|
||||
@@ -0,0 +1,212 @@
|
||||
/**
|
||||
* @fileoverview Internal rule to prevent missing or invalid meta property in core rules.
|
||||
* @author Vitor Balocco
|
||||
*/
|
||||
|
||||
"use strict";
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Helpers
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Gets the property of the Object node passed in that has the name specified.
|
||||
*
|
||||
* @param {string} property Name of the property to return.
|
||||
* @param {ASTNode} node The ObjectExpression node.
|
||||
* @returns {ASTNode} The Property node or null if not found.
|
||||
*/
|
||||
function getPropertyFromObject(property, node) {
|
||||
let properties = node.properties;
|
||||
|
||||
for (let i = 0; i < properties.length; i++) {
|
||||
if (properties[i].key.name === property) {
|
||||
return properties[i];
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts the `meta` property from the ObjectExpression that all rules export.
|
||||
*
|
||||
* @param {ASTNode} exportsNode ObjectExpression node that the rule exports.
|
||||
* @returns {ASTNode} The `meta` Property node or null if not found.
|
||||
*/
|
||||
function getMetaPropertyFromExportsNode(exportsNode) {
|
||||
return getPropertyFromObject("meta", exportsNode);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether this `meta` ObjectExpression has a `docs` property defined or not.
|
||||
*
|
||||
* @param {ASTNode} metaPropertyNode The `meta` ObjectExpression for this rule.
|
||||
* @returns {boolean} `true` if a `docs` property exists.
|
||||
*/
|
||||
function hasMetaDocs(metaPropertyNode) {
|
||||
return Boolean(getPropertyFromObject("docs", metaPropertyNode.value));
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether this `meta` ObjectExpression has a `docs.description` property defined or not.
|
||||
*
|
||||
* @param {ASTNode} metaPropertyNode The `meta` ObjectExpression for this rule.
|
||||
* @returns {boolean} `true` if a `docs.description` property exists.
|
||||
*/
|
||||
function hasMetaDocsDescription(metaPropertyNode) {
|
||||
let metaDocs = getPropertyFromObject("docs", metaPropertyNode.value);
|
||||
|
||||
return metaDocs && getPropertyFromObject("description", metaDocs.value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether this `meta` ObjectExpression has a `docs.category` property defined or not.
|
||||
*
|
||||
* @param {ASTNode} metaPropertyNode The `meta` ObjectExpression for this rule.
|
||||
* @returns {boolean} `true` if a `docs.category` property exists.
|
||||
*/
|
||||
function hasMetaDocsCategory(metaPropertyNode) {
|
||||
let metaDocs = getPropertyFromObject("docs", metaPropertyNode.value);
|
||||
|
||||
return metaDocs && getPropertyFromObject("category", metaDocs.value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether this `meta` ObjectExpression has a `docs.recommended` property defined or not.
|
||||
*
|
||||
* @param {ASTNode} metaPropertyNode The `meta` ObjectExpression for this rule.
|
||||
* @returns {boolean} `true` if a `docs.recommended` property exists.
|
||||
*/
|
||||
function hasMetaDocsRecommended(metaPropertyNode) {
|
||||
let metaDocs = getPropertyFromObject("docs", metaPropertyNode.value);
|
||||
|
||||
return metaDocs && getPropertyFromObject("recommended", metaDocs.value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether this `meta` ObjectExpression has a `schema` property defined or not.
|
||||
*
|
||||
* @param {ASTNode} metaPropertyNode The `meta` ObjectExpression for this rule.
|
||||
* @returns {boolean} `true` if a `schema` property exists.
|
||||
*/
|
||||
function hasMetaSchema(metaPropertyNode) {
|
||||
return getPropertyFromObject("schema", metaPropertyNode.value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether this `meta` ObjectExpression has a `fixable` property defined or not.
|
||||
*
|
||||
* @param {ASTNode} metaPropertyNode The `meta` ObjectExpression for this rule.
|
||||
* @returns {boolean} `true` if a `fixable` property exists.
|
||||
*/
|
||||
function hasMetaFixable(metaPropertyNode) {
|
||||
return getPropertyFromObject("fixable", metaPropertyNode.value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks the validity of the meta definition of this rule and reports any errors found.
|
||||
*
|
||||
* @param {RuleContext} context The ESLint rule context.
|
||||
* @param {ASTNode} exportsNode ObjectExpression node that the rule exports.
|
||||
* @param {boolean} ruleIsFixable whether the rule is fixable or not.
|
||||
* @returns {void}
|
||||
*/
|
||||
function checkMetaValidity(context, exportsNode, ruleIsFixable) {
|
||||
let metaProperty = getMetaPropertyFromExportsNode(exportsNode);
|
||||
|
||||
if (!metaProperty) {
|
||||
context.report(exportsNode, "Rule is missing a meta property.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!hasMetaDocs(metaProperty)) {
|
||||
context.report(metaProperty, "Rule is missing a meta.docs property.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!hasMetaDocsDescription(metaProperty)) {
|
||||
context.report(metaProperty, "Rule is missing a meta.docs.description property.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!hasMetaDocsCategory(metaProperty)) {
|
||||
context.report(metaProperty, "Rule is missing a meta.docs.category property.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!hasMetaDocsRecommended(metaProperty)) {
|
||||
context.report(metaProperty, "Rule is missing a meta.docs.recommended property.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!hasMetaSchema(metaProperty)) {
|
||||
context.report(metaProperty, "Rule is missing a meta.schema property.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (ruleIsFixable && !hasMetaFixable(metaProperty)) {
|
||||
context.report(metaProperty, "Rule is fixable, but is missing a meta.fixable property.");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Rule Definition
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
module.exports = {
|
||||
meta: {
|
||||
docs: {
|
||||
description: "enforce correct use of `meta` property in core rules",
|
||||
category: "Internal",
|
||||
recommended: false
|
||||
},
|
||||
|
||||
schema: []
|
||||
},
|
||||
|
||||
create: function(context) {
|
||||
let metaExportsValue;
|
||||
let ruleIsFixable = false;
|
||||
|
||||
return {
|
||||
AssignmentExpression: function(node) {
|
||||
if (node.left &&
|
||||
node.right &&
|
||||
node.left.type === "MemberExpression" &&
|
||||
node.left.object.name === "module" &&
|
||||
node.left.property.name === "exports") {
|
||||
|
||||
metaExportsValue = node.right;
|
||||
}
|
||||
},
|
||||
|
||||
CallExpression: function(node) {
|
||||
|
||||
// If the rule has a call for `context.report` and a property `fix`
|
||||
// is being passed in, then we consider that the rule is fixable.
|
||||
//
|
||||
// Note that we only look for context.report() calls in the new
|
||||
// style (with single MessageDescriptor argument), because only
|
||||
// calls in the new style can specify a fix.
|
||||
if (node.callee.type === "MemberExpression" &&
|
||||
node.callee.object.type === "Identifier" &&
|
||||
node.callee.object.name === "context" &&
|
||||
node.callee.property.type === "Identifier" &&
|
||||
node.callee.property.name === "report" &&
|
||||
node.arguments.length === 1 &&
|
||||
node.arguments[0].type === "ObjectExpression") {
|
||||
|
||||
if (getPropertyFromObject("fix", node.arguments[0])) {
|
||||
ruleIsFixable = true;
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
"Program:exit": function() {
|
||||
checkMetaValidity(context, metaExportsValue, ruleIsFixable);
|
||||
}
|
||||
};
|
||||
}
|
||||
};
|
||||
@@ -9,7 +9,7 @@
|
||||
// Requirements
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
var fs = require("fs"),
|
||||
let fs = require("fs"),
|
||||
path = require("path");
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
@@ -29,7 +29,7 @@ module.exports = function(rulesDir, cwd) {
|
||||
rulesDir = path.resolve(cwd, rulesDir);
|
||||
}
|
||||
|
||||
var rules = Object.create(null);
|
||||
let rules = Object.create(null);
|
||||
|
||||
fs.readdirSync(rulesDir).forEach(function(file) {
|
||||
if (path.extname(file) !== ".js") {
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
// Requirements
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
var optionator = require("optionator");
|
||||
let optionator = require("optionator");
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Initialization and Public Interface
|
||||
|
||||
@@ -8,13 +8,13 @@
|
||||
// Requirements
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
var RuleFixer = require("./util/rule-fixer");
|
||||
let RuleFixer = require("./util/rule-fixer");
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Constants
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
var PASSTHROUGHS = [
|
||||
let PASSTHROUGHS = [
|
||||
"getAncestors",
|
||||
"getDeclaredVariables",
|
||||
"getFilename",
|
||||
@@ -111,7 +111,7 @@ RuleContext.prototype = {
|
||||
* @returns {void}
|
||||
*/
|
||||
report: function(nodeOrDescriptor, location, message, opts) {
|
||||
var descriptor,
|
||||
let descriptor,
|
||||
fix = null;
|
||||
|
||||
// check to see if it's a new style call
|
||||
|
||||
@@ -9,13 +9,13 @@
|
||||
// Requirements
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
var loadRules = require("./load-rules");
|
||||
let loadRules = require("./load-rules");
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Privates
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
var rules = Object.create(null);
|
||||
let rules = Object.create(null);
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Public Interface
|
||||
@@ -38,7 +38,7 @@ function define(ruleId, ruleModule) {
|
||||
* @returns {void}
|
||||
*/
|
||||
function load(rulesDir, cwd) {
|
||||
var newRules = loadRules(rulesDir, cwd);
|
||||
let newRules = loadRules(rulesDir, cwd);
|
||||
|
||||
Object.keys(newRules).forEach(function(ruleId) {
|
||||
define(ruleId, newRules[ruleId]);
|
||||
@@ -53,7 +53,7 @@ function load(rulesDir, cwd) {
|
||||
*/
|
||||
function importPlugin(pluginRules, pluginName) {
|
||||
Object.keys(pluginRules).forEach(function(ruleId) {
|
||||
var qualifiedRuleId = pluginName + "/" + ruleId,
|
||||
let qualifiedRuleId = pluginName + "/" + ruleId,
|
||||
rule = pluginRules[ruleId];
|
||||
|
||||
define(qualifiedRuleId, rule);
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
rules:
|
||||
internal-no-invalid-meta: "error"
|
||||
@@ -28,7 +28,7 @@ function isIdentifier(node, name) {
|
||||
* @returns {boolean} `true` if the node is an argument of the specified method call.
|
||||
*/
|
||||
function isArgumentOfMethodCall(node, index, object, property) {
|
||||
var parent = node.parent;
|
||||
let parent = node.parent;
|
||||
|
||||
return (
|
||||
parent.type === "CallExpression" &&
|
||||
@@ -91,9 +91,9 @@ module.exports = {
|
||||
}]
|
||||
},
|
||||
create: function(context) {
|
||||
var config = context.options[0] || {};
|
||||
var checkGetWithoutSet = config.getWithoutSet === true;
|
||||
var checkSetWithoutGet = config.setWithoutGet !== false;
|
||||
let config = context.options[0] || {};
|
||||
let checkGetWithoutSet = config.getWithoutSet === true;
|
||||
let checkSetWithoutGet = config.setWithoutGet !== false;
|
||||
|
||||
/**
|
||||
* Checks a object expression to see if it has setter and getter both present or none.
|
||||
@@ -102,14 +102,14 @@ module.exports = {
|
||||
* @private
|
||||
*/
|
||||
function checkLonelySetGet(node) {
|
||||
var isSetPresent = false;
|
||||
var isGetPresent = false;
|
||||
var isDescriptor = isPropertyDescriptor(node);
|
||||
let isSetPresent = false;
|
||||
let isGetPresent = false;
|
||||
let isDescriptor = isPropertyDescriptor(node);
|
||||
|
||||
for (var i = 0, end = node.properties.length; i < end; i++) {
|
||||
var property = node.properties[i];
|
||||
for (let i = 0, end = node.properties.length; i < end; i++) {
|
||||
let property = node.properties[i];
|
||||
|
||||
var propToCheck = "";
|
||||
let propToCheck = "";
|
||||
|
||||
if (property.kind === "init") {
|
||||
if (isDescriptor && !property.computed) {
|
||||
@@ -139,9 +139,9 @@ module.exports = {
|
||||
}
|
||||
|
||||
if (checkSetWithoutGet && isSetPresent && !isGetPresent) {
|
||||
context.report(node, "Getter is not present");
|
||||
context.report(node, "Getter is not present.");
|
||||
} else if (checkGetWithoutSet && isGetPresent && !isSetPresent) {
|
||||
context.report(node, "Setter is not present");
|
||||
context.report(node, "Setter is not present.");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
*/
|
||||
"use strict";
|
||||
|
||||
var astUtils = require("../ast-utils");
|
||||
let astUtils = require("../ast-utils");
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Rule Definition
|
||||
@@ -40,7 +40,7 @@ module.exports = {
|
||||
]
|
||||
},
|
||||
create: function(context) {
|
||||
var spaced = context.options[0] === "always",
|
||||
let spaced = context.options[0] === "always",
|
||||
sourceCode = context.getSourceCode();
|
||||
|
||||
/**
|
||||
@@ -54,7 +54,7 @@ module.exports = {
|
||||
return context.options[1] ? context.options[1][option] === !spaced : false;
|
||||
}
|
||||
|
||||
var options = {
|
||||
let options = {
|
||||
spaced: spaced,
|
||||
singleElementException: isOptionSet("singleValue"),
|
||||
objectsInArraysException: isOptionSet("objectsInArrays"),
|
||||
@@ -75,9 +75,9 @@ module.exports = {
|
||||
context.report({
|
||||
node: node,
|
||||
loc: token.loc.start,
|
||||
message: "There should be no space after '" + token.value + "'",
|
||||
message: "There should be no space after '" + token.value + "'.",
|
||||
fix: function(fixer) {
|
||||
var nextToken = sourceCode.getTokenAfter(token);
|
||||
let nextToken = sourceCode.getTokenAfter(token);
|
||||
|
||||
return fixer.removeRange([token.range[1], nextToken.range[0]]);
|
||||
}
|
||||
@@ -94,9 +94,9 @@ module.exports = {
|
||||
context.report({
|
||||
node: node,
|
||||
loc: token.loc.start,
|
||||
message: "There should be no space before '" + token.value + "'",
|
||||
message: "There should be no space before '" + token.value + "'.",
|
||||
fix: function(fixer) {
|
||||
var previousToken = sourceCode.getTokenBefore(token);
|
||||
let previousToken = sourceCode.getTokenBefore(token);
|
||||
|
||||
return fixer.removeRange([previousToken.range[1], token.range[0]]);
|
||||
}
|
||||
@@ -113,7 +113,7 @@ module.exports = {
|
||||
context.report({
|
||||
node: node,
|
||||
loc: token.loc.start,
|
||||
message: "A space is required after '" + token.value + "'",
|
||||
message: "A space is required after '" + token.value + "'.",
|
||||
fix: function(fixer) {
|
||||
return fixer.insertTextAfter(token, " ");
|
||||
}
|
||||
@@ -130,7 +130,7 @@ module.exports = {
|
||||
context.report({
|
||||
node: node,
|
||||
loc: token.loc.start,
|
||||
message: "A space is required before '" + token.value + "'",
|
||||
message: "A space is required before '" + token.value + "'.",
|
||||
fix: function(fixer) {
|
||||
return fixer.insertTextBefore(token, " ");
|
||||
}
|
||||
@@ -165,20 +165,20 @@ module.exports = {
|
||||
return;
|
||||
}
|
||||
|
||||
var first = sourceCode.getFirstToken(node),
|
||||
let first = sourceCode.getFirstToken(node),
|
||||
second = sourceCode.getFirstToken(node, 1),
|
||||
penultimate = sourceCode.getLastToken(node, 1),
|
||||
last = sourceCode.getLastToken(node),
|
||||
firstElement = node.elements[0],
|
||||
lastElement = node.elements[node.elements.length - 1];
|
||||
|
||||
var openingBracketMustBeSpaced =
|
||||
let openingBracketMustBeSpaced =
|
||||
options.objectsInArraysException && isObjectType(firstElement) ||
|
||||
options.arraysInArraysException && isArrayType(firstElement) ||
|
||||
options.singleElementException && node.elements.length === 1
|
||||
? !options.spaced : options.spaced;
|
||||
|
||||
var closingBracketMustBeSpaced =
|
||||
let closingBracketMustBeSpaced =
|
||||
options.objectsInArraysException && isObjectType(lastElement) ||
|
||||
options.arraysInArraysException && isArrayType(lastElement) ||
|
||||
options.singleElementException && node.elements.length === 1
|
||||
|
||||
@@ -9,14 +9,14 @@
|
||||
// Requirements
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
var astUtils = require("../ast-utils");
|
||||
let astUtils = require("../ast-utils");
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Helpers
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
var TARGET_NODE_TYPE = /^(?:Arrow)?FunctionExpression$/;
|
||||
var TARGET_METHODS = /^(?:every|filter|find(?:Index)?|map|reduce(?:Right)?|some|sort)$/;
|
||||
let TARGET_NODE_TYPE = /^(?:Arrow)?FunctionExpression$/;
|
||||
let TARGET_METHODS = /^(?:every|filter|find(?:Index)?|map|reduce(?:Right)?|some|sort)$/;
|
||||
|
||||
/**
|
||||
* Checks a given code path segment is reachable.
|
||||
@@ -104,7 +104,7 @@ function isTargetMethod(node) {
|
||||
*/
|
||||
function isCallbackOfArrayMethod(node) {
|
||||
while (node) {
|
||||
var parent = node.parent;
|
||||
let parent = node.parent;
|
||||
|
||||
switch (parent.type) {
|
||||
|
||||
@@ -123,14 +123,15 @@ function isCallbackOfArrayMethod(node) {
|
||||
// // setup...
|
||||
// return function callback() { ... };
|
||||
// })());
|
||||
case "ReturnStatement":
|
||||
var func = astUtils.getUpperFunction(parent);
|
||||
case "ReturnStatement": {
|
||||
const func = astUtils.getUpperFunction(parent);
|
||||
|
||||
if (func === null || !astUtils.isCallee(func)) {
|
||||
return false;
|
||||
}
|
||||
node = func.parent;
|
||||
break;
|
||||
}
|
||||
|
||||
// e.g.
|
||||
// Array.from([], function() {});
|
||||
@@ -176,7 +177,7 @@ module.exports = {
|
||||
},
|
||||
|
||||
create: function(context) {
|
||||
var funcInfo = {
|
||||
let funcInfo = {
|
||||
upper: null,
|
||||
codePath: null,
|
||||
hasReturn: false,
|
||||
|
||||
@@ -50,11 +50,11 @@ module.exports = {
|
||||
},
|
||||
|
||||
create: function(context) {
|
||||
var options = context.options;
|
||||
var always = options[0] === "always";
|
||||
var asNeeded = !options[0] || options[0] === "as-needed";
|
||||
var never = options[0] === "never";
|
||||
var requireReturnForObjectLiteral = options[1] && options[1].requireReturnForObjectLiteral;
|
||||
let options = context.options;
|
||||
let always = options[0] === "always";
|
||||
let asNeeded = !options[0] || options[0] === "as-needed";
|
||||
let never = options[0] === "never";
|
||||
let requireReturnForObjectLiteral = options[1] && options[1].requireReturnForObjectLiteral;
|
||||
|
||||
/**
|
||||
* Determines whether a arrow function body needs braces
|
||||
@@ -62,7 +62,7 @@ module.exports = {
|
||||
* @returns {void}
|
||||
*/
|
||||
function validate(node) {
|
||||
var arrowBody = node.body;
|
||||
let arrowBody = node.body;
|
||||
|
||||
if (arrowBody.type === "BlockStatement") {
|
||||
if (never) {
|
||||
@@ -72,7 +72,7 @@ module.exports = {
|
||||
message: "Unexpected block statement surrounding arrow body."
|
||||
});
|
||||
} else {
|
||||
var blockBody = arrowBody.body;
|
||||
let blockBody = arrowBody.body;
|
||||
|
||||
if (blockBody.length !== 1) {
|
||||
return;
|
||||
|
||||
@@ -26,11 +26,11 @@ module.exports = {
|
||||
},
|
||||
|
||||
create: function(context) {
|
||||
var message = "Expected parentheses around arrow function argument.";
|
||||
var asNeededMessage = "Unexpected parentheses around single function argument";
|
||||
var asNeeded = context.options[0] === "as-needed";
|
||||
let message = "Expected parentheses around arrow function argument.";
|
||||
let asNeededMessage = "Unexpected parentheses around single function argument.";
|
||||
let asNeeded = context.options[0] === "as-needed";
|
||||
|
||||
var sourceCode = context.getSourceCode();
|
||||
let sourceCode = context.getSourceCode();
|
||||
|
||||
/**
|
||||
* Determines whether a arrow function argument end with `)`
|
||||
@@ -38,7 +38,7 @@ module.exports = {
|
||||
* @returns {void}
|
||||
*/
|
||||
function parens(node) {
|
||||
var token = sourceCode.getFirstToken(node);
|
||||
let token = sourceCode.getFirstToken(node);
|
||||
|
||||
// as-needed: x => x
|
||||
if (asNeeded && node.params.length === 1 && node.params[0].type === "Identifier") {
|
||||
@@ -47,8 +47,8 @@ module.exports = {
|
||||
node: node,
|
||||
message: asNeededMessage,
|
||||
fix: function(fixer) {
|
||||
var paramToken = context.getTokenAfter(token);
|
||||
var closingParenToken = context.getTokenAfter(paramToken);
|
||||
let paramToken = context.getTokenAfter(token);
|
||||
let closingParenToken = context.getTokenAfter(paramToken);
|
||||
|
||||
return fixer.replaceTextRange([
|
||||
token.range[0],
|
||||
@@ -61,7 +61,7 @@ module.exports = {
|
||||
}
|
||||
|
||||
if (token.type === "Identifier") {
|
||||
var after = sourceCode.getTokenAfter(token);
|
||||
let after = sourceCode.getTokenAfter(token);
|
||||
|
||||
// (x) => x
|
||||
if (after.value !== ")") {
|
||||
|
||||
@@ -37,13 +37,13 @@ module.exports = {
|
||||
create: function(context) {
|
||||
|
||||
// merge rules with default
|
||||
var rule = { before: true, after: true },
|
||||
let rule = { before: true, after: true },
|
||||
option = context.options[0] || {};
|
||||
|
||||
rule.before = option.before !== false;
|
||||
rule.after = option.after !== false;
|
||||
|
||||
var sourceCode = context.getSourceCode();
|
||||
let sourceCode = context.getSourceCode();
|
||||
|
||||
/**
|
||||
* Get tokens of arrow(`=>`) and before/after arrow.
|
||||
@@ -51,14 +51,14 @@ module.exports = {
|
||||
* @returns {Object} Tokens of arrow and before/after arrow.
|
||||
*/
|
||||
function getTokens(node) {
|
||||
var t = sourceCode.getFirstToken(node);
|
||||
var before;
|
||||
let t = sourceCode.getFirstToken(node);
|
||||
let before;
|
||||
|
||||
while (t.type !== "Punctuator" || t.value !== "=>") {
|
||||
before = t;
|
||||
t = sourceCode.getTokenAfter(t);
|
||||
}
|
||||
var after = sourceCode.getTokenAfter(t);
|
||||
let after = sourceCode.getTokenAfter(t);
|
||||
|
||||
return { before: before, arrow: t, after: after };
|
||||
}
|
||||
@@ -69,8 +69,8 @@ module.exports = {
|
||||
* @returns {Object} count of space before/after arrow.
|
||||
*/
|
||||
function countSpaces(tokens) {
|
||||
var before = tokens.arrow.range[0] - tokens.before.range[1];
|
||||
var after = tokens.after.range[0] - tokens.arrow.range[1];
|
||||
let before = tokens.arrow.range[0] - tokens.before.range[1];
|
||||
let after = tokens.after.range[0] - tokens.arrow.range[1];
|
||||
|
||||
return { before: before, after: after };
|
||||
}
|
||||
@@ -83,8 +83,8 @@ module.exports = {
|
||||
* @returns {void}
|
||||
*/
|
||||
function spaces(node) {
|
||||
var tokens = getTokens(node);
|
||||
var countSpace = countSpaces(tokens);
|
||||
let tokens = getTokens(node);
|
||||
let countSpace = countSpaces(tokens);
|
||||
|
||||
if (rule.before) {
|
||||
|
||||
@@ -92,7 +92,7 @@ module.exports = {
|
||||
if (countSpace.before === 0) {
|
||||
context.report({
|
||||
node: tokens.before,
|
||||
message: "Missing space before =>",
|
||||
message: "Missing space before =>.",
|
||||
fix: function(fixer) {
|
||||
return fixer.insertTextBefore(tokens.arrow, " ");
|
||||
}
|
||||
@@ -104,7 +104,7 @@ module.exports = {
|
||||
if (countSpace.before > 0) {
|
||||
context.report({
|
||||
node: tokens.before,
|
||||
message: "Unexpected space before =>",
|
||||
message: "Unexpected space before =>.",
|
||||
fix: function(fixer) {
|
||||
return fixer.removeRange([tokens.before.range[1], tokens.arrow.range[0]]);
|
||||
}
|
||||
@@ -118,7 +118,7 @@ module.exports = {
|
||||
if (countSpace.after === 0) {
|
||||
context.report({
|
||||
node: tokens.after,
|
||||
message: "Missing space after =>",
|
||||
message: "Missing space after =>.",
|
||||
fix: function(fixer) {
|
||||
return fixer.insertTextAfter(tokens.arrow, " ");
|
||||
}
|
||||
@@ -130,7 +130,7 @@ module.exports = {
|
||||
if (countSpace.after > 0) {
|
||||
context.report({
|
||||
node: tokens.after,
|
||||
message: "Unexpected space after =>",
|
||||
message: "Unexpected space after =>.",
|
||||
fix: function(fixer) {
|
||||
return fixer.removeRange([tokens.arrow.range[1], tokens.after.range[0]]);
|
||||
}
|
||||
|
||||
@@ -20,7 +20,7 @@ module.exports = {
|
||||
},
|
||||
|
||||
create: function(context) {
|
||||
var stack = [];
|
||||
let stack = [];
|
||||
|
||||
/**
|
||||
* Makes a block scope.
|
||||
@@ -45,7 +45,7 @@ module.exports = {
|
||||
* @returns {void}
|
||||
*/
|
||||
function report(reference) {
|
||||
var identifier = reference.identifier;
|
||||
let identifier = reference.identifier;
|
||||
|
||||
context.report(
|
||||
identifier,
|
||||
@@ -64,7 +64,7 @@ module.exports = {
|
||||
}
|
||||
|
||||
// Defines a predicate to check whether or not a given reference is outside of valid scope.
|
||||
var scopeRange = stack[stack.length - 1];
|
||||
let scopeRange = stack[stack.length - 1];
|
||||
|
||||
/**
|
||||
* Check if a reference is out of scope
|
||||
@@ -73,15 +73,15 @@ module.exports = {
|
||||
* @private
|
||||
*/
|
||||
function isOutsideOfScope(reference) {
|
||||
var idRange = reference.identifier.range;
|
||||
let idRange = reference.identifier.range;
|
||||
|
||||
return idRange[0] < scopeRange[0] || idRange[1] > scopeRange[1];
|
||||
}
|
||||
|
||||
// Gets declared variables, and checks its references.
|
||||
var variables = context.getDeclaredVariables(node);
|
||||
let variables = context.getDeclaredVariables(node);
|
||||
|
||||
for (var i = 0; i < variables.length; ++i) {
|
||||
for (let i = 0; i < variables.length; ++i) {
|
||||
|
||||
// Reports.
|
||||
variables[i]
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
|
||||
"use strict";
|
||||
|
||||
var util = require("../ast-utils");
|
||||
let util = require("../ast-utils");
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Rule Definition
|
||||
@@ -27,7 +27,7 @@ module.exports = {
|
||||
},
|
||||
|
||||
create: function(context) {
|
||||
var always = (context.options[0] !== "never"),
|
||||
let always = (context.options[0] !== "never"),
|
||||
message = always ? "Requires a space" : "Unexpected space(s)",
|
||||
sourceCode = context.getSourceCode();
|
||||
|
||||
@@ -72,10 +72,10 @@ module.exports = {
|
||||
function checkSpacingInsideBraces(node) {
|
||||
|
||||
// Gets braces and the first/last token of content.
|
||||
var openBrace = getOpenBrace(node);
|
||||
var closeBrace = sourceCode.getLastToken(node);
|
||||
var firstToken = sourceCode.getTokenOrCommentAfter(openBrace);
|
||||
var lastToken = sourceCode.getTokenOrCommentBefore(closeBrace);
|
||||
let openBrace = getOpenBrace(node);
|
||||
let closeBrace = sourceCode.getLastToken(node);
|
||||
let firstToken = sourceCode.getTokenOrCommentAfter(openBrace);
|
||||
let lastToken = sourceCode.getTokenOrCommentBefore(closeBrace);
|
||||
|
||||
// Skip if the node is invalid or empty.
|
||||
if (openBrace.type !== "Punctuator" ||
|
||||
|
||||
@@ -34,11 +34,11 @@ module.exports = {
|
||||
},
|
||||
|
||||
create: function(context) {
|
||||
var style = context.options[0] || "1tbs",
|
||||
let style = context.options[0] || "1tbs",
|
||||
params = context.options[1] || {},
|
||||
sourceCode = context.getSourceCode();
|
||||
|
||||
var OPEN_MESSAGE = "Opening curly brace does not appear on the same line as controlling statement.",
|
||||
let OPEN_MESSAGE = "Opening curly brace does not appear on the same line as controlling statement.",
|
||||
OPEN_MESSAGE_ALLMAN = "Opening curly brace appears on the same line as controlling statement.",
|
||||
BODY_MESSAGE = "Statement inside of curly braces should be on next line.",
|
||||
CLOSE_MESSAGE = "Closing curly brace does not appear on the same line as the subsequent block.",
|
||||
@@ -61,7 +61,7 @@ module.exports = {
|
||||
|
||||
/**
|
||||
* Check if the token is an punctuator with a value of curly brace
|
||||
* @param {object} token - Token to check
|
||||
* @param {Object} token - Token to check
|
||||
* @returns {boolean} true if its a curly punctuator
|
||||
* @private
|
||||
*/
|
||||
@@ -78,11 +78,11 @@ module.exports = {
|
||||
* @private
|
||||
*/
|
||||
function checkBlock() {
|
||||
var blockProperties = arguments;
|
||||
let blockProperties = arguments;
|
||||
|
||||
return function(node) {
|
||||
Array.prototype.forEach.call(blockProperties, function(blockProp) {
|
||||
var block = node[blockProp],
|
||||
let block = node[blockProp],
|
||||
previousToken,
|
||||
curlyToken,
|
||||
curlyTokenEnd,
|
||||
@@ -129,7 +129,7 @@ module.exports = {
|
||||
* @private
|
||||
*/
|
||||
function checkIfStatement(node) {
|
||||
var tokens;
|
||||
let tokens;
|
||||
|
||||
checkBlock("consequent", "alternate")(node);
|
||||
|
||||
@@ -157,7 +157,7 @@ module.exports = {
|
||||
* @private
|
||||
*/
|
||||
function checkTryStatement(node) {
|
||||
var tokens;
|
||||
let tokens;
|
||||
|
||||
checkBlock("block", "finalizer")(node);
|
||||
|
||||
@@ -180,7 +180,7 @@ module.exports = {
|
||||
* @private
|
||||
*/
|
||||
function checkCatchClause(node) {
|
||||
var previousToken = sourceCode.getTokenBefore(node),
|
||||
let previousToken = sourceCode.getTokenBefore(node),
|
||||
firstToken = sourceCode.getFirstToken(node);
|
||||
|
||||
checkBlock("body")(node);
|
||||
@@ -205,7 +205,7 @@ module.exports = {
|
||||
* @private
|
||||
*/
|
||||
function checkSwitchStatement(node) {
|
||||
var tokens;
|
||||
let tokens;
|
||||
|
||||
if (node.cases && node.cases.length) {
|
||||
tokens = sourceCode.getTokensBefore(node.cases[0], 2);
|
||||
|
||||
@@ -24,7 +24,7 @@ module.exports = {
|
||||
|
||||
create: function(context) {
|
||||
|
||||
var callbacks = context.options[0] || ["callback", "cb", "next"],
|
||||
let callbacks = context.options[0] || ["callback", "cb", "next"],
|
||||
sourceCode = context.getSourceCode();
|
||||
|
||||
//--------------------------------------------------------------------------
|
||||
@@ -50,7 +50,7 @@ module.exports = {
|
||||
/**
|
||||
* Check to see if a node contains only identifers
|
||||
* @param {ASTNode} node The node to check
|
||||
* @returns {Boolean} Whether or not the node contains only identifers
|
||||
* @returns {boolean} Whether or not the node contains only identifers
|
||||
*/
|
||||
function containsOnlyIdentifiers(node) {
|
||||
if (node.type === "Identifier") {
|
||||
@@ -71,7 +71,7 @@ module.exports = {
|
||||
/**
|
||||
* Check to see if a CallExpression is in our callback list.
|
||||
* @param {ASTNode} node The node to check against our callback names list.
|
||||
* @returns {Boolean} Whether or not this function matches our callback name.
|
||||
* @returns {boolean} Whether or not this function matches our callback name.
|
||||
*/
|
||||
function isCallback(node) {
|
||||
return containsOnlyIdentifiers(node.callee) && callbacks.indexOf(sourceCode.getText(node.callee)) > -1;
|
||||
@@ -118,7 +118,7 @@ module.exports = {
|
||||
}
|
||||
|
||||
// find the closest block, return or loop
|
||||
var closestBlock = findClosestParentOfType(node, ["BlockStatement", "ReturnStatement", "ArrowFunctionExpression"]) || {},
|
||||
let closestBlock = findClosestParentOfType(node, ["BlockStatement", "ReturnStatement", "ArrowFunctionExpression"]) || {},
|
||||
lastItem, parentType;
|
||||
|
||||
// if our parent is a return we know we're ok
|
||||
|
||||
@@ -37,11 +37,11 @@ module.exports = {
|
||||
//--------------------------------------------------------------------------
|
||||
|
||||
// contains reported nodes to avoid reporting twice on destructuring with shorthand notation
|
||||
var reported = [];
|
||||
let reported = [];
|
||||
|
||||
/**
|
||||
* Checks if a string contains an underscore and isn't all upper-case
|
||||
* @param {String} name The string to check.
|
||||
* @param {string} name The string to check.
|
||||
* @returns {boolean} if the string is underscored
|
||||
* @private
|
||||
*/
|
||||
@@ -64,7 +64,7 @@ module.exports = {
|
||||
}
|
||||
}
|
||||
|
||||
var options = context.options[0] || {},
|
||||
let options = context.options[0] || {},
|
||||
properties = options.properties || "";
|
||||
|
||||
if (properties !== "always" && properties !== "never") {
|
||||
@@ -79,7 +79,7 @@ module.exports = {
|
||||
* Leading and trailing underscores are commonly used to flag
|
||||
* private/protected identifiers, strip them
|
||||
*/
|
||||
var name = node.name.replace(/^_+|_+$/g, ""),
|
||||
let name = node.name.replace(/^_+|_+$/g, ""),
|
||||
effectiveParent = (node.parent.type === "MemberExpression") ? node.parent.parent : node.parent;
|
||||
|
||||
// MemberExpressions get special rules
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
// Requirements
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
var lodash = require("lodash");
|
||||
let lodash = require("lodash");
|
||||
|
||||
/**
|
||||
* Checks whether or not a trailing comma is allowed in a given node.
|
||||
@@ -45,9 +45,9 @@ module.exports = {
|
||||
},
|
||||
|
||||
create: function(context) {
|
||||
var mode = context.options[0];
|
||||
var UNEXPECTED_MESSAGE = "Unexpected trailing comma.";
|
||||
var MISSING_MESSAGE = "Missing trailing comma.";
|
||||
let mode = context.options[0];
|
||||
let UNEXPECTED_MESSAGE = "Unexpected trailing comma.";
|
||||
let MISSING_MESSAGE = "Missing trailing comma.";
|
||||
|
||||
/**
|
||||
* Checks whether or not a given node is multiline.
|
||||
@@ -58,13 +58,13 @@ module.exports = {
|
||||
* @returns {boolean} `true` if the node is multiline.
|
||||
*/
|
||||
function isMultiline(node) {
|
||||
var lastItem = lodash.last(node.properties || node.elements || node.specifiers);
|
||||
let lastItem = lodash.last(node.properties || node.elements || node.specifiers);
|
||||
|
||||
if (!lastItem) {
|
||||
return false;
|
||||
}
|
||||
|
||||
var sourceCode = context.getSourceCode(),
|
||||
let sourceCode = context.getSourceCode(),
|
||||
penultimateToken = sourceCode.getLastToken(lastItem),
|
||||
lastToken = sourceCode.getTokenAfter(penultimateToken);
|
||||
|
||||
@@ -91,13 +91,13 @@ module.exports = {
|
||||
* @returns {void}
|
||||
*/
|
||||
function forbidTrailingComma(node) {
|
||||
var lastItem = lodash.last(node.properties || node.elements || node.specifiers);
|
||||
let lastItem = lodash.last(node.properties || node.elements || node.specifiers);
|
||||
|
||||
if (!lastItem || (node.type === "ImportDeclaration" && lastItem.type !== "ImportSpecifier")) {
|
||||
return;
|
||||
}
|
||||
|
||||
var sourceCode = context.getSourceCode(),
|
||||
let sourceCode = context.getSourceCode(),
|
||||
trailingToken;
|
||||
|
||||
// last item can be surrounded by parentheses for object and array literals
|
||||
@@ -132,7 +132,7 @@ module.exports = {
|
||||
* @returns {void}
|
||||
*/
|
||||
function forceTrailingComma(node) {
|
||||
var lastItem = lodash.last(node.properties || node.elements || node.specifiers);
|
||||
let lastItem = lodash.last(node.properties || node.elements || node.specifiers);
|
||||
|
||||
if (!lastItem || (node.type === "ImportDeclaration" && lastItem.type !== "ImportSpecifier")) {
|
||||
return;
|
||||
@@ -142,7 +142,7 @@ module.exports = {
|
||||
return;
|
||||
}
|
||||
|
||||
var sourceCode = context.getSourceCode(),
|
||||
let sourceCode = context.getSourceCode(),
|
||||
penultimateToken = lastItem,
|
||||
trailingToken = sourceCode.getTokenAfter(lastItem);
|
||||
|
||||
@@ -199,7 +199,7 @@ module.exports = {
|
||||
}
|
||||
|
||||
// Chooses a checking function.
|
||||
var checkForTrailingComma;
|
||||
let checkForTrailingComma;
|
||||
|
||||
if (mode === "always") {
|
||||
checkForTrailingComma = forceTrailingComma;
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
*/
|
||||
"use strict";
|
||||
|
||||
var astUtils = require("../ast-utils");
|
||||
let astUtils = require("../ast-utils");
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Rule Definition
|
||||
@@ -38,10 +38,10 @@ module.exports = {
|
||||
|
||||
create: function(context) {
|
||||
|
||||
var sourceCode = context.getSourceCode();
|
||||
var tokensAndComments = sourceCode.tokensAndComments;
|
||||
let sourceCode = context.getSourceCode();
|
||||
let tokensAndComments = sourceCode.tokensAndComments;
|
||||
|
||||
var options = {
|
||||
let options = {
|
||||
before: context.options[0] ? !!context.options[0].before : false,
|
||||
after: context.options[0] ? !!context.options[0].after : true
|
||||
};
|
||||
@@ -51,7 +51,7 @@ module.exports = {
|
||||
//--------------------------------------------------------------------------
|
||||
|
||||
// list of comma tokens to ignore for the check of leading whitespace
|
||||
var commaTokensToIgnore = [];
|
||||
let commaTokensToIgnore = [];
|
||||
|
||||
/**
|
||||
* Determines if a given token is a comma operator.
|
||||
@@ -82,8 +82,8 @@ module.exports = {
|
||||
return fixer.insertTextAfter(node, " ");
|
||||
}
|
||||
} else {
|
||||
var start, end;
|
||||
var newText = "";
|
||||
let start, end;
|
||||
let newText = "";
|
||||
|
||||
if (dir === "before") {
|
||||
start = otherNode.range[1];
|
||||
@@ -136,10 +136,10 @@ module.exports = {
|
||||
* @returns {void}
|
||||
*/
|
||||
function addNullElementsToIgnoreList(node) {
|
||||
var previousToken = sourceCode.getFirstToken(node);
|
||||
let previousToken = sourceCode.getFirstToken(node);
|
||||
|
||||
node.elements.forEach(function(element) {
|
||||
var token;
|
||||
let token;
|
||||
|
||||
if (element === null) {
|
||||
token = sourceCode.getTokenAfter(previousToken);
|
||||
@@ -162,7 +162,7 @@ module.exports = {
|
||||
return {
|
||||
"Program:exit": function() {
|
||||
|
||||
var previousToken,
|
||||
let previousToken,
|
||||
nextToken;
|
||||
|
||||
tokensAndComments.forEach(function(token, i) {
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
|
||||
"use strict";
|
||||
|
||||
var astUtils = require("../ast-utils");
|
||||
let astUtils = require("../ast-utils");
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Rule Definition
|
||||
@@ -39,7 +39,7 @@ module.exports = {
|
||||
},
|
||||
|
||||
create: function(context) {
|
||||
var style = context.options[0] || "last",
|
||||
let style = context.options[0] || "last",
|
||||
exceptions = {},
|
||||
sourceCode = context.getSourceCode();
|
||||
|
||||
@@ -108,7 +108,7 @@ module.exports = {
|
||||
* @returns {void}
|
||||
*/
|
||||
function validateComma(node, property) {
|
||||
var items = node[property],
|
||||
let items = node[property],
|
||||
arrayLiteral = (node.type === "ArrayExpression"),
|
||||
previousItemToken;
|
||||
|
||||
@@ -118,7 +118,7 @@ module.exports = {
|
||||
previousItemToken = sourceCode.getFirstToken(node);
|
||||
|
||||
items.forEach(function(item) {
|
||||
var commaToken = item ? sourceCode.getTokenBefore(item) : previousItemToken,
|
||||
let commaToken = item ? sourceCode.getTokenBefore(item) : previousItemToken,
|
||||
currentItemToken = item ? sourceCode.getFirstToken(item) : sourceCode.getTokenAfter(commaToken),
|
||||
reportItem = item || currentItemToken,
|
||||
tokenBeforeComma = sourceCode.getTokenBefore(commaToken);
|
||||
@@ -158,7 +158,7 @@ module.exports = {
|
||||
*/
|
||||
if (arrayLiteral) {
|
||||
|
||||
var lastToken = sourceCode.getLastToken(node),
|
||||
let lastToken = sourceCode.getLastToken(node),
|
||||
nextToLastToken = sourceCode.getTokenBefore(lastToken);
|
||||
|
||||
if (isComma(nextToLastToken)) {
|
||||
@@ -177,7 +177,7 @@ module.exports = {
|
||||
// Public
|
||||
//--------------------------------------------------------------------------
|
||||
|
||||
var nodes = {};
|
||||
let nodes = {};
|
||||
|
||||
if (!exceptions.VariableDeclaration) {
|
||||
nodes.VariableDeclaration = function(node) {
|
||||
|
||||
@@ -45,7 +45,7 @@ module.exports = {
|
||||
},
|
||||
|
||||
create: function(context) {
|
||||
var option = context.options[0],
|
||||
let option = context.options[0],
|
||||
THRESHOLD = 20;
|
||||
|
||||
if (typeof option === "object" && option.hasOwnProperty("maximum") && typeof option.maximum === "number") {
|
||||
@@ -63,7 +63,7 @@ module.exports = {
|
||||
//--------------------------------------------------------------------------
|
||||
|
||||
// Using a stack to store complexity (handling nested functions)
|
||||
var fns = [];
|
||||
let fns = [];
|
||||
|
||||
/**
|
||||
* When parsing a new function, store it in our function stack
|
||||
@@ -81,7 +81,7 @@ module.exports = {
|
||||
* @private
|
||||
*/
|
||||
function endFunction(node) {
|
||||
var complexity = fns.pop(),
|
||||
let complexity = fns.pop(),
|
||||
name = "anonymous";
|
||||
|
||||
if (node.id) {
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
*/
|
||||
"use strict";
|
||||
|
||||
var astUtils = require("../ast-utils");
|
||||
let astUtils = require("../ast-utils");
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Rule Definition
|
||||
@@ -28,8 +28,8 @@ module.exports = {
|
||||
},
|
||||
|
||||
create: function(context) {
|
||||
var sourceCode = context.getSourceCode();
|
||||
var propertyNameMustBeSpaced = context.options[0] === "always"; // default is "never"
|
||||
let sourceCode = context.getSourceCode();
|
||||
let propertyNameMustBeSpaced = context.options[0] === "always"; // default is "never"
|
||||
|
||||
//--------------------------------------------------------------------------
|
||||
// Helpers
|
||||
@@ -46,7 +46,7 @@ module.exports = {
|
||||
context.report({
|
||||
node: node,
|
||||
loc: token.loc.start,
|
||||
message: "There should be no space after '" + token.value + "'",
|
||||
message: "There should be no space after '" + token.value + "'.",
|
||||
fix: function(fixer) {
|
||||
return fixer.removeRange([token.range[1], tokenAfter.range[0]]);
|
||||
}
|
||||
@@ -64,7 +64,7 @@ module.exports = {
|
||||
context.report({
|
||||
node: node,
|
||||
loc: token.loc.start,
|
||||
message: "There should be no space before '" + token.value + "'",
|
||||
message: "There should be no space before '" + token.value + "'.",
|
||||
fix: function(fixer) {
|
||||
return fixer.removeRange([tokenBefore.range[1], token.range[0]]);
|
||||
}
|
||||
@@ -81,7 +81,7 @@ module.exports = {
|
||||
context.report({
|
||||
node: node,
|
||||
loc: token.loc.start,
|
||||
message: "A space is required after '" + token.value + "'",
|
||||
message: "A space is required after '" + token.value + "'.",
|
||||
fix: function(fixer) {
|
||||
return fixer.insertTextAfter(token, " ");
|
||||
}
|
||||
@@ -98,7 +98,7 @@ module.exports = {
|
||||
context.report({
|
||||
node: node,
|
||||
loc: token.loc.start,
|
||||
message: "A space is required before '" + token.value + "'",
|
||||
message: "A space is required before '" + token.value + "'.",
|
||||
fix: function(fixer) {
|
||||
return fixer.insertTextBefore(token, " ");
|
||||
}
|
||||
@@ -108,7 +108,7 @@ module.exports = {
|
||||
/**
|
||||
* Returns a function that checks the spacing of a node on the property name
|
||||
* that was passed in.
|
||||
* @param {String} propertyName The property on the node to check for spacing
|
||||
* @param {string} propertyName The property on the node to check for spacing
|
||||
* @returns {Function} A function that will check spacing on a node
|
||||
*/
|
||||
function checkSpacing(propertyName) {
|
||||
@@ -117,9 +117,9 @@ module.exports = {
|
||||
return;
|
||||
}
|
||||
|
||||
var property = node[propertyName];
|
||||
let property = node[propertyName];
|
||||
|
||||
var before = sourceCode.getTokenBefore(property),
|
||||
let before = sourceCode.getTokenBefore(property),
|
||||
first = sourceCode.getFirstToken(property),
|
||||
last = sourceCode.getLastToken(property),
|
||||
after = sourceCode.getTokenAfter(property);
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
// Requirements
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
var astUtils = require("../ast-utils");
|
||||
let astUtils = require("../ast-utils");
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Helpers
|
||||
@@ -57,9 +57,9 @@ module.exports = {
|
||||
},
|
||||
|
||||
create: function(context) {
|
||||
var options = context.options[0] || {};
|
||||
var treatUndefinedAsUnspecified = options.treatUndefinedAsUnspecified === true;
|
||||
var funcInfo = null;
|
||||
let options = context.options[0] || {};
|
||||
let treatUndefinedAsUnspecified = options.treatUndefinedAsUnspecified === true;
|
||||
let funcInfo = null;
|
||||
|
||||
/**
|
||||
* Checks whether of not the implicit returning is consistent if the last
|
||||
@@ -69,7 +69,7 @@ module.exports = {
|
||||
* @returns {void}
|
||||
*/
|
||||
function checkLastSegment(node) {
|
||||
var loc, type;
|
||||
let loc, type;
|
||||
|
||||
/*
|
||||
* Skip if it expected no return value or unreachable.
|
||||
@@ -135,8 +135,8 @@ module.exports = {
|
||||
|
||||
// Reports a given return statement if it's inconsistent.
|
||||
ReturnStatement: function(node) {
|
||||
var argument = node.argument;
|
||||
var hasReturnValue = Boolean(argument);
|
||||
let argument = node.argument;
|
||||
let hasReturnValue = Boolean(argument);
|
||||
|
||||
if (treatUndefinedAsUnspecified && hasReturnValue) {
|
||||
hasReturnValue = !isIdentifier(argument, "undefined") && argument.operator !== "void";
|
||||
|
||||
@@ -27,7 +27,7 @@ module.exports = {
|
||||
},
|
||||
|
||||
create: function(context) {
|
||||
var aliases = [];
|
||||
let aliases = [];
|
||||
|
||||
if (context.options.length === 0) {
|
||||
aliases.push("that");
|
||||
@@ -57,7 +57,7 @@ module.exports = {
|
||||
* @returns {void}
|
||||
*/
|
||||
function checkAssignment(node, name, value) {
|
||||
var isThis = value.type === "ThisExpression";
|
||||
let isThis = value.type === "ThisExpression";
|
||||
|
||||
if (aliases.indexOf(name) !== -1) {
|
||||
if (!isThis || node.operator && node.operator !== "=") {
|
||||
@@ -73,12 +73,12 @@ module.exports = {
|
||||
* Ensures that a variable declaration of the alias in a program or function
|
||||
* is assigned to the correct value.
|
||||
* @param {string} alias alias the check the assignment of.
|
||||
* @param {object} scope scope of the current code we are checking.
|
||||
* @param {Object} scope scope of the current code we are checking.
|
||||
* @private
|
||||
* @returns {void}
|
||||
*/
|
||||
function checkWasAssigned(alias, scope) {
|
||||
var variable = scope.set.get(alias);
|
||||
let variable = scope.set.get(alias);
|
||||
|
||||
if (!variable) {
|
||||
return;
|
||||
@@ -94,7 +94,7 @@ module.exports = {
|
||||
// The alias has been declared and not assigned: check it was
|
||||
// assigned later in the same scope.
|
||||
if (!variable.references.some(function(reference) {
|
||||
var write = reference.writeExpr;
|
||||
let write = reference.writeExpr;
|
||||
|
||||
return (
|
||||
reference.from === scope &&
|
||||
@@ -115,7 +115,7 @@ module.exports = {
|
||||
* @returns {void}
|
||||
*/
|
||||
function ensureWasAssigned() {
|
||||
var scope = context.getScope();
|
||||
let scope = context.getScope();
|
||||
|
||||
aliases.forEach(function(alias) {
|
||||
checkWasAssigned(alias, scope);
|
||||
@@ -128,8 +128,8 @@ module.exports = {
|
||||
"FunctionDeclaration:exit": ensureWasAssigned,
|
||||
|
||||
VariableDeclarator: function(node) {
|
||||
var id = node.id;
|
||||
var isDestructuring =
|
||||
let id = node.id;
|
||||
let isDestructuring =
|
||||
id.type === "ArrayPattern" || id.type === "ObjectPattern";
|
||||
|
||||
if (node.init !== null && !isDestructuring) {
|
||||
|
||||
@@ -75,10 +75,11 @@ function isPossibleConstructor(node) {
|
||||
isPossibleConstructor(node.consequent)
|
||||
);
|
||||
|
||||
case "SequenceExpression":
|
||||
var lastExpression = node.expressions[node.expressions.length - 1];
|
||||
case "SequenceExpression": {
|
||||
const lastExpression = node.expressions[node.expressions.length - 1];
|
||||
|
||||
return isPossibleConstructor(lastExpression);
|
||||
}
|
||||
|
||||
default:
|
||||
return false;
|
||||
@@ -111,7 +112,7 @@ module.exports = {
|
||||
* - scope: The scope of own class.
|
||||
* - codePath: The code path object of the constructor.
|
||||
*/
|
||||
var funcInfo = null;
|
||||
let funcInfo = null;
|
||||
|
||||
/*
|
||||
* {Map<string, {calledInSomePaths: boolean, calledInEveryPaths: boolean}>}
|
||||
@@ -120,7 +121,7 @@ module.exports = {
|
||||
* - calledInEveryPaths: A flag of be called `super()` in all code paths.
|
||||
* - validNodes:
|
||||
*/
|
||||
var segInfoMap = Object.create(null);
|
||||
let segInfoMap = Object.create(null);
|
||||
|
||||
/**
|
||||
* Gets the flag which shows `super()` is called in some paths.
|
||||
@@ -163,8 +164,8 @@ module.exports = {
|
||||
if (isConstructorFunction(node)) {
|
||||
|
||||
// Class > ClassBody > MethodDefinition > FunctionExpression
|
||||
var classNode = node.parent.parent.parent;
|
||||
var superClass = classNode.superClass;
|
||||
let classNode = node.parent.parent.parent;
|
||||
let superClass = classNode.superClass;
|
||||
|
||||
funcInfo = {
|
||||
upper: funcInfo,
|
||||
@@ -192,7 +193,7 @@ module.exports = {
|
||||
* @returns {void}
|
||||
*/
|
||||
onCodePathEnd: function(codePath, node) {
|
||||
var hasExtends = funcInfo.hasExtends;
|
||||
let hasExtends = funcInfo.hasExtends;
|
||||
|
||||
// Pop.
|
||||
funcInfo = funcInfo.upper;
|
||||
@@ -202,9 +203,9 @@ module.exports = {
|
||||
}
|
||||
|
||||
// Reports if `super()` lacked.
|
||||
var segments = codePath.returnedSegments;
|
||||
var calledInEveryPaths = segments.every(isCalledInEveryPath);
|
||||
var calledInSomePaths = segments.some(isCalledInSomePath);
|
||||
let segments = codePath.returnedSegments;
|
||||
let calledInEveryPaths = segments.every(isCalledInEveryPath);
|
||||
let calledInSomePaths = segments.some(isCalledInSomePath);
|
||||
|
||||
if (!calledInEveryPaths) {
|
||||
context.report({
|
||||
@@ -227,14 +228,14 @@ module.exports = {
|
||||
}
|
||||
|
||||
// Initialize info.
|
||||
var info = segInfoMap[segment.id] = {
|
||||
let info = segInfoMap[segment.id] = {
|
||||
calledInSomePaths: false,
|
||||
calledInEveryPaths: false,
|
||||
validNodes: []
|
||||
};
|
||||
|
||||
// When there are previous segments, aggregates these.
|
||||
var prevSegments = segment.prevSegments;
|
||||
let prevSegments = segment.prevSegments;
|
||||
|
||||
if (prevSegments.length > 0) {
|
||||
info.calledInSomePaths = prevSegments.some(isCalledInSomePath);
|
||||
@@ -257,13 +258,13 @@ module.exports = {
|
||||
}
|
||||
|
||||
// Update information inside of the loop.
|
||||
var isRealLoop = toSegment.prevSegments.length >= 2;
|
||||
let isRealLoop = toSegment.prevSegments.length >= 2;
|
||||
|
||||
funcInfo.codePath.traverseSegments(
|
||||
{first: toSegment, last: fromSegment},
|
||||
function(segment) {
|
||||
var info = segInfoMap[segment.id];
|
||||
var prevSegments = segment.prevSegments;
|
||||
let info = segInfoMap[segment.id];
|
||||
let prevSegments = segment.prevSegments;
|
||||
|
||||
// Updates flags.
|
||||
info.calledInSomePaths = prevSegments.some(isCalledInSomePath);
|
||||
@@ -271,12 +272,12 @@ module.exports = {
|
||||
|
||||
// If flags become true anew, reports the valid nodes.
|
||||
if (info.calledInSomePaths || isRealLoop) {
|
||||
var nodes = info.validNodes;
|
||||
let nodes = info.validNodes;
|
||||
|
||||
info.validNodes = [];
|
||||
|
||||
for (var i = 0; i < nodes.length; ++i) {
|
||||
var node = nodes[i];
|
||||
for (let i = 0; i < nodes.length; ++i) {
|
||||
let node = nodes[i];
|
||||
|
||||
context.report({
|
||||
message: "Unexpected duplicate 'super()'.",
|
||||
@@ -305,23 +306,22 @@ module.exports = {
|
||||
|
||||
// Reports if needed.
|
||||
if (funcInfo.hasExtends) {
|
||||
var segments = funcInfo.codePath.currentSegments;
|
||||
var reachable = false;
|
||||
var duplicate = false;
|
||||
let segments = funcInfo.codePath.currentSegments;
|
||||
let duplicate = false;
|
||||
let info = null;
|
||||
|
||||
for (var i = 0; i < segments.length; ++i) {
|
||||
var segment = segments[i];
|
||||
for (let i = 0; i < segments.length; ++i) {
|
||||
let segment = segments[i];
|
||||
|
||||
if (segment.reachable) {
|
||||
var info = segInfoMap[segment.id];
|
||||
info = segInfoMap[segment.id];
|
||||
|
||||
reachable = true;
|
||||
duplicate = duplicate || info.calledInSomePaths;
|
||||
info.calledInSomePaths = info.calledInEveryPaths = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (reachable) {
|
||||
if (info) {
|
||||
if (duplicate) {
|
||||
context.report({
|
||||
message: "Unexpected duplicate 'super()'.",
|
||||
@@ -360,13 +360,13 @@ module.exports = {
|
||||
}
|
||||
|
||||
// Returning argument is a substitute of 'super()'.
|
||||
var segments = funcInfo.codePath.currentSegments;
|
||||
let segments = funcInfo.codePath.currentSegments;
|
||||
|
||||
for (var i = 0; i < segments.length; ++i) {
|
||||
var segment = segments[i];
|
||||
for (let i = 0; i < segments.length; ++i) {
|
||||
let segment = segments[i];
|
||||
|
||||
if (segment.reachable) {
|
||||
var info = segInfoMap[segment.id];
|
||||
let info = segInfoMap[segment.id];
|
||||
|
||||
info.calledInSomePaths = info.calledInEveryPaths = true;
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
// Requirements
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
var astUtils = require("../ast-utils");
|
||||
let astUtils = require("../ast-utils");
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Rule Definition
|
||||
@@ -53,12 +53,12 @@ module.exports = {
|
||||
|
||||
create: function(context) {
|
||||
|
||||
var multiOnly = (context.options[0] === "multi");
|
||||
var multiLine = (context.options[0] === "multi-line");
|
||||
var multiOrNest = (context.options[0] === "multi-or-nest");
|
||||
var consistent = (context.options[1] === "consistent");
|
||||
let multiOnly = (context.options[0] === "multi");
|
||||
let multiLine = (context.options[0] === "multi-line");
|
||||
let multiOrNest = (context.options[0] === "multi-or-nest");
|
||||
let consistent = (context.options[1] === "consistent");
|
||||
|
||||
var sourceCode = context.getSourceCode();
|
||||
let sourceCode = context.getSourceCode();
|
||||
|
||||
//--------------------------------------------------------------------------
|
||||
// Helpers
|
||||
@@ -71,7 +71,7 @@ module.exports = {
|
||||
* @private
|
||||
*/
|
||||
function isCollapsedOneLiner(node) {
|
||||
var before = sourceCode.getTokenBefore(node),
|
||||
let before = sourceCode.getTokenBefore(node),
|
||||
last = sourceCode.getLastToken(node);
|
||||
|
||||
return before.loc.start.line === last.loc.end.line;
|
||||
@@ -84,7 +84,7 @@ module.exports = {
|
||||
* @private
|
||||
*/
|
||||
function isOneLiner(node) {
|
||||
var first = sourceCode.getFirstToken(node),
|
||||
let first = sourceCode.getFirstToken(node),
|
||||
last = sourceCode.getLastToken(node);
|
||||
|
||||
return first.loc.start.line === last.loc.end.line;
|
||||
@@ -96,7 +96,7 @@ module.exports = {
|
||||
* @returns {Token} The `else` keyword token.
|
||||
*/
|
||||
function getElseKeyword(node) {
|
||||
var token = sourceCode.getTokenAfter(node.consequent);
|
||||
let token = sourceCode.getTokenAfter(node.consequent);
|
||||
|
||||
while (token.type !== "Keyword" || token.value !== "else") {
|
||||
token = sourceCode.getTokenAfter(token);
|
||||
@@ -180,7 +180,7 @@ module.exports = {
|
||||
* @param {ASTNode} body The body node to check for blocks.
|
||||
* @param {string} name The name to report if there's a problem.
|
||||
* @param {string} suffix Additional string to add to the end of a report.
|
||||
* @returns {object} a prepared check object, with "actual", "expected", "check" properties.
|
||||
* @returns {Object} a prepared check object, with "actual", "expected", "check" properties.
|
||||
* "actual" will be `true` or `false` whether the body is already a block statement.
|
||||
* "expected" will be `true` or `false` if the body should be a block statement or not, or
|
||||
* `null` if it doesn't matter, depending on the rule options. It can be modified to change
|
||||
@@ -189,8 +189,8 @@ module.exports = {
|
||||
* properties.
|
||||
*/
|
||||
function prepareCheck(node, body, name, suffix) {
|
||||
var hasBlock = (body.type === "BlockStatement");
|
||||
var expected = null;
|
||||
let hasBlock = (body.type === "BlockStatement");
|
||||
let expected = null;
|
||||
|
||||
if (node.type === "IfStatement" && node.consequent === body && requiresBraceOfConsequent(node)) {
|
||||
expected = true;
|
||||
@@ -230,11 +230,11 @@ module.exports = {
|
||||
/**
|
||||
* Prepares to check the bodies of a "if", "else if" and "else" chain.
|
||||
* @param {ASTNode} node The first IfStatement node of the chain.
|
||||
* @returns {object[]} prepared checks for each body of the chain. See `prepareCheck` for more
|
||||
* @returns {Object[]} prepared checks for each body of the chain. See `prepareCheck` for more
|
||||
* information.
|
||||
*/
|
||||
function prepareIfChecks(node) {
|
||||
var preparedChecks = [];
|
||||
let preparedChecks = [];
|
||||
|
||||
do {
|
||||
preparedChecks.push(prepareCheck(node, node.consequent, "if", "condition"));
|
||||
@@ -252,7 +252,7 @@ module.exports = {
|
||||
* all have braces.
|
||||
* If all nodes shouldn't have braces, make sure they don't.
|
||||
*/
|
||||
var expected = preparedChecks.some(function(preparedCheck) {
|
||||
let expected = preparedChecks.some(function(preparedCheck) {
|
||||
if (preparedCheck.expected !== null) {
|
||||
return preparedCheck.expected;
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
*/
|
||||
"use strict";
|
||||
|
||||
var DEFAULT_COMMENT_PATTERN = /^no default$/;
|
||||
let DEFAULT_COMMENT_PATTERN = /^no default$/;
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Rule Definition
|
||||
@@ -30,12 +30,12 @@ module.exports = {
|
||||
},
|
||||
|
||||
create: function(context) {
|
||||
var options = context.options[0] || {};
|
||||
var commentPattern = options.commentPattern ?
|
||||
let options = context.options[0] || {};
|
||||
let commentPattern = options.commentPattern ?
|
||||
new RegExp(options.commentPattern) :
|
||||
DEFAULT_COMMENT_PATTERN;
|
||||
|
||||
var sourceCode = context.getSourceCode();
|
||||
let sourceCode = context.getSourceCode();
|
||||
|
||||
//--------------------------------------------------------------------------
|
||||
// Helpers
|
||||
@@ -67,16 +67,16 @@ module.exports = {
|
||||
return;
|
||||
}
|
||||
|
||||
var hasDefault = node.cases.some(function(v) {
|
||||
let hasDefault = node.cases.some(function(v) {
|
||||
return v.test === null;
|
||||
});
|
||||
|
||||
if (!hasDefault) {
|
||||
|
||||
var comment;
|
||||
var comments;
|
||||
let comment;
|
||||
let comments;
|
||||
|
||||
var lastCase = last(node.cases);
|
||||
let lastCase = last(node.cases);
|
||||
|
||||
comments = sourceCode.getComments(lastCase).trailing;
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
|
||||
"use strict";
|
||||
|
||||
var astUtils = require("../ast-utils");
|
||||
let astUtils = require("../ast-utils");
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Rule Definition
|
||||
@@ -28,12 +28,12 @@ module.exports = {
|
||||
|
||||
create: function(context) {
|
||||
|
||||
var config = context.options[0];
|
||||
let config = context.options[0];
|
||||
|
||||
// default to onObject if no preference is passed
|
||||
var onObject = config === "object" || !config;
|
||||
let onObject = config === "object" || !config;
|
||||
|
||||
var sourceCode = context.getSourceCode();
|
||||
let sourceCode = context.getSourceCode();
|
||||
|
||||
/**
|
||||
* Reports if the dot between object and property is on the correct loccation.
|
||||
@@ -43,7 +43,7 @@ module.exports = {
|
||||
* @returns {void}
|
||||
*/
|
||||
function checkDotLocation(obj, prop, node) {
|
||||
var dot = sourceCode.getTokenBefore(prop);
|
||||
let dot = sourceCode.getTokenBefore(prop);
|
||||
|
||||
if (dot.type === "Punctuator" && dot.value === ".") {
|
||||
if (onObject) {
|
||||
|
||||
@@ -8,8 +8,8 @@
|
||||
// Rule Definition
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
var validIdentifier = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/;
|
||||
var keywords = require("../util/keywords");
|
||||
let validIdentifier = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/;
|
||||
let keywords = require("../util/keywords");
|
||||
|
||||
module.exports = {
|
||||
meta: {
|
||||
@@ -36,10 +36,10 @@ module.exports = {
|
||||
},
|
||||
|
||||
create: function(context) {
|
||||
var options = context.options[0] || {};
|
||||
var allowKeywords = options.allowKeywords === void 0 || !!options.allowKeywords;
|
||||
let options = context.options[0] || {};
|
||||
let allowKeywords = options.allowKeywords === void 0 || !!options.allowKeywords;
|
||||
|
||||
var allowPattern;
|
||||
let allowPattern;
|
||||
|
||||
if (options.allowPattern) {
|
||||
allowPattern = new RegExp(options.allowPattern);
|
||||
|
||||
@@ -35,7 +35,7 @@ module.exports = {
|
||||
|
||||
Program: function checkBadEOF(node) {
|
||||
|
||||
var sourceCode = context.getSourceCode(),
|
||||
let sourceCode = context.getSourceCode(),
|
||||
src = sourceCode.getText(),
|
||||
location = {column: 1},
|
||||
linebreakStyle = context.options[0] || "unix",
|
||||
|
||||
@@ -25,7 +25,7 @@ module.exports = {
|
||||
},
|
||||
|
||||
create: function(context) {
|
||||
var sourceCode = context.getSourceCode();
|
||||
let sourceCode = context.getSourceCode();
|
||||
|
||||
/**
|
||||
* Checks if an expression is a typeof expression
|
||||
@@ -71,12 +71,12 @@ module.exports = {
|
||||
/**
|
||||
* Gets the location (line and column) of the binary expression's operator
|
||||
* @param {ASTNode} node The binary expression node to check
|
||||
* @param {String} operator The operator to find
|
||||
* @param {string} operator The operator to find
|
||||
* @returns {Object} { line, column } location of operator
|
||||
* @private
|
||||
*/
|
||||
function getOperatorLocation(node) {
|
||||
var opToken = sourceCode.getTokenAfter(node.left);
|
||||
let opToken = sourceCode.getTokenAfter(node.left);
|
||||
|
||||
return {line: opToken.loc.start.line, column: opToken.loc.start.column};
|
||||
}
|
||||
|
||||
@@ -5,6 +5,15 @@
|
||||
|
||||
"use strict";
|
||||
|
||||
/**
|
||||
* Checks whether or not a given variable is a function name.
|
||||
* @param {escope.Variable} variable - A variable to check.
|
||||
* @returns {boolean} `true` if the variable is a function name.
|
||||
*/
|
||||
function isFunctionName(variable) {
|
||||
return variable && variable.defs[0].type === "FunctionName";
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Rule Definition
|
||||
//------------------------------------------------------------------------------
|
||||
@@ -25,7 +34,7 @@ module.exports = {
|
||||
},
|
||||
|
||||
create: function(context) {
|
||||
var never = context.options[0] === "never";
|
||||
let never = context.options[0] === "never";
|
||||
|
||||
/**
|
||||
* Determines whether the current FunctionExpression node is a get, set, or
|
||||
@@ -33,7 +42,7 @@ module.exports = {
|
||||
* @returns {boolean} True if the node is a get, set, or shorthand method.
|
||||
*/
|
||||
function isObjectOrClassMethod() {
|
||||
var parent = context.getAncestors().pop();
|
||||
let parent = context.getAncestors().pop();
|
||||
|
||||
return (parent.type === "MethodDefinition" || (
|
||||
parent.type === "Property" && (
|
||||
@@ -45,9 +54,16 @@ module.exports = {
|
||||
}
|
||||
|
||||
return {
|
||||
FunctionExpression: function(node) {
|
||||
"FunctionExpression:exit": function(node) {
|
||||
|
||||
var name = node.id && node.id.name;
|
||||
// Skip recursive functions.
|
||||
let nameVar = context.getDeclaredVariables(node)[0];
|
||||
|
||||
if (isFunctionName(nameVar) && nameVar.references.length > 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
let name = node.id && node.id.name;
|
||||
|
||||
if (never) {
|
||||
if (name) {
|
||||
|
||||
@@ -34,12 +34,12 @@ module.exports = {
|
||||
|
||||
create: function(context) {
|
||||
|
||||
var style = context.options[0],
|
||||
let style = context.options[0],
|
||||
allowArrowFunctions = context.options[1] && context.options[1].allowArrowFunctions === true,
|
||||
enforceDeclarations = (style === "declaration"),
|
||||
stack = [];
|
||||
|
||||
var nodesToCheck = {
|
||||
let nodesToCheck = {
|
||||
Program: function() {
|
||||
stack = [];
|
||||
},
|
||||
@@ -79,7 +79,7 @@ module.exports = {
|
||||
};
|
||||
|
||||
nodesToCheck["ArrowFunctionExpression:exit"] = function(node) {
|
||||
var hasThisExpr = stack.pop();
|
||||
let hasThisExpr = stack.pop();
|
||||
|
||||
if (enforceDeclarations && !hasThisExpr && node.parent.type === "VariableDeclarator") {
|
||||
context.report(node.parent, "Expected a function declaration.");
|
||||
|
||||
@@ -40,7 +40,7 @@ module.exports = {
|
||||
|
||||
create: function(context) {
|
||||
|
||||
var mode = (function(option) {
|
||||
let mode = (function(option) {
|
||||
if (!option || typeof option === "string") {
|
||||
return {
|
||||
before: { before: true, after: false },
|
||||
@@ -52,7 +52,7 @@ module.exports = {
|
||||
return option;
|
||||
}(context.options[0]));
|
||||
|
||||
var sourceCode = context.getSourceCode();
|
||||
let sourceCode = context.getSourceCode();
|
||||
|
||||
/**
|
||||
* Gets `*` token from a given node.
|
||||
@@ -63,7 +63,7 @@ module.exports = {
|
||||
* @returns {Token} `*` token.
|
||||
*/
|
||||
function getStarToken(node) {
|
||||
var token = sourceCode.getFirstToken(node);
|
||||
let token = sourceCode.getFirstToken(node);
|
||||
|
||||
while (token.value !== "*") {
|
||||
token = sourceCode.getTokenAfter(token);
|
||||
@@ -83,11 +83,11 @@ module.exports = {
|
||||
*/
|
||||
function checkSpacing(side, leftToken, rightToken) {
|
||||
if (!!(rightToken.range[0] - leftToken.range[1]) !== mode[side]) {
|
||||
var after = leftToken.value === "*";
|
||||
var spaceRequired = mode[side];
|
||||
var node = after ? leftToken : rightToken;
|
||||
var type = spaceRequired ? "Missing" : "Unexpected";
|
||||
var message = type + " space " + side + " *.";
|
||||
let after = leftToken.value === "*";
|
||||
let spaceRequired = mode[side];
|
||||
let node = after ? leftToken : rightToken;
|
||||
let type = spaceRequired ? "Missing" : "Unexpected";
|
||||
let message = type + " space " + side + " *.";
|
||||
|
||||
context.report({
|
||||
node: node,
|
||||
@@ -111,7 +111,7 @@ module.exports = {
|
||||
* @returns {void}
|
||||
*/
|
||||
function checkFunction(node) {
|
||||
var prevToken, starToken, nextToken;
|
||||
let prevToken, starToken, nextToken;
|
||||
|
||||
if (!node.generator) {
|
||||
return;
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
|
||||
"use strict";
|
||||
|
||||
var ACCEPTABLE_PARENTS = [
|
||||
let ACCEPTABLE_PARENTS = [
|
||||
"AssignmentExpression",
|
||||
"VariableDeclarator",
|
||||
"MemberExpression",
|
||||
@@ -23,7 +23,7 @@ var ACCEPTABLE_PARENTS = [
|
||||
* @returns {Reference|null} Returns the found reference or null if none were found.
|
||||
*/
|
||||
function findReference(scope, node) {
|
||||
var references = scope.references.filter(function(reference) {
|
||||
let references = scope.references.filter(function(reference) {
|
||||
return reference.identifier.range[0] === node.range[0] &&
|
||||
reference.identifier.range[1] === node.range[1];
|
||||
});
|
||||
@@ -43,7 +43,7 @@ function findReference(scope, node) {
|
||||
* @returns {boolean} Whether or not the name is shadowed.
|
||||
*/
|
||||
function isShadowed(scope, node) {
|
||||
var reference = findReference(scope, node);
|
||||
let reference = findReference(scope, node);
|
||||
|
||||
return reference && reference.resolved && reference.resolved.defs.length > 0;
|
||||
}
|
||||
@@ -62,7 +62,7 @@ module.exports = {
|
||||
create: function(context) {
|
||||
return {
|
||||
CallExpression: function(node) {
|
||||
var currentScope = context.getScope(),
|
||||
let currentScope = context.getScope(),
|
||||
isGoodRequire;
|
||||
|
||||
if (node.callee.name === "require" && !isShadowed(currentScope, node.callee)) {
|
||||
|
||||
@@ -30,7 +30,7 @@ module.exports = {
|
||||
* If the for-in statement has {}, then the real body is the body
|
||||
* of the BlockStatement. Otherwise, just use body as provided.
|
||||
*/
|
||||
var body = node.body.type === "BlockStatement" ? node.body.body[0] : node.body;
|
||||
let body = node.body.type === "BlockStatement" ? node.body.body[0] : node.body;
|
||||
|
||||
if (body && body.type !== "IfStatement") {
|
||||
context.report(node, "The body of a for-in should be wrapped in an if statement to filter unwanted properties from the prototype.");
|
||||
|
||||
@@ -26,7 +26,7 @@ module.exports = {
|
||||
|
||||
create: function(context) {
|
||||
|
||||
var errorArgument = context.options[0] || "err";
|
||||
let errorArgument = context.options[0] || "err";
|
||||
|
||||
/**
|
||||
* Checks if the given argument should be interpreted as a regexp pattern.
|
||||
@@ -34,7 +34,7 @@ module.exports = {
|
||||
* @returns {boolean} Whether or not the string should be interpreted as a pattern.
|
||||
*/
|
||||
function isPattern(stringToCheck) {
|
||||
var firstChar = stringToCheck[0];
|
||||
let firstChar = stringToCheck[0];
|
||||
|
||||
return firstChar === "^";
|
||||
}
|
||||
@@ -46,7 +46,7 @@ module.exports = {
|
||||
*/
|
||||
function matchesConfiguredErrorName(name) {
|
||||
if (isPattern(errorArgument)) {
|
||||
var regexp = new RegExp(errorArgument);
|
||||
let regexp = new RegExp(errorArgument);
|
||||
|
||||
return regexp.test(name);
|
||||
}
|
||||
@@ -55,7 +55,7 @@ module.exports = {
|
||||
|
||||
/**
|
||||
* Get the parameters of a given function scope.
|
||||
* @param {object} scope The function scope.
|
||||
* @param {Object} scope The function scope.
|
||||
* @returns {array} All parameters of the given scope.
|
||||
*/
|
||||
function getParameters(scope) {
|
||||
@@ -70,7 +70,7 @@ module.exports = {
|
||||
* @returns {void}
|
||||
*/
|
||||
function checkForError(node) {
|
||||
var scope = context.getScope(),
|
||||
let scope = context.getScope(),
|
||||
parameters = getParameters(scope),
|
||||
firstParameter = parameters[0];
|
||||
|
||||
|
||||
@@ -34,12 +34,12 @@ module.exports = {
|
||||
// Helpers
|
||||
//--------------------------------------------------------------------------
|
||||
|
||||
var blacklist = context.options;
|
||||
let blacklist = context.options;
|
||||
|
||||
|
||||
/**
|
||||
* Checks if a string matches the provided pattern
|
||||
* @param {String} name The string to check.
|
||||
* @param {string} name The string to check.
|
||||
* @returns {boolean} if the string is a match
|
||||
* @private
|
||||
*/
|
||||
@@ -51,7 +51,7 @@ module.exports = {
|
||||
* Verifies if we should report an error or not based on the effective
|
||||
* parent node and the identifier name.
|
||||
* @param {ASTNode} effectiveParent The effective parent node of the node to be reported
|
||||
* @param {String} name The identifier name of the identifier node
|
||||
* @param {string} name The identifier name of the identifier node
|
||||
* @returns {boolean} whether an error should be reported or not
|
||||
*/
|
||||
function shouldReport(effectiveParent, name) {
|
||||
@@ -67,7 +67,7 @@ module.exports = {
|
||||
* @private
|
||||
*/
|
||||
function report(node) {
|
||||
context.report(node, "Identifier '{{name}}' is blacklisted", {
|
||||
context.report(node, "Identifier '{{name}}' is blacklisted.", {
|
||||
name: node.name
|
||||
});
|
||||
}
|
||||
@@ -75,7 +75,7 @@ module.exports = {
|
||||
return {
|
||||
|
||||
Identifier: function(node) {
|
||||
var name = node.name,
|
||||
let name = node.name,
|
||||
effectiveParent = (node.parent.type === "MemberExpression") ? node.parent.parent : node.parent;
|
||||
|
||||
// MemberExpressions get special rules
|
||||
|
||||
@@ -45,18 +45,18 @@ module.exports = {
|
||||
},
|
||||
|
||||
create: function(context) {
|
||||
var options = context.options[0] || {};
|
||||
var minLength = typeof options.min !== "undefined" ? options.min : 2;
|
||||
var maxLength = typeof options.max !== "undefined" ? options.max : Infinity;
|
||||
var properties = options.properties !== "never";
|
||||
var exceptions = (options.exceptions ? options.exceptions : [])
|
||||
let options = context.options[0] || {};
|
||||
let minLength = typeof options.min !== "undefined" ? options.min : 2;
|
||||
let maxLength = typeof options.max !== "undefined" ? options.max : Infinity;
|
||||
let properties = options.properties !== "never";
|
||||
let exceptions = (options.exceptions ? options.exceptions : [])
|
||||
.reduce(function(obj, item) {
|
||||
obj[item] = true;
|
||||
|
||||
return obj;
|
||||
}, {});
|
||||
|
||||
var SUPPORTED_EXPRESSIONS = {
|
||||
let SUPPORTED_EXPRESSIONS = {
|
||||
MemberExpression: properties && function(parent) {
|
||||
return !parent.computed && (
|
||||
|
||||
@@ -87,24 +87,24 @@ module.exports = {
|
||||
|
||||
return {
|
||||
Identifier: function(node) {
|
||||
var name = node.name;
|
||||
var parent = node.parent;
|
||||
let name = node.name;
|
||||
let parent = node.parent;
|
||||
|
||||
var isShort = name.length < minLength;
|
||||
var isLong = name.length > maxLength;
|
||||
let isShort = name.length < minLength;
|
||||
let isLong = name.length > maxLength;
|
||||
|
||||
if (!(isShort || isLong) || exceptions[name]) {
|
||||
return; // Nothing to report
|
||||
}
|
||||
|
||||
var isValidExpression = SUPPORTED_EXPRESSIONS[parent.type];
|
||||
let isValidExpression = SUPPORTED_EXPRESSIONS[parent.type];
|
||||
|
||||
if (isValidExpression && (isValidExpression === true || isValidExpression(parent, node))) {
|
||||
context.report(
|
||||
node,
|
||||
isShort ?
|
||||
"Identifier name '{{name}}' is too short. (< {{min}})" :
|
||||
"Identifier name '{{name}}' is too long. (> {{max}})",
|
||||
"Identifier name '{{name}}' is too short (< {{min}})." :
|
||||
"Identifier name '{{name}}' is too long (> {{max}}).",
|
||||
{ name: name, min: minLength, max: maxLength }
|
||||
);
|
||||
}
|
||||
|
||||
@@ -38,16 +38,16 @@ module.exports = {
|
||||
// Helpers
|
||||
//--------------------------------------------------------------------------
|
||||
|
||||
var pattern = context.options[0] || "^.+$",
|
||||
let pattern = context.options[0] || "^.+$",
|
||||
regexp = new RegExp(pattern);
|
||||
|
||||
var options = context.options[1] || {},
|
||||
let options = context.options[1] || {},
|
||||
properties = !!options.properties,
|
||||
onlyDeclarations = !!options.onlyDeclarations;
|
||||
|
||||
/**
|
||||
* Checks if a string matches the provided pattern
|
||||
* @param {String} name The string to check.
|
||||
* @param {string} name The string to check.
|
||||
* @returns {boolean} if the string is a match
|
||||
* @private
|
||||
*/
|
||||
@@ -59,7 +59,7 @@ module.exports = {
|
||||
* Verifies if we should report an error or not based on the effective
|
||||
* parent node and the identifier name.
|
||||
* @param {ASTNode} effectiveParent The effective parent node of the node to be reported
|
||||
* @param {String} name The identifier name of the identifier node
|
||||
* @param {string} name The identifier name of the identifier node
|
||||
* @returns {boolean} whether an error should be reported or not
|
||||
*/
|
||||
function shouldReport(effectiveParent, name) {
|
||||
@@ -84,7 +84,7 @@ module.exports = {
|
||||
return {
|
||||
|
||||
Identifier: function(node) {
|
||||
var name = node.name,
|
||||
let name = node.name,
|
||||
parent = node.parent,
|
||||
effectiveParent = (parent.type === "MemberExpression") ? parent.parent : parent;
|
||||
|
||||
@@ -122,7 +122,7 @@ module.exports = {
|
||||
}
|
||||
|
||||
} else {
|
||||
var isDeclaration = effectiveParent.type === "FunctionDeclaration" || effectiveParent.type === "VariableDeclarator";
|
||||
let isDeclaration = effectiveParent.type === "FunctionDeclaration" || effectiveParent.type === "VariableDeclarator";
|
||||
|
||||
if (onlyDeclarations && !isDeclaration) {
|
||||
return;
|
||||
|
||||
@@ -11,8 +11,8 @@
|
||||
//------------------------------------------------------------------------------
|
||||
// Rule Definition
|
||||
//------------------------------------------------------------------------------
|
||||
var util = require("util");
|
||||
var lodash = require("lodash");
|
||||
let util = require("util");
|
||||
let lodash = require("lodash");
|
||||
|
||||
module.exports = {
|
||||
meta: {
|
||||
@@ -71,6 +71,10 @@ module.exports = {
|
||||
outerIIFEBody: {
|
||||
type: "integer",
|
||||
minimum: 0
|
||||
},
|
||||
MemberExpression: {
|
||||
type: "integer",
|
||||
minimum: 0
|
||||
}
|
||||
},
|
||||
additionalProperties: false
|
||||
@@ -80,12 +84,12 @@ module.exports = {
|
||||
|
||||
create: function(context) {
|
||||
|
||||
var MESSAGE = "Expected indentation of {{needed}} {{type}} {{characters}} but found {{gotten}}.";
|
||||
var DEFAULT_VARIABLE_INDENT = 1;
|
||||
let MESSAGE = "Expected indentation of {{needed}} {{type}} {{characters}} but found {{gotten}}.";
|
||||
let DEFAULT_VARIABLE_INDENT = 1;
|
||||
|
||||
var indentType = "space";
|
||||
var indentSize = 4;
|
||||
var options = {
|
||||
let indentType = "space";
|
||||
let indentSize = 4;
|
||||
let options = {
|
||||
SwitchCase: 0,
|
||||
VariableDeclarator: {
|
||||
var: DEFAULT_VARIABLE_INDENT,
|
||||
@@ -95,7 +99,7 @@ module.exports = {
|
||||
outerIIFEBody: null
|
||||
};
|
||||
|
||||
var sourceCode = context.getSourceCode();
|
||||
let sourceCode = context.getSourceCode();
|
||||
|
||||
if (context.options.length) {
|
||||
if (context.options[0] === "tab") {
|
||||
@@ -107,10 +111,10 @@ module.exports = {
|
||||
}
|
||||
|
||||
if (context.options[1]) {
|
||||
var opts = context.options[1];
|
||||
let opts = context.options[1];
|
||||
|
||||
options.SwitchCase = opts.SwitchCase || 0;
|
||||
var variableDeclaratorRules = opts.VariableDeclarator;
|
||||
let variableDeclaratorRules = opts.VariableDeclarator;
|
||||
|
||||
if (typeof variableDeclaratorRules === "number") {
|
||||
options.VariableDeclarator = {
|
||||
@@ -125,15 +129,19 @@ module.exports = {
|
||||
if (typeof opts.outerIIFEBody === "number") {
|
||||
options.outerIIFEBody = opts.outerIIFEBody;
|
||||
}
|
||||
|
||||
if (typeof opts.MemberExpression === "number") {
|
||||
options.MemberExpression = opts.MemberExpression;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var indentPattern = {
|
||||
let indentPattern = {
|
||||
normal: indentType === "space" ? /^ +/ : /^\t+/,
|
||||
excludeCommas: indentType === "space" ? /^[ ,]+/ : /^[\t,]+/
|
||||
};
|
||||
|
||||
var caseIndentStore = {};
|
||||
let caseIndentStore = {};
|
||||
|
||||
/**
|
||||
* Reports a given indent violation and properly pluralizes the message
|
||||
@@ -145,13 +153,13 @@ module.exports = {
|
||||
* @returns {void}
|
||||
*/
|
||||
function report(node, needed, gotten, loc, isLastNodeCheck) {
|
||||
var msgContext = {
|
||||
let msgContext = {
|
||||
needed: needed,
|
||||
type: indentType,
|
||||
characters: needed === 1 ? "character" : "characters",
|
||||
gotten: gotten
|
||||
};
|
||||
var indentChar = indentType === "space" ? " " : "\t";
|
||||
let indentChar = indentType === "space" ? " " : "\t";
|
||||
|
||||
/**
|
||||
* Responsible for fixing the indentation issue fix
|
||||
@@ -159,10 +167,10 @@ module.exports = {
|
||||
* @private
|
||||
*/
|
||||
function getFixerFunction() {
|
||||
var rangeToFix = [];
|
||||
let rangeToFix = [];
|
||||
|
||||
if (needed > gotten) {
|
||||
var spaces = "" + new Array(needed - gotten + 1).join(indentChar); // replace with repeat in future
|
||||
let spaces = "" + new Array(needed - gotten + 1).join(indentChar); // replace with repeat in future
|
||||
|
||||
if (isLastNodeCheck === true) {
|
||||
rangeToFix = [
|
||||
@@ -224,10 +232,10 @@ module.exports = {
|
||||
* @returns {int} Indent
|
||||
*/
|
||||
function getNodeIndent(node, byLastLine, excludeCommas) {
|
||||
var token = byLastLine ? sourceCode.getLastToken(node) : sourceCode.getFirstToken(node);
|
||||
var src = sourceCode.getText(token, token.loc.start.column);
|
||||
var regExp = excludeCommas ? indentPattern.excludeCommas : indentPattern.normal;
|
||||
var indent = regExp.exec(src);
|
||||
let token = byLastLine ? sourceCode.getLastToken(node) : sourceCode.getFirstToken(node);
|
||||
let src = sourceCode.getText(token, token.loc.start.column);
|
||||
let regExp = excludeCommas ? indentPattern.excludeCommas : indentPattern.normal;
|
||||
let indent = regExp.exec(src);
|
||||
|
||||
return indent ? indent[0].length : 0;
|
||||
}
|
||||
@@ -239,7 +247,7 @@ module.exports = {
|
||||
* @returns {boolean} true if its the first in the its start line
|
||||
*/
|
||||
function isNodeFirstInLine(node, byEndLocation) {
|
||||
var firstToken = byEndLocation === true ? sourceCode.getLastToken(node, 1) : sourceCode.getTokenBefore(node),
|
||||
let firstToken = byEndLocation === true ? sourceCode.getLastToken(node, 1) : sourceCode.getTokenBefore(node),
|
||||
startLine = byEndLocation === true ? node.loc.end.line : node.loc.start.line,
|
||||
endLine = firstToken ? firstToken.loc.end.line : -1;
|
||||
|
||||
@@ -254,7 +262,7 @@ module.exports = {
|
||||
* @returns {void}
|
||||
*/
|
||||
function checkNodeIndent(node, indent, excludeCommas) {
|
||||
var nodeIndent = getNodeIndent(node, false, excludeCommas);
|
||||
let nodeIndent = getNodeIndent(node, false, excludeCommas);
|
||||
|
||||
if (
|
||||
node.type !== "ArrayExpression" && node.type !== "ObjectExpression" &&
|
||||
@@ -274,7 +282,7 @@ module.exports = {
|
||||
function checkNodesIndent(nodes, indent, excludeCommas) {
|
||||
nodes.forEach(function(node) {
|
||||
if (node.type === "IfStatement" && node.alternate) {
|
||||
var elseToken = sourceCode.getTokenBefore(node.alternate);
|
||||
let elseToken = sourceCode.getTokenBefore(node.alternate);
|
||||
|
||||
checkNodeIndent(elseToken, indent, excludeCommas);
|
||||
}
|
||||
@@ -289,8 +297,8 @@ module.exports = {
|
||||
* @returns {void}
|
||||
*/
|
||||
function checkLastNodeLineIndent(node, lastLineIndent) {
|
||||
var lastToken = sourceCode.getLastToken(node);
|
||||
var endIndent = getNodeIndent(lastToken, true);
|
||||
let lastToken = sourceCode.getLastToken(node);
|
||||
let endIndent = getNodeIndent(lastToken, true);
|
||||
|
||||
if (endIndent !== lastLineIndent && isNodeFirstInLine(node, true)) {
|
||||
report(
|
||||
@@ -310,7 +318,7 @@ module.exports = {
|
||||
* @returns {void}
|
||||
*/
|
||||
function checkFirstNodeLineIndent(node, firstLineIndent) {
|
||||
var startIndent = getNodeIndent(node, false);
|
||||
let startIndent = getNodeIndent(node, false);
|
||||
|
||||
if (startIndent !== firstLineIndent && isNodeFirstInLine(node)) {
|
||||
report(
|
||||
@@ -322,6 +330,23 @@ module.exports = {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a parent node of given node based on a specified type
|
||||
* if not present then return null
|
||||
* @param {ASTNode} node node to examine
|
||||
* @param {string} type type that is being looked for
|
||||
* @returns {ASTNode|void} if found then node otherwise null
|
||||
*/
|
||||
function getParentNodeByType(node, type) {
|
||||
let parent = node.parent;
|
||||
|
||||
while (parent.type !== type && parent.type !== "Program") {
|
||||
parent = parent.parent;
|
||||
}
|
||||
|
||||
return parent.type === type ? parent : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the VariableDeclarator based on the current node
|
||||
* if not present then return null
|
||||
@@ -329,13 +354,17 @@ module.exports = {
|
||||
* @returns {ASTNode|void} if found then node otherwise null
|
||||
*/
|
||||
function getVariableDeclaratorNode(node) {
|
||||
var parent = node.parent;
|
||||
return getParentNodeByType(node, "VariableDeclarator");
|
||||
}
|
||||
|
||||
while (parent.type !== "VariableDeclarator" && parent.type !== "Program") {
|
||||
parent = parent.parent;
|
||||
}
|
||||
|
||||
return parent.type === "VariableDeclarator" ? parent : null;
|
||||
/**
|
||||
* Returns the ExpressionStatement based on the current node
|
||||
* if not present then return null
|
||||
* @param {ASTNode} node node to examine
|
||||
* @returns {ASTNode|void} if found then node otherwise null
|
||||
*/
|
||||
function getAssignmentExpressionNode(node) {
|
||||
return getParentNodeByType(node, "AssignmentExpression");
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -358,7 +387,7 @@ module.exports = {
|
||||
* @returns {boolean} True if arguments are multi-line
|
||||
*/
|
||||
function isArgBeforeCalleeNodeMultiline(node) {
|
||||
var parent = node.parent;
|
||||
let parent = node.parent;
|
||||
|
||||
if (parent.arguments.length >= 2 && parent.arguments[1] === node) {
|
||||
return parent.arguments[0].loc.end.line > parent.arguments[0].loc.start.line;
|
||||
@@ -367,19 +396,46 @@ module.exports = {
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
/**
|
||||
* Check to see if the node is a file level IIFE
|
||||
* @param {ASTNode} node The function node to check.
|
||||
* @returns {boolean} True if the node is the outer IIFE
|
||||
*/
|
||||
function isOuterIIFE(node) {
|
||||
var parent = node.parent;
|
||||
let parent = node.parent;
|
||||
let stmt = parent.parent;
|
||||
|
||||
return (
|
||||
parent.type === "CallExpression" &&
|
||||
parent.callee === node &&
|
||||
parent.parent.type === "ExpressionStatement" &&
|
||||
parent.parent.parent && parent.parent.parent.type === "Program"
|
||||
/*
|
||||
* Verify that the node is an IIEF
|
||||
*/
|
||||
if (
|
||||
parent.type !== "CallExpression" ||
|
||||
parent.callee !== node) {
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/*
|
||||
* Navigate legal ancestors to determine whether this IIEF is outer
|
||||
*/
|
||||
while (
|
||||
stmt.type === "UnaryExpression" && (
|
||||
stmt.operator === "!" ||
|
||||
stmt.operator === "~" ||
|
||||
stmt.operator === "+" ||
|
||||
stmt.operator === "-") ||
|
||||
stmt.type === "AssignmentExpression" ||
|
||||
stmt.type === "LogicalExpression" ||
|
||||
stmt.type === "SequenceExpression" ||
|
||||
stmt.type === "VariableDeclarator") {
|
||||
|
||||
stmt = stmt.parent;
|
||||
}
|
||||
|
||||
return ((
|
||||
stmt.type === "ExpressionStatement" ||
|
||||
stmt.type === "VariableDeclaration") &&
|
||||
stmt.parent && stmt.parent.type === "Program"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -403,8 +459,8 @@ module.exports = {
|
||||
*
|
||||
* Looks for 'Models'
|
||||
*/
|
||||
var calleeNode = node.parent; // FunctionExpression
|
||||
var indent;
|
||||
let calleeNode = node.parent; // FunctionExpression
|
||||
let indent;
|
||||
|
||||
if (calleeNode.parent &&
|
||||
(calleeNode.parent.type === "Property" ||
|
||||
@@ -419,7 +475,7 @@ module.exports = {
|
||||
}
|
||||
|
||||
if (calleeNode.parent.type === "CallExpression") {
|
||||
var calleeParent = calleeNode.parent;
|
||||
let calleeParent = calleeNode.parent;
|
||||
|
||||
if (calleeNode.type !== "FunctionExpression" && calleeNode.type !== "ArrowFunctionExpression") {
|
||||
if (calleeParent && calleeParent.loc.start.line < node.loc.start.line) {
|
||||
@@ -436,7 +492,7 @@ module.exports = {
|
||||
|
||||
// function body indent should be indent + indent size, unless this
|
||||
// is the outer IIFE and that option is enabled.
|
||||
var functionOffset = indentSize;
|
||||
let functionOffset = indentSize;
|
||||
|
||||
if (options.outerIIFEBody !== null && isOuterIIFE(calleeNode)) {
|
||||
functionOffset = options.outerIIFEBody * indentSize;
|
||||
@@ -444,7 +500,7 @@ module.exports = {
|
||||
indent += functionOffset;
|
||||
|
||||
// check if the node is inside a variable
|
||||
var parentVarNode = getVariableDeclaratorNode(node);
|
||||
let parentVarNode = getVariableDeclaratorNode(node);
|
||||
|
||||
if (parentVarNode && isNodeInVarOnTop(node, parentVarNode)) {
|
||||
indent += indentSize * options.VariableDeclarator[parentVarNode.parent.kind];
|
||||
@@ -464,7 +520,7 @@ module.exports = {
|
||||
* @returns {boolean} Whether or not the block starts and ends on the same line.
|
||||
*/
|
||||
function isSingleLineNode(node) {
|
||||
var lastToken = sourceCode.getLastToken(node),
|
||||
let lastToken = sourceCode.getLastToken(node),
|
||||
startLine = node.loc.start.line,
|
||||
endLine = lastToken.loc.end.line;
|
||||
|
||||
@@ -497,7 +553,7 @@ module.exports = {
|
||||
return;
|
||||
}
|
||||
|
||||
var elements = (node.type === "ArrayExpression") ? node.elements : node.properties;
|
||||
let elements = (node.type === "ArrayExpression") ? node.elements : node.properties;
|
||||
|
||||
// filter out empty elements example would be [ , 2] so remove first element as espree considers it as null
|
||||
elements = elements.filter(function(elem) {
|
||||
@@ -509,14 +565,14 @@ module.exports = {
|
||||
return;
|
||||
}
|
||||
|
||||
var nodeIndent;
|
||||
var elementsIndent;
|
||||
var parentVarNode = getVariableDeclaratorNode(node);
|
||||
let nodeIndent;
|
||||
let elementsIndent;
|
||||
let parentVarNode = getVariableDeclaratorNode(node);
|
||||
|
||||
// TODO - come up with a better strategy in future
|
||||
if (isNodeFirstInLine(node)) {
|
||||
var parent = node.parent;
|
||||
var effectiveParent = parent;
|
||||
let parent = node.parent;
|
||||
let effectiveParent = parent;
|
||||
|
||||
if (parent.type === "MemberExpression") {
|
||||
if (isNodeFirstInLine(parent)) {
|
||||
@@ -605,14 +661,14 @@ module.exports = {
|
||||
return;
|
||||
}
|
||||
|
||||
var indent;
|
||||
var nodesToCheck = [];
|
||||
let indent;
|
||||
let nodesToCheck = [];
|
||||
|
||||
/*
|
||||
* For this statements we should check indent from statement beginning,
|
||||
* not from the beginning of the block.
|
||||
*/
|
||||
var statementsWithProperties = [
|
||||
let statementsWithProperties = [
|
||||
"IfStatement", "WhileStatement", "ForStatement", "ForInStatement", "ForOfStatement", "DoWhileStatement", "ClassDeclaration"
|
||||
];
|
||||
|
||||
@@ -647,7 +703,7 @@ module.exports = {
|
||||
*/
|
||||
function filterOutSameLineVars(node) {
|
||||
return node.declarations.reduce(function(finalCollection, elem) {
|
||||
var lastElem = finalCollection[finalCollection.length - 1];
|
||||
let lastElem = finalCollection[finalCollection.length - 1];
|
||||
|
||||
if ((elem.loc.start.line !== node.loc.start.line && !lastElem) ||
|
||||
(lastElem && lastElem.loc.start.line !== elem.loc.start.line)) {
|
||||
@@ -664,11 +720,11 @@ module.exports = {
|
||||
* @returns {void}
|
||||
*/
|
||||
function checkIndentInVariableDeclarations(node) {
|
||||
var elements = filterOutSameLineVars(node);
|
||||
var nodeIndent = getNodeIndent(node);
|
||||
var lastElement = elements[elements.length - 1];
|
||||
let elements = filterOutSameLineVars(node);
|
||||
let nodeIndent = getNodeIndent(node);
|
||||
let lastElement = elements[elements.length - 1];
|
||||
|
||||
var elementsIndent = nodeIndent + indentSize * options.VariableDeclarator[node.kind];
|
||||
let elementsIndent = nodeIndent + indentSize * options.VariableDeclarator[node.kind];
|
||||
|
||||
// Comma can be placed before declaration
|
||||
checkNodesIndent(elements, elementsIndent, true);
|
||||
@@ -678,7 +734,7 @@ module.exports = {
|
||||
return;
|
||||
}
|
||||
|
||||
var tokenBeforeLastElement = sourceCode.getTokenBefore(lastElement);
|
||||
let tokenBeforeLastElement = sourceCode.getTokenBefore(lastElement);
|
||||
|
||||
if (tokenBeforeLastElement.value === ",") {
|
||||
|
||||
@@ -708,8 +764,8 @@ module.exports = {
|
||||
* @returns {int} indent size
|
||||
*/
|
||||
function expectedCaseIndent(node, switchIndent) {
|
||||
var switchNode = (node.type === "SwitchStatement") ? node : node.parent;
|
||||
var caseIndent;
|
||||
let switchNode = (node.type === "SwitchStatement") ? node : node.parent;
|
||||
let caseIndent;
|
||||
|
||||
if (caseIndentStore[switchNode.loc.start.line]) {
|
||||
return caseIndentStore[switchNode.loc.start.line];
|
||||
@@ -772,11 +828,45 @@ module.exports = {
|
||||
checkIndentInArrayOrObjectBlock(node);
|
||||
},
|
||||
|
||||
MemberExpression: function(node) {
|
||||
if (typeof options.MemberExpression === "undefined") {
|
||||
return;
|
||||
}
|
||||
|
||||
if (isSingleLineNode(node)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// The typical layout of variable declarations and assignments
|
||||
// alter the expectation of correct indentation. Skip them.
|
||||
// TODO: Add appropriate configuration options for variable
|
||||
// declarations and assignments.
|
||||
if (getVariableDeclaratorNode(node)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (getAssignmentExpressionNode(node)) {
|
||||
return;
|
||||
}
|
||||
|
||||
let propertyIndent = getNodeIndent(node) + indentSize * options.MemberExpression;
|
||||
|
||||
let checkNodes = [node.property];
|
||||
|
||||
let dot = context.getTokenBefore(node.property);
|
||||
|
||||
if (dot.type === "Punctuator" && dot.value === ".") {
|
||||
checkNodes.push(dot);
|
||||
}
|
||||
|
||||
checkNodesIndent(checkNodes, propertyIndent);
|
||||
},
|
||||
|
||||
SwitchStatement: function(node) {
|
||||
|
||||
// Switch is not a 'BlockStatement'
|
||||
var switchIndent = getNodeIndent(node);
|
||||
var caseIndent = expectedCaseIndent(node, switchIndent);
|
||||
let switchIndent = getNodeIndent(node);
|
||||
let caseIndent = expectedCaseIndent(node, switchIndent);
|
||||
|
||||
checkNodesIndent(node.cases, caseIndent);
|
||||
|
||||
@@ -790,7 +880,7 @@ module.exports = {
|
||||
if (isSingleLineNode(node)) {
|
||||
return;
|
||||
}
|
||||
var caseIndent = expectedCaseIndent(node);
|
||||
let caseIndent = expectedCaseIndent(node);
|
||||
|
||||
checkNodesIndent(node.consequent, caseIndent + indentSize);
|
||||
}
|
||||
|
||||
@@ -26,8 +26,8 @@ function isForLoop(block) {
|
||||
* @returns {boolean} `true` when the node has its initializer.
|
||||
*/
|
||||
function isInitialized(node) {
|
||||
var declaration = node.parent;
|
||||
var block = declaration.parent;
|
||||
let declaration = node.parent;
|
||||
let block = declaration.parent;
|
||||
|
||||
if (isForLoop(block)) {
|
||||
if (block.type === "ForStatement") {
|
||||
@@ -87,11 +87,11 @@ module.exports = {
|
||||
|
||||
create: function(context) {
|
||||
|
||||
var MODE_ALWAYS = "always",
|
||||
let MODE_ALWAYS = "always",
|
||||
MODE_NEVER = "never";
|
||||
|
||||
var mode = context.options[0] || MODE_ALWAYS;
|
||||
var params = context.options[1] || {};
|
||||
let mode = context.options[0] || MODE_ALWAYS;
|
||||
let params = context.options[1] || {};
|
||||
|
||||
//--------------------------------------------------------------------------
|
||||
// Public API
|
||||
@@ -100,11 +100,11 @@ module.exports = {
|
||||
return {
|
||||
"VariableDeclaration:exit": function(node) {
|
||||
|
||||
var kind = node.kind,
|
||||
let kind = node.kind,
|
||||
declarations = node.declarations;
|
||||
|
||||
for (var i = 0; i < declarations.length; ++i) {
|
||||
var declaration = declarations[i],
|
||||
for (let i = 0; i < declarations.length; ++i) {
|
||||
let declaration = declarations[i],
|
||||
id = declaration.id,
|
||||
initialized = isInitialized(declaration),
|
||||
isIgnoredForLoop = params.ignoreForLoopInit && isForLoop(node.parent);
|
||||
|
||||
@@ -9,13 +9,13 @@
|
||||
// Requirements
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
var astUtils = require("../ast-utils");
|
||||
let astUtils = require("../ast-utils");
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Constants
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
var QUOTE_SETTINGS = {
|
||||
let QUOTE_SETTINGS = {
|
||||
"prefer-double": {
|
||||
quote: "\"",
|
||||
description: "singlequote",
|
||||
@@ -54,7 +54,7 @@ module.exports = {
|
||||
},
|
||||
|
||||
create: function(context) {
|
||||
var quoteOption = context.options[0] || "prefer-double",
|
||||
let quoteOption = context.options[0] || "prefer-double",
|
||||
setting = QUOTE_SETTINGS[quoteOption];
|
||||
|
||||
/**
|
||||
@@ -69,7 +69,7 @@ module.exports = {
|
||||
|
||||
return {
|
||||
JSXAttribute: function(node) {
|
||||
var attributeValue = node.value;
|
||||
let attributeValue = node.value;
|
||||
|
||||
if (attributeValue && astUtils.isStringLiteral(attributeValue) && !usesExpectedQuotes(attributeValue)) {
|
||||
context.report({
|
||||
|
||||
@@ -34,7 +34,7 @@ function last(arr) {
|
||||
* @returns {boolean} True if the candidate property is part of the group.
|
||||
*/
|
||||
function continuesPropertyGroup(lastMember, candidate) {
|
||||
var groupEndLine = lastMember.loc.start.line,
|
||||
let groupEndLine = lastMember.loc.start.line,
|
||||
candidateStartLine = candidate.loc.start.line,
|
||||
comments, i;
|
||||
|
||||
@@ -71,19 +71,15 @@ function isSingleLine(node) {
|
||||
return (node.loc.end.line === node.loc.start.line);
|
||||
}
|
||||
|
||||
/** Sets option values from the configured options with defaults
|
||||
/**
|
||||
* Initializes a single option property from the configuration with defaults for undefined values
|
||||
* @param {Object} toOptions Object to be initialized
|
||||
* @param {Object} fromOptions Object to be initialized from
|
||||
* @returns {Object} The object with correctly initialized options and values
|
||||
*/
|
||||
function initOptions(toOptions, fromOptions) {
|
||||
function initOptionProperty(toOptions, fromOptions) {
|
||||
toOptions.mode = fromOptions.mode || "strict";
|
||||
|
||||
// Set align if exists - multiLine case
|
||||
if (typeof fromOptions.align !== "undefined") {
|
||||
toOptions.align = fromOptions.align;
|
||||
}
|
||||
|
||||
// Set value of beforeColon
|
||||
if (typeof fromOptions.beforeColon !== "undefined") {
|
||||
toOptions.beforeColon = +fromOptions.beforeColon;
|
||||
@@ -98,6 +94,55 @@ function initOptions(toOptions, fromOptions) {
|
||||
toOptions.afterColon = 1;
|
||||
}
|
||||
|
||||
// Set align if exists
|
||||
if (typeof fromOptions.align !== "undefined") {
|
||||
if (typeof fromOptions.align === "object") {
|
||||
toOptions.align = fromOptions.align;
|
||||
} else { // "string"
|
||||
toOptions.align = {
|
||||
on: fromOptions.align,
|
||||
mode: toOptions.mode,
|
||||
beforeColon: toOptions.beforeColon,
|
||||
afterColon: toOptions.afterColon
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return toOptions;
|
||||
}
|
||||
|
||||
/**
|
||||
* Initializes all the option values (singleLine, multiLine and align) from the configuration with defaults for undefined values
|
||||
* @param {Object} toOptions Object to be initialized
|
||||
* @param {Object} fromOptions Object to be initialized from
|
||||
* @returns {Object} The object with correctly initialized options and values
|
||||
*/
|
||||
function initOptions(toOptions, fromOptions) {
|
||||
if (typeof fromOptions.align === "object") {
|
||||
|
||||
// Initialize the alignment configuration
|
||||
toOptions.align = initOptionProperty({}, fromOptions.align);
|
||||
toOptions.align.on = fromOptions.align.on || "colon";
|
||||
toOptions.align.mode = fromOptions.align.mode || "strict";
|
||||
|
||||
toOptions.multiLine = initOptionProperty({}, (fromOptions.multiLine || fromOptions));
|
||||
toOptions.singleLine = initOptionProperty({}, (fromOptions.singleLine || fromOptions));
|
||||
|
||||
} else { // string or undefined
|
||||
toOptions.multiLine = initOptionProperty({}, (fromOptions.multiLine || fromOptions));
|
||||
toOptions.singleLine = initOptionProperty({}, (fromOptions.singleLine || fromOptions));
|
||||
|
||||
// If alignment options are defined in multiLine, pull them out into the general align configuration
|
||||
if (toOptions.multiLine.align) {
|
||||
toOptions.align = {
|
||||
on: toOptions.multiLine.align.on,
|
||||
mode: toOptions.multiLine.mode,
|
||||
beforeColon: toOptions.multiLine.align.beforeColon,
|
||||
afterColon: toOptions.multiLine.align.afterColon
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return toOptions;
|
||||
}
|
||||
|
||||
@@ -105,7 +150,7 @@ function initOptions(toOptions, fromOptions) {
|
||||
// Rule Definition
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
var messages = {
|
||||
let messages = {
|
||||
key: "{{error}} space after {{computed}}key '{{key}}'.",
|
||||
value: "{{error}} space before value for {{computed}}key '{{key}}'."
|
||||
};
|
||||
@@ -126,7 +171,29 @@ module.exports = {
|
||||
type: "object",
|
||||
properties: {
|
||||
align: {
|
||||
enum: ["colon", "value"]
|
||||
anyOf: [
|
||||
{
|
||||
enum: ["colon", "value"]
|
||||
},
|
||||
{
|
||||
type: "object",
|
||||
properties: {
|
||||
mode: {
|
||||
enum: ["strict", "minimum"]
|
||||
},
|
||||
on: {
|
||||
enum: ["colon", "value"]
|
||||
},
|
||||
beforeColon: {
|
||||
type: "boolean"
|
||||
},
|
||||
afterColon: {
|
||||
type: "boolean"
|
||||
}
|
||||
},
|
||||
additionalProperties: false
|
||||
}
|
||||
]
|
||||
},
|
||||
mode: {
|
||||
enum: ["strict", "minimum"]
|
||||
@@ -162,7 +229,29 @@ module.exports = {
|
||||
type: "object",
|
||||
properties: {
|
||||
align: {
|
||||
enum: ["colon", "value"]
|
||||
anyOf: [
|
||||
{
|
||||
enum: ["colon", "value"]
|
||||
},
|
||||
{
|
||||
type: "object",
|
||||
properties: {
|
||||
mode: {
|
||||
enum: ["strict", "minimum"]
|
||||
},
|
||||
on: {
|
||||
enum: ["colon", "value"]
|
||||
},
|
||||
beforeColon: {
|
||||
type: "boolean"
|
||||
},
|
||||
afterColon: {
|
||||
type: "boolean"
|
||||
}
|
||||
},
|
||||
additionalProperties: false
|
||||
}
|
||||
]
|
||||
},
|
||||
mode: {
|
||||
enum: ["strict", "minimum"]
|
||||
@@ -178,6 +267,57 @@ module.exports = {
|
||||
}
|
||||
},
|
||||
additionalProperties: false
|
||||
},
|
||||
{
|
||||
type: "object",
|
||||
properties: {
|
||||
singleLine: {
|
||||
type: "object",
|
||||
properties: {
|
||||
mode: {
|
||||
enum: ["strict", "minimum"]
|
||||
},
|
||||
beforeColon: {
|
||||
type: "boolean"
|
||||
},
|
||||
afterColon: {
|
||||
type: "boolean"
|
||||
}
|
||||
},
|
||||
additionalProperties: false
|
||||
},
|
||||
multiLine: {
|
||||
type: "object",
|
||||
properties: {
|
||||
beforeColon: {
|
||||
type: "boolean"
|
||||
},
|
||||
afterColon: {
|
||||
type: "boolean"
|
||||
}
|
||||
},
|
||||
additionalProperties: false
|
||||
},
|
||||
align: {
|
||||
type: "object",
|
||||
properties: {
|
||||
mode: {
|
||||
enum: ["strict", "minimum"]
|
||||
},
|
||||
on: {
|
||||
enum: ["colon", "value"]
|
||||
},
|
||||
beforeColon: {
|
||||
type: "boolean"
|
||||
},
|
||||
afterColon: {
|
||||
type: "boolean"
|
||||
}
|
||||
},
|
||||
additionalProperties: false
|
||||
}
|
||||
},
|
||||
additionalProperties: false
|
||||
}
|
||||
]
|
||||
}]
|
||||
@@ -193,17 +333,18 @@ module.exports = {
|
||||
* align: "colon" // Optional, or "value"
|
||||
* }
|
||||
*/
|
||||
let options = context.options[0] || {},
|
||||
ruleOptions = initOptions({}, options),
|
||||
multiLineOptions = ruleOptions.multiLine,
|
||||
singleLineOptions = ruleOptions.singleLine,
|
||||
alignmentOptions = ruleOptions.align || null;
|
||||
|
||||
var options = context.options[0] || {},
|
||||
multiLineOptions = initOptions({}, (options.multiLine || options)),
|
||||
singleLineOptions = initOptions({}, (options.singleLine || options));
|
||||
|
||||
var sourceCode = context.getSourceCode();
|
||||
let sourceCode = context.getSourceCode();
|
||||
|
||||
/**
|
||||
* Determines if the given property is key-value property.
|
||||
* @param {ASTNode} property Property node to check.
|
||||
* @returns {Boolean} Whether the property is a key-value property.
|
||||
* @returns {boolean} Whether the property is a key-value property.
|
||||
*/
|
||||
function isKeyValueProperty(property) {
|
||||
return !(
|
||||
@@ -220,7 +361,7 @@ module.exports = {
|
||||
* @returns {ASTNode} The last token before a colon punctuator.
|
||||
*/
|
||||
function getLastTokenBeforeColon(node) {
|
||||
var prevNode;
|
||||
let prevNode;
|
||||
|
||||
while (node && (node.type !== "Punctuator" || node.value !== ":")) {
|
||||
prevNode = node;
|
||||
@@ -251,7 +392,7 @@ module.exports = {
|
||||
* @returns {string} The property's key.
|
||||
*/
|
||||
function getKey(property) {
|
||||
var key = property.key;
|
||||
let key = property.key;
|
||||
|
||||
if (property.computed) {
|
||||
return sourceCode.getText().slice(key.range[0], key.range[1]);
|
||||
@@ -271,7 +412,7 @@ module.exports = {
|
||||
* @returns {void}
|
||||
*/
|
||||
function report(property, side, whitespace, expected, mode) {
|
||||
var diff = whitespace.length - expected,
|
||||
let diff = whitespace.length - expected,
|
||||
nextColon = getNextColon(property.key),
|
||||
tokenBeforeColon = sourceCode.getTokenBefore(nextColon),
|
||||
tokenAfterColon = sourceCode.getTokenAfter(nextColon),
|
||||
@@ -335,7 +476,7 @@ module.exports = {
|
||||
* @returns {int} Width of the key.
|
||||
*/
|
||||
function getKeyWidth(property) {
|
||||
var startToken, endToken;
|
||||
let startToken, endToken;
|
||||
|
||||
startToken = sourceCode.getFirstToken(property);
|
||||
endToken = getLastTokenBeforeColon(property.key);
|
||||
@@ -349,7 +490,7 @@ module.exports = {
|
||||
* @returns {Object} Whitespace before and after the property's colon.
|
||||
*/
|
||||
function getPropertyWhitespace(property) {
|
||||
var whitespace = /(\s*):(\s*)/.exec(sourceCode.getText().slice(
|
||||
let whitespace = /(\s*):(\s*)/.exec(sourceCode.getText().slice(
|
||||
property.key.range[1], property.value.range[0]
|
||||
));
|
||||
|
||||
@@ -373,7 +514,7 @@ module.exports = {
|
||||
}
|
||||
|
||||
return node.properties.reduce(function(groups, property) {
|
||||
var currentGroup = last(groups),
|
||||
let currentGroup = last(groups),
|
||||
prev = last(currentGroup);
|
||||
|
||||
if (!prev || continuesPropertyGroup(prev, property)) {
|
||||
@@ -394,14 +535,22 @@ module.exports = {
|
||||
* @returns {void}
|
||||
*/
|
||||
function verifyGroupAlignment(properties) {
|
||||
var length = properties.length,
|
||||
let length = properties.length,
|
||||
widths = properties.map(getKeyWidth), // Width of keys, including quotes
|
||||
targetWidth = Math.max.apply(null, widths),
|
||||
align = alignmentOptions.on, // "value" or "colon"
|
||||
i, property, whitespace, width,
|
||||
align = multiLineOptions.align,
|
||||
beforeColon = multiLineOptions.beforeColon,
|
||||
afterColon = multiLineOptions.afterColon,
|
||||
mode = multiLineOptions.mode;
|
||||
beforeColon, afterColon, mode;
|
||||
|
||||
if (alignmentOptions && length > 1) { // When aligning values within a group, use the alignment configuration.
|
||||
beforeColon = alignmentOptions.beforeColon;
|
||||
afterColon = alignmentOptions.afterColon;
|
||||
mode = alignmentOptions.mode;
|
||||
} else {
|
||||
beforeColon = multiLineOptions.beforeColon;
|
||||
afterColon = multiLineOptions.afterColon;
|
||||
mode = alignmentOptions.mode;
|
||||
}
|
||||
|
||||
// Conditionally include one space before or after colon
|
||||
targetWidth += (align === "colon" ? beforeColon : afterColon);
|
||||
@@ -441,7 +590,7 @@ module.exports = {
|
||||
* @returns {void}
|
||||
*/
|
||||
function verifySpacing(node, lineOptions) {
|
||||
var actual = getPropertyWhitespace(node);
|
||||
let actual = getPropertyWhitespace(node);
|
||||
|
||||
if (actual) { // Object literal getters/setters lack colons
|
||||
report(node, "key", actual.beforeColon, lineOptions.beforeColon, lineOptions.mode);
|
||||
@@ -455,9 +604,9 @@ module.exports = {
|
||||
* @returns {void}
|
||||
*/
|
||||
function verifyListSpacing(properties) {
|
||||
var length = properties.length;
|
||||
let length = properties.length;
|
||||
|
||||
for (var i = 0; i < length; i++) {
|
||||
for (let i = 0; i < length; i++) {
|
||||
verifySpacing(properties[i], singleLineOptions);
|
||||
}
|
||||
}
|
||||
@@ -466,7 +615,7 @@ module.exports = {
|
||||
// Public API
|
||||
//--------------------------------------------------------------------------
|
||||
|
||||
if (multiLineOptions.align) { // Verify vertical alignment
|
||||
if (alignmentOptions) { // Verify vertical alignment
|
||||
|
||||
return {
|
||||
ObjectExpression: function(node) {
|
||||
|
||||
@@ -9,26 +9,26 @@
|
||||
// Requirements
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
var astUtils = require("../ast-utils"),
|
||||
let astUtils = require("../ast-utils"),
|
||||
keywords = require("../util/keywords");
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Constants
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
var PREV_TOKEN = /^[\)\]\}>]$/;
|
||||
var NEXT_TOKEN = /^(?:[\(\[\{<~!]|\+\+?|--?)$/;
|
||||
var PREV_TOKEN_M = /^[\)\]\}>*]$/;
|
||||
var NEXT_TOKEN_M = /^[\{*]$/;
|
||||
var TEMPLATE_OPEN_PAREN = /\$\{$/;
|
||||
var TEMPLATE_CLOSE_PAREN = /^\}/;
|
||||
var CHECK_TYPE = /^(?:JSXElement|RegularExpression|String|Template)$/;
|
||||
var KEYS = keywords.concat(["as", "await", "from", "get", "let", "of", "set", "yield"]);
|
||||
let PREV_TOKEN = /^[\)\]\}>]$/;
|
||||
let NEXT_TOKEN = /^(?:[\(\[\{<~!]|\+\+?|--?)$/;
|
||||
let PREV_TOKEN_M = /^[\)\]\}>*]$/;
|
||||
let NEXT_TOKEN_M = /^[\{*]$/;
|
||||
let TEMPLATE_OPEN_PAREN = /\$\{$/;
|
||||
let TEMPLATE_CLOSE_PAREN = /^\}/;
|
||||
let CHECK_TYPE = /^(?:JSXElement|RegularExpression|String|Template)$/;
|
||||
let KEYS = keywords.concat(["as", "await", "from", "get", "let", "of", "set", "yield"]);
|
||||
|
||||
// check duplications.
|
||||
(function() {
|
||||
KEYS.sort();
|
||||
for (var i = 1; i < KEYS.length; ++i) {
|
||||
for (let i = 1; i < KEYS.length; ++i) {
|
||||
if (KEYS[i] === KEYS[i - 1]) {
|
||||
throw new Error("Duplication was found in the keyword list: " + KEYS[i]);
|
||||
}
|
||||
@@ -101,7 +101,7 @@ module.exports = {
|
||||
},
|
||||
|
||||
create: function(context) {
|
||||
var sourceCode = context.getSourceCode();
|
||||
let sourceCode = context.getSourceCode();
|
||||
|
||||
/**
|
||||
* Reports a given token if there are not space(s) before the token.
|
||||
@@ -114,7 +114,7 @@ module.exports = {
|
||||
function expectSpaceBefore(token, pattern) {
|
||||
pattern = pattern || PREV_TOKEN;
|
||||
|
||||
var prevToken = sourceCode.getTokenBefore(token);
|
||||
let prevToken = sourceCode.getTokenBefore(token);
|
||||
|
||||
if (prevToken &&
|
||||
(CHECK_TYPE.test(prevToken.type) || pattern.test(prevToken.value)) &&
|
||||
@@ -144,7 +144,7 @@ module.exports = {
|
||||
function unexpectSpaceBefore(token, pattern) {
|
||||
pattern = pattern || PREV_TOKEN;
|
||||
|
||||
var prevToken = sourceCode.getTokenBefore(token);
|
||||
let prevToken = sourceCode.getTokenBefore(token);
|
||||
|
||||
if (prevToken &&
|
||||
(CHECK_TYPE.test(prevToken.type) || pattern.test(prevToken.value)) &&
|
||||
@@ -174,7 +174,7 @@ module.exports = {
|
||||
function expectSpaceAfter(token, pattern) {
|
||||
pattern = pattern || NEXT_TOKEN;
|
||||
|
||||
var nextToken = sourceCode.getTokenAfter(token);
|
||||
let nextToken = sourceCode.getTokenAfter(token);
|
||||
|
||||
if (nextToken &&
|
||||
(CHECK_TYPE.test(nextToken.type) || pattern.test(nextToken.value)) &&
|
||||
@@ -204,7 +204,7 @@ module.exports = {
|
||||
function unexpectSpaceAfter(token, pattern) {
|
||||
pattern = pattern || NEXT_TOKEN;
|
||||
|
||||
var nextToken = sourceCode.getTokenAfter(token);
|
||||
let nextToken = sourceCode.getTokenAfter(token);
|
||||
|
||||
if (nextToken &&
|
||||
(CHECK_TYPE.test(nextToken.type) || pattern.test(nextToken.value)) &&
|
||||
@@ -226,28 +226,28 @@ module.exports = {
|
||||
/**
|
||||
* Parses the option object and determines check methods for each keyword.
|
||||
*
|
||||
* @param {object|undefined} options - The option object to parse.
|
||||
* @returns {object} - Normalized option object.
|
||||
* @param {Object|undefined} options - The option object to parse.
|
||||
* @returns {Object} - Normalized option object.
|
||||
* Keys are keywords (there are for every keyword).
|
||||
* Values are instances of `{"before": function, "after": function}`.
|
||||
*/
|
||||
function parseOptions(options) {
|
||||
var before = !options || options.before !== false;
|
||||
var after = !options || options.after !== false;
|
||||
var defaultValue = {
|
||||
let before = !options || options.before !== false;
|
||||
let after = !options || options.after !== false;
|
||||
let defaultValue = {
|
||||
before: before ? expectSpaceBefore : unexpectSpaceBefore,
|
||||
after: after ? expectSpaceAfter : unexpectSpaceAfter
|
||||
};
|
||||
var overrides = (options && options.overrides) || {};
|
||||
var retv = Object.create(null);
|
||||
let overrides = (options && options.overrides) || {};
|
||||
let retv = Object.create(null);
|
||||
|
||||
for (var i = 0; i < KEYS.length; ++i) {
|
||||
var key = KEYS[i];
|
||||
var override = overrides[key];
|
||||
for (let i = 0; i < KEYS.length; ++i) {
|
||||
let key = KEYS[i];
|
||||
let override = overrides[key];
|
||||
|
||||
if (override) {
|
||||
var thisBefore = ("before" in override) ? override.before : before;
|
||||
var thisAfter = ("after" in override) ? override.after : after;
|
||||
let thisBefore = ("before" in override) ? override.before : before;
|
||||
let thisAfter = ("after" in override) ? override.after : after;
|
||||
|
||||
retv[key] = {
|
||||
before: thisBefore ? expectSpaceBefore : unexpectSpaceBefore,
|
||||
@@ -261,7 +261,7 @@ module.exports = {
|
||||
return retv;
|
||||
}
|
||||
|
||||
var checkMethodMap = parseOptions(context.options[0]);
|
||||
let checkMethodMap = parseOptions(context.options[0]);
|
||||
|
||||
/**
|
||||
* Reports a given token if usage of spacing followed by the token is
|
||||
@@ -308,7 +308,7 @@ module.exports = {
|
||||
* @returns {void}
|
||||
*/
|
||||
function checkSpacingAroundFirstToken(node) {
|
||||
var firstToken = node && sourceCode.getFirstToken(node);
|
||||
let firstToken = node && sourceCode.getFirstToken(node);
|
||||
|
||||
if (firstToken && firstToken.type === "Keyword") {
|
||||
checkSpacingAround(firstToken);
|
||||
@@ -326,7 +326,7 @@ module.exports = {
|
||||
* @returns {void}
|
||||
*/
|
||||
function checkSpacingBeforeFirstToken(node) {
|
||||
var firstToken = node && sourceCode.getFirstToken(node);
|
||||
let firstToken = node && sourceCode.getFirstToken(node);
|
||||
|
||||
if (firstToken && firstToken.type === "Keyword") {
|
||||
checkSpacingBefore(firstToken);
|
||||
@@ -342,7 +342,7 @@ module.exports = {
|
||||
*/
|
||||
function checkSpacingAroundTokenBefore(node) {
|
||||
if (node) {
|
||||
var token = sourceCode.getTokenBefore(node);
|
||||
let token = sourceCode.getTokenBefore(node);
|
||||
|
||||
while (token.type !== "Keyword") {
|
||||
token = sourceCode.getTokenBefore(token);
|
||||
@@ -424,7 +424,7 @@ module.exports = {
|
||||
checkSpacingAroundFirstToken(node);
|
||||
|
||||
// `of` is not a keyword token.
|
||||
var token = sourceCode.getTokenBefore(node.right);
|
||||
let token = sourceCode.getTokenBefore(node.right);
|
||||
|
||||
while (token.value !== "of") {
|
||||
token = sourceCode.getTokenBefore(token);
|
||||
@@ -445,13 +445,13 @@ module.exports = {
|
||||
* @returns {void}
|
||||
*/
|
||||
function checkSpacingForModuleDeclaration(node) {
|
||||
var firstToken = sourceCode.getFirstToken(node);
|
||||
let firstToken = sourceCode.getFirstToken(node);
|
||||
|
||||
checkSpacingBefore(firstToken, PREV_TOKEN_M);
|
||||
checkSpacingAfter(firstToken, NEXT_TOKEN_M);
|
||||
|
||||
if (node.source) {
|
||||
var fromToken = sourceCode.getTokenBefore(node.source);
|
||||
let fromToken = sourceCode.getTokenBefore(node.source);
|
||||
|
||||
checkSpacingBefore(fromToken, PREV_TOKEN_M);
|
||||
checkSpacingAfter(fromToken, NEXT_TOKEN_M);
|
||||
@@ -466,7 +466,7 @@ module.exports = {
|
||||
* @returns {void}
|
||||
*/
|
||||
function checkSpacingForImportNamespaceSpecifier(node) {
|
||||
var asToken = sourceCode.getFirstToken(node, 1);
|
||||
let asToken = sourceCode.getFirstToken(node, 1);
|
||||
|
||||
checkSpacingBefore(asToken, PREV_TOKEN_M);
|
||||
}
|
||||
@@ -483,7 +483,7 @@ module.exports = {
|
||||
checkSpacingAroundFirstToken(node);
|
||||
}
|
||||
if (node.kind === "get" || node.kind === "set") {
|
||||
var token = sourceCode.getFirstToken(
|
||||
let token = sourceCode.getFirstToken(
|
||||
node,
|
||||
node.static ? 1 : 0
|
||||
);
|
||||
|
||||
@@ -28,10 +28,10 @@ module.exports = {
|
||||
|
||||
create: function(context) {
|
||||
|
||||
var EXPECTED_LF_MSG = "Expected linebreaks to be 'LF' but found 'CRLF'.",
|
||||
let EXPECTED_LF_MSG = "Expected linebreaks to be 'LF' but found 'CRLF'.",
|
||||
EXPECTED_CRLF_MSG = "Expected linebreaks to be 'CRLF' but found 'LF'.";
|
||||
|
||||
var sourceCode = context.getSourceCode();
|
||||
let sourceCode = context.getSourceCode();
|
||||
|
||||
//--------------------------------------------------------------------------
|
||||
// Helpers
|
||||
@@ -41,7 +41,7 @@ module.exports = {
|
||||
* Builds a fix function that replaces text at the specified range in the source text.
|
||||
* @param {int[]} range The range to replace
|
||||
* @param {string} text The text to insert.
|
||||
* @returns {function} Fixer function
|
||||
* @returns {Function} Fixer function
|
||||
* @private
|
||||
*/
|
||||
function createFix(range, text) {
|
||||
@@ -56,7 +56,7 @@ module.exports = {
|
||||
|
||||
return {
|
||||
Program: function checkForlinebreakStyle(node) {
|
||||
var linebreakStyle = context.options[0] || "unix",
|
||||
let linebreakStyle = context.options[0] || "unix",
|
||||
expectedLF = linebreakStyle === "unix",
|
||||
expectedLFChars = expectedLF ? "\n" : "\r\n",
|
||||
source = sourceCode.getText(),
|
||||
@@ -65,7 +65,7 @@ module.exports = {
|
||||
index,
|
||||
range;
|
||||
|
||||
var i = 0;
|
||||
let i = 0;
|
||||
|
||||
while ((match = pattern.exec(source)) !== null) {
|
||||
i++;
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
// Requirements
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
var lodash = require("lodash"),
|
||||
let lodash = require("lodash"),
|
||||
astUtils = require("../ast-utils");
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
@@ -21,7 +21,7 @@ var lodash = require("lodash"),
|
||||
* @returns {Array} An array of line numbers.
|
||||
*/
|
||||
function getEmptyLineNums(lines) {
|
||||
var emptyLines = lines.map(function(line, i) {
|
||||
let emptyLines = lines.map(function(line, i) {
|
||||
return {
|
||||
code: line.trim(),
|
||||
num: i + 1
|
||||
@@ -41,11 +41,11 @@ function getEmptyLineNums(lines) {
|
||||
* @returns {Array} An array of line numbers.
|
||||
*/
|
||||
function getCommentLineNums(comments) {
|
||||
var lines = [];
|
||||
let lines = [];
|
||||
|
||||
comments.forEach(function(token) {
|
||||
var start = token.loc.start.line;
|
||||
var end = token.loc.end.line;
|
||||
let start = token.loc.start.line;
|
||||
let end = token.loc.end.line;
|
||||
|
||||
lines.push(start, end);
|
||||
});
|
||||
@@ -108,7 +108,7 @@ module.exports = {
|
||||
|
||||
create: function(context) {
|
||||
|
||||
var options = context.options[0] ? lodash.assign({}, context.options[0]) : {};
|
||||
let options = context.options[0] ? lodash.assign({}, context.options[0]) : {};
|
||||
|
||||
options.beforeLineComment = options.beforeLineComment || false;
|
||||
options.afterLineComment = options.afterLineComment || false;
|
||||
@@ -117,9 +117,9 @@ module.exports = {
|
||||
options.allowBlockStart = options.allowBlockStart || false;
|
||||
options.allowBlockEnd = options.allowBlockEnd || false;
|
||||
|
||||
var sourceCode = context.getSourceCode();
|
||||
let sourceCode = context.getSourceCode();
|
||||
|
||||
var lines = sourceCode.lines,
|
||||
let lines = sourceCode.lines,
|
||||
numLines = lines.length + 1,
|
||||
comments = sourceCode.getAllComments(),
|
||||
commentLines = getCommentLineNums(comments),
|
||||
@@ -141,7 +141,7 @@ module.exports = {
|
||||
* @returns {boolean} True if the comment is not alone.
|
||||
*/
|
||||
function codeAroundComment(node) {
|
||||
var token;
|
||||
let token;
|
||||
|
||||
token = node;
|
||||
do {
|
||||
@@ -184,8 +184,8 @@ module.exports = {
|
||||
* @returns {boolean} True if the comment is at parent start.
|
||||
*/
|
||||
function isCommentAtParentStart(node, nodeType) {
|
||||
var ancestors = context.getAncestors();
|
||||
var parent;
|
||||
let ancestors = context.getAncestors();
|
||||
let parent;
|
||||
|
||||
if (ancestors.length) {
|
||||
parent = ancestors.pop();
|
||||
@@ -202,8 +202,8 @@ module.exports = {
|
||||
* @returns {boolean} True if the comment is at parent end.
|
||||
*/
|
||||
function isCommentAtParentEnd(node, nodeType) {
|
||||
var ancestors = context.getAncestors();
|
||||
var parent;
|
||||
let ancestors = context.getAncestors();
|
||||
let parent;
|
||||
|
||||
if (ancestors.length) {
|
||||
parent = ancestors.pop();
|
||||
@@ -271,27 +271,27 @@ module.exports = {
|
||||
* Checks if a comment node has lines around it (ignores inline comments)
|
||||
* @param {ASTNode} node The Comment node.
|
||||
* @param {Object} opts Options to determine the newline.
|
||||
* @param {Boolean} opts.after Should have a newline after this line.
|
||||
* @param {Boolean} opts.before Should have a newline before this line.
|
||||
* @param {boolean} opts.after Should have a newline after this line.
|
||||
* @param {boolean} opts.before Should have a newline before this line.
|
||||
* @returns {void}
|
||||
*/
|
||||
function checkForEmptyLine(node, opts) {
|
||||
var after = opts.after,
|
||||
let after = opts.after,
|
||||
before = opts.before;
|
||||
|
||||
var prevLineNum = node.loc.start.line - 1,
|
||||
let prevLineNum = node.loc.start.line - 1,
|
||||
nextLineNum = node.loc.end.line + 1,
|
||||
commentIsNotAlone = codeAroundComment(node);
|
||||
|
||||
var blockStartAllowed = options.allowBlockStart && isCommentAtBlockStart(node),
|
||||
let blockStartAllowed = options.allowBlockStart && isCommentAtBlockStart(node),
|
||||
blockEndAllowed = options.allowBlockEnd && isCommentAtBlockEnd(node),
|
||||
objectStartAllowed = options.allowObjectStart && isCommentAtObjectStart(node),
|
||||
objectEndAllowed = options.allowObjectEnd && isCommentAtObjectEnd(node),
|
||||
arrayStartAllowed = options.allowArrayStart && isCommentAtArrayStart(node),
|
||||
arrayEndAllowed = options.allowArrayEnd && isCommentAtArrayEnd(node);
|
||||
|
||||
var exceptionStartAllowed = blockStartAllowed || objectStartAllowed || arrayStartAllowed;
|
||||
var exceptionEndAllowed = blockEndAllowed || objectEndAllowed || arrayEndAllowed;
|
||||
let exceptionStartAllowed = blockStartAllowed || objectStartAllowed || arrayStartAllowed;
|
||||
let exceptionEndAllowed = blockEndAllowed || objectEndAllowed || arrayEndAllowed;
|
||||
|
||||
// ignore top of the file and bottom of the file
|
||||
if (prevLineNum < 1) {
|
||||
@@ -306,14 +306,14 @@ module.exports = {
|
||||
return;
|
||||
}
|
||||
|
||||
var previousTokenOrComment = sourceCode.getTokenOrCommentBefore(node);
|
||||
var nextTokenOrComment = sourceCode.getTokenOrCommentAfter(node);
|
||||
let previousTokenOrComment = sourceCode.getTokenOrCommentBefore(node);
|
||||
let nextTokenOrComment = sourceCode.getTokenOrCommentAfter(node);
|
||||
|
||||
// check for newline before
|
||||
if (!exceptionStartAllowed && before && !lodash.includes(commentAndEmptyLines, prevLineNum) &&
|
||||
!(isCommentNodeType(previousTokenOrComment) && astUtils.isTokenOnSameLine(previousTokenOrComment, node))) {
|
||||
var lineStart = node.range[0] - node.loc.start.column;
|
||||
var range = [lineStart, lineStart];
|
||||
let lineStart = node.range[0] - node.loc.start.column;
|
||||
let range = [lineStart, lineStart];
|
||||
|
||||
context.report({
|
||||
node: node,
|
||||
|
||||
@@ -49,7 +49,7 @@ module.exports = {
|
||||
// Helpers
|
||||
//--------------------------------------------------------------------------
|
||||
|
||||
var functionStack = [],
|
||||
let functionStack = [],
|
||||
option = context.options[0],
|
||||
maxDepth = 4;
|
||||
|
||||
@@ -88,7 +88,7 @@ module.exports = {
|
||||
* @private
|
||||
*/
|
||||
function pushBlock(node) {
|
||||
var len = ++functionStack[functionStack.length - 1];
|
||||
let len = ++functionStack[functionStack.length - 1];
|
||||
|
||||
if (len > maxDepth) {
|
||||
context.report(node, "Blocks are nested too deeply ({{depth}}).",
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
// Constants
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
var OPTIONS_SCHEMA = {
|
||||
let OPTIONS_SCHEMA = {
|
||||
type: "object",
|
||||
properties: {
|
||||
code: {
|
||||
@@ -40,7 +40,7 @@ var OPTIONS_SCHEMA = {
|
||||
additionalProperties: false
|
||||
};
|
||||
|
||||
var OPTIONS_OR_INTEGER_SCHEMA = {
|
||||
let OPTIONS_OR_INTEGER_SCHEMA = {
|
||||
anyOf: [
|
||||
OPTIONS_SCHEMA,
|
||||
{
|
||||
@@ -79,9 +79,9 @@ module.exports = {
|
||||
* too many false positives
|
||||
* - We don't care about matching the entire URL, any small segment is fine
|
||||
*/
|
||||
var URL_REGEXP = /[^:/?#]:\/\/[^?#]/;
|
||||
let URL_REGEXP = /[^:/?#]:\/\/[^?#]/;
|
||||
|
||||
var sourceCode = context.getSourceCode();
|
||||
let sourceCode = context.getSourceCode();
|
||||
|
||||
/**
|
||||
* Computes the length of a line that may contain tabs. The width of each
|
||||
@@ -92,10 +92,10 @@ module.exports = {
|
||||
* @private
|
||||
*/
|
||||
function computeLineLength(line, tabWidth) {
|
||||
var extraCharacterCount = 0;
|
||||
let extraCharacterCount = 0;
|
||||
|
||||
line.replace(/\t/g, function(match, offset) {
|
||||
var totalOffset = offset + extraCharacterCount,
|
||||
let totalOffset = offset + extraCharacterCount,
|
||||
previousTabStopOffset = tabWidth ? totalOffset % tabWidth : 0,
|
||||
spaceCount = tabWidth - previousTabStopOffset;
|
||||
|
||||
@@ -105,8 +105,8 @@ module.exports = {
|
||||
}
|
||||
|
||||
// The options object must be the last option specified…
|
||||
var lastOption = context.options[context.options.length - 1];
|
||||
var options = typeof lastOption === "object" ? Object.create(lastOption) : {};
|
||||
let lastOption = context.options[context.options.length - 1];
|
||||
let options = typeof lastOption === "object" ? Object.create(lastOption) : {};
|
||||
|
||||
// …but max code length…
|
||||
if (typeof context.options[0] === "number") {
|
||||
@@ -118,7 +118,7 @@ module.exports = {
|
||||
options.tabWidth = context.options[1];
|
||||
}
|
||||
|
||||
var maxLength = options.code || 80,
|
||||
let maxLength = options.code || 80,
|
||||
tabWidth = options.tabWidth || 4,
|
||||
ignorePattern = options.ignorePattern || null,
|
||||
ignoreComments = options.ignoreComments || false,
|
||||
@@ -156,7 +156,7 @@ module.exports = {
|
||||
* @returns {boolean} If the comment covers the entire line
|
||||
*/
|
||||
function isFullLineComment(line, lineNumber, comment) {
|
||||
var start = comment.loc.start,
|
||||
let start = comment.loc.start,
|
||||
end = comment.loc.end,
|
||||
isFirstTokenOnLine = !line.slice(0, comment.loc.start.column).trim();
|
||||
|
||||
@@ -188,7 +188,7 @@ module.exports = {
|
||||
function checkProgramForMaxLength(node) {
|
||||
|
||||
// split (honors line-ending)
|
||||
var lines = sourceCode.lines,
|
||||
let lines = sourceCode.lines,
|
||||
|
||||
// list of comments to ignore
|
||||
comments = ignoreComments || maxCommentLength || ignoreTrailingComments ? sourceCode.getAllComments() : [],
|
||||
@@ -199,23 +199,24 @@ module.exports = {
|
||||
lines.forEach(function(line, i) {
|
||||
|
||||
// i is zero-indexed, line numbers are one-indexed
|
||||
var lineNumber = i + 1;
|
||||
let lineNumber = i + 1;
|
||||
|
||||
/*
|
||||
* if we're checking comment length; we need to know whether this
|
||||
* line is a comment
|
||||
*/
|
||||
var lineIsComment = false;
|
||||
let lineIsComment = false;
|
||||
|
||||
/*
|
||||
* We can short-circuit the comment checks if we're already out of
|
||||
* comments to check.
|
||||
*/
|
||||
if (commentsIndex < comments.length) {
|
||||
let comment = null;
|
||||
|
||||
// iterate over comments until we find one past the current line
|
||||
do {
|
||||
var comment = comments[++commentsIndex];
|
||||
comment = comments[++commentsIndex];
|
||||
} while (comment && comment.loc.start.line <= lineNumber);
|
||||
|
||||
// and step back by one
|
||||
@@ -234,7 +235,7 @@ module.exports = {
|
||||
return;
|
||||
}
|
||||
|
||||
var lineLength = computeLineLength(line, tabWidth);
|
||||
let lineLength = computeLineLength(line, tabWidth);
|
||||
|
||||
if (lineIsComment && ignoreComments) {
|
||||
return;
|
||||
|
||||
@@ -8,8 +8,8 @@
|
||||
// Requirements
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
var lodash = require("lodash");
|
||||
var astUtils = require("../ast-utils");
|
||||
let lodash = require("lodash");
|
||||
let astUtils = require("../ast-utils");
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Rule Definition
|
||||
@@ -52,7 +52,7 @@ module.exports = {
|
||||
},
|
||||
|
||||
create: function(context) {
|
||||
var option = context.options[0],
|
||||
let option = context.options[0],
|
||||
max = 300;
|
||||
|
||||
if (typeof option === "object" && option.hasOwnProperty("max") && typeof option.max === "number") {
|
||||
@@ -63,10 +63,10 @@ module.exports = {
|
||||
max = option;
|
||||
}
|
||||
|
||||
var skipComments = option && option.skipComments;
|
||||
var skipBlankLines = option && option.skipBlankLines;
|
||||
let skipComments = option && option.skipComments;
|
||||
let skipBlankLines = option && option.skipBlankLines;
|
||||
|
||||
var sourceCode = context.getSourceCode();
|
||||
let sourceCode = context.getSourceCode();
|
||||
|
||||
/**
|
||||
* Returns whether or not a token is a comment node type
|
||||
@@ -83,10 +83,10 @@ module.exports = {
|
||||
* @returns {int[]} The line numbers
|
||||
*/
|
||||
function getLinesWithoutCode(comment) {
|
||||
var start = comment.loc.start.line;
|
||||
var end = comment.loc.end.line;
|
||||
let start = comment.loc.start.line;
|
||||
let end = comment.loc.end.line;
|
||||
|
||||
var token;
|
||||
let token;
|
||||
|
||||
token = comment;
|
||||
do {
|
||||
@@ -114,7 +114,7 @@ module.exports = {
|
||||
|
||||
return {
|
||||
"Program:exit": function() {
|
||||
var lines = sourceCode.lines.map(function(text, i) {
|
||||
let lines = sourceCode.lines.map(function(text, i) {
|
||||
return { lineNumber: i + 1, text: text };
|
||||
});
|
||||
|
||||
@@ -125,9 +125,9 @@ module.exports = {
|
||||
}
|
||||
|
||||
if (skipComments) {
|
||||
var comments = sourceCode.getAllComments();
|
||||
let comments = sourceCode.getAllComments();
|
||||
|
||||
var commentLines = lodash.flatten(comments.map(function(comment) {
|
||||
let commentLines = lodash.flatten(comments.map(function(comment) {
|
||||
return getLinesWithoutCode(comment);
|
||||
}));
|
||||
|
||||
@@ -139,7 +139,7 @@ module.exports = {
|
||||
if (lines.length > max) {
|
||||
context.report({
|
||||
loc: { line: 1, column: 0 },
|
||||
message: "File must be at most " + max + " lines long"
|
||||
message: "File must be at most " + max + " lines long."
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -48,7 +48,7 @@ module.exports = {
|
||||
//--------------------------------------------------------------------------
|
||||
// Constants
|
||||
//--------------------------------------------------------------------------
|
||||
var option = context.options[0],
|
||||
let option = context.options[0],
|
||||
THRESHOLD = 10;
|
||||
|
||||
if (typeof option === "object" && option.hasOwnProperty("maximum") && typeof option.maximum === "number") {
|
||||
@@ -65,7 +65,7 @@ module.exports = {
|
||||
// Helpers
|
||||
//--------------------------------------------------------------------------
|
||||
|
||||
var callbackStack = [];
|
||||
let callbackStack = [];
|
||||
|
||||
/**
|
||||
* Checks a given function node for too many callbacks.
|
||||
@@ -74,14 +74,14 @@ module.exports = {
|
||||
* @private
|
||||
*/
|
||||
function checkFunction(node) {
|
||||
var parent = node.parent;
|
||||
let parent = node.parent;
|
||||
|
||||
if (parent.type === "CallExpression") {
|
||||
callbackStack.push(node);
|
||||
}
|
||||
|
||||
if (callbackStack.length > THRESHOLD) {
|
||||
var opts = {num: callbackStack.length, max: THRESHOLD};
|
||||
let opts = {num: callbackStack.length, max: THRESHOLD};
|
||||
|
||||
context.report(node, "Too many nested callbacks ({{num}}). Maximum allowed is {{max}}.", opts);
|
||||
}
|
||||
|
||||
@@ -45,7 +45,7 @@ module.exports = {
|
||||
|
||||
create: function(context) {
|
||||
|
||||
var option = context.options[0],
|
||||
let option = context.options[0],
|
||||
numParams = 3;
|
||||
|
||||
if (typeof option === "object" && option.hasOwnProperty("maximum") && typeof option.maximum === "number") {
|
||||
|
||||
@@ -32,7 +32,7 @@ module.exports = {
|
||||
|
||||
create: function(context) {
|
||||
|
||||
var sourceCode = context.getSourceCode(),
|
||||
let sourceCode = context.getSourceCode(),
|
||||
options = context.options[0] || {},
|
||||
lastStatementLine = 0,
|
||||
numberOfStatementsOnThisLine = 0,
|
||||
@@ -43,7 +43,7 @@ module.exports = {
|
||||
// Helpers
|
||||
//--------------------------------------------------------------------------
|
||||
|
||||
var SINGLE_CHILD_ALLOWED = /^(?:(?:DoWhile|For|ForIn|ForOf|If|Labeled|While)Statement|Export(?:Default|Named)Declaration)$/;
|
||||
let SINGLE_CHILD_ALLOWED = /^(?:(?:DoWhile|For|ForIn|ForOf|If|Labeled|While)Statement|Export(?:Default|Named)Declaration)$/;
|
||||
|
||||
/**
|
||||
* Gets the actual last token of a given node.
|
||||
@@ -52,7 +52,7 @@ module.exports = {
|
||||
* @returns {Token} The actual last token.
|
||||
*/
|
||||
function getActualLastToken(node) {
|
||||
var lastToken = sourceCode.getLastToken(node);
|
||||
let lastToken = sourceCode.getLastToken(node);
|
||||
|
||||
if (lastToken.value === ";") {
|
||||
lastToken = sourceCode.getTokenBefore(lastToken);
|
||||
@@ -68,7 +68,7 @@ module.exports = {
|
||||
* @returns {void}
|
||||
*/
|
||||
function enterStatement(node) {
|
||||
var line = node.loc.start.line;
|
||||
let line = node.loc.start.line;
|
||||
|
||||
// Skip to allow non-block statements if this is direct child of control statements.
|
||||
// `if (a) foo();` is counted as 1.
|
||||
@@ -100,7 +100,7 @@ module.exports = {
|
||||
* @returns {void}
|
||||
*/
|
||||
function leaveStatement(node) {
|
||||
var line = getActualLastToken(node).loc.end.line;
|
||||
let line = getActualLastToken(node).loc.end.line;
|
||||
|
||||
// Update state.
|
||||
if (line !== lastStatementLine) {
|
||||
|
||||
@@ -58,7 +58,7 @@ module.exports = {
|
||||
// Helpers
|
||||
//--------------------------------------------------------------------------
|
||||
|
||||
var functionStack = [],
|
||||
let functionStack = [],
|
||||
option = context.options[0],
|
||||
maxStatements = 10,
|
||||
ignoreTopLevelFunctions = context.options[1] && context.options[1].ignoreTopLevelFunctions || false,
|
||||
@@ -107,7 +107,7 @@ module.exports = {
|
||||
* @private
|
||||
*/
|
||||
function endFunction(node) {
|
||||
var count = functionStack.pop();
|
||||
let count = functionStack.pop();
|
||||
|
||||
if (ignoreTopLevelFunctions && functionStack.length === 0) {
|
||||
topLevelFunctions.push({ node: node, count: count});
|
||||
@@ -147,8 +147,8 @@ module.exports = {
|
||||
}
|
||||
|
||||
topLevelFunctions.forEach(function(element) {
|
||||
var count = element.count;
|
||||
var node = element.node;
|
||||
let count = element.count;
|
||||
let node = element.node;
|
||||
|
||||
reportIfTooManyStatements(node, count, maxStatements);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
/**
|
||||
* @fileoverview Enforce newlines between operands of ternary expressions
|
||||
* @author Kai Cataldo
|
||||
*/
|
||||
|
||||
"use strict";
|
||||
|
||||
let astUtils = require("../ast-utils");
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Rule Definition
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
module.exports = {
|
||||
meta: {
|
||||
docs: {
|
||||
description: "enforce newlines between operands of ternary expressions",
|
||||
category: "Stylistic Issues",
|
||||
recommended: false
|
||||
},
|
||||
schema: []
|
||||
},
|
||||
|
||||
create: function(context) {
|
||||
|
||||
//--------------------------------------------------------------------------
|
||||
// Helpers
|
||||
//--------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Tests whether node is preceded by supplied tokens
|
||||
* @param {ASTNode} node - node to check
|
||||
* @param {ASTNode} parentNode - parent of node to report
|
||||
* @returns {void}
|
||||
* @private
|
||||
*/
|
||||
function reportError(node, parentNode) {
|
||||
context.report({
|
||||
node: node,
|
||||
message: "Expected newline between {{typeOfError}} of ternary expression.",
|
||||
data: {
|
||||
typeOfError: node === parentNode.test ? "test and consequent" : "consequent and alternate"
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
//--------------------------------------------------------------------------
|
||||
// Public
|
||||
//--------------------------------------------------------------------------
|
||||
|
||||
return {
|
||||
ConditionalExpression: function(node) {
|
||||
let areTestAndConsequentOnSameLine = astUtils.isTokenOnSameLine(node.test, node.consequent);
|
||||
let areConsequentAndAlternateOnSameLine = astUtils.isTokenOnSameLine(node.consequent, node.alternate);
|
||||
|
||||
if (areTestAndConsequentOnSameLine) {
|
||||
reportError(node.test, node);
|
||||
}
|
||||
|
||||
if (areConsequentAndAlternateOnSameLine) {
|
||||
reportError(node.consequent, node);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
};
|
||||
@@ -9,13 +9,13 @@
|
||||
// Requirements
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
var lodash = require("lodash");
|
||||
let lodash = require("lodash");
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Helpers
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
var CAPS_ALLOWED = [
|
||||
let CAPS_ALLOWED = [
|
||||
"Array",
|
||||
"Boolean",
|
||||
"Date",
|
||||
@@ -61,7 +61,7 @@ function invert(map, key) {
|
||||
* @returns {Object} Object with cap is new exceptions.
|
||||
*/
|
||||
function calculateCapIsNewExceptions(config) {
|
||||
var capIsNewExceptions = checkArray(config, "capIsNewExceptions", CAPS_ALLOWED);
|
||||
let capIsNewExceptions = checkArray(config, "capIsNewExceptions", CAPS_ALLOWED);
|
||||
|
||||
if (capIsNewExceptions !== CAPS_ALLOWED) {
|
||||
capIsNewExceptions = capIsNewExceptions.concat(CAPS_ALLOWED);
|
||||
@@ -115,19 +115,19 @@ module.exports = {
|
||||
|
||||
create: function(context) {
|
||||
|
||||
var config = context.options[0] ? lodash.assign({}, context.options[0]) : {};
|
||||
let config = context.options[0] ? lodash.assign({}, context.options[0]) : {};
|
||||
|
||||
config.newIsCap = config.newIsCap !== false;
|
||||
config.capIsNew = config.capIsNew !== false;
|
||||
var skipProperties = config.properties === false;
|
||||
let skipProperties = config.properties === false;
|
||||
|
||||
var newIsCapExceptions = checkArray(config, "newIsCapExceptions", []).reduce(invert, {});
|
||||
let newIsCapExceptions = checkArray(config, "newIsCapExceptions", []).reduce(invert, {});
|
||||
|
||||
var capIsNewExceptions = calculateCapIsNewExceptions(config);
|
||||
let capIsNewExceptions = calculateCapIsNewExceptions(config);
|
||||
|
||||
var listeners = {};
|
||||
let listeners = {};
|
||||
|
||||
var sourceCode = context.getSourceCode();
|
||||
let sourceCode = context.getSourceCode();
|
||||
|
||||
//--------------------------------------------------------------------------
|
||||
// Helpers
|
||||
@@ -140,7 +140,7 @@ module.exports = {
|
||||
*/
|
||||
function extractNameFromExpression(node) {
|
||||
|
||||
var name = "",
|
||||
let name = "",
|
||||
property;
|
||||
|
||||
if (node.callee.type === "MemberExpression") {
|
||||
@@ -164,10 +164,10 @@ module.exports = {
|
||||
* @returns {string} capitalization state: "non-alpha", "lower", or "upper"
|
||||
*/
|
||||
function getCap(str) {
|
||||
var firstChar = str.charAt(0);
|
||||
let firstChar = str.charAt(0);
|
||||
|
||||
var firstCharLower = firstChar.toLowerCase();
|
||||
var firstCharUpper = firstChar.toUpperCase();
|
||||
let firstCharLower = firstChar.toLowerCase();
|
||||
let firstCharUpper = firstChar.toUpperCase();
|
||||
|
||||
if (firstCharLower === firstCharUpper) {
|
||||
|
||||
@@ -185,7 +185,7 @@ module.exports = {
|
||||
* @param {Object} allowedMap Object mapping calleeName to a Boolean
|
||||
* @param {ASTNode} node CallExpression node
|
||||
* @param {string} calleeName Capitalized callee name from a CallExpression
|
||||
* @returns {Boolean} Returns true if the callee may be capitalized
|
||||
* @returns {boolean} Returns true if the callee may be capitalized
|
||||
*/
|
||||
function isCapAllowed(allowedMap, node, calleeName) {
|
||||
if (allowedMap[calleeName] || allowedMap[sourceCode.getText(node.callee)]) {
|
||||
@@ -209,7 +209,7 @@ module.exports = {
|
||||
* @returns {void}
|
||||
*/
|
||||
function report(node, message) {
|
||||
var callee = node.callee;
|
||||
let callee = node.callee;
|
||||
|
||||
if (callee.type === "MemberExpression") {
|
||||
callee = callee.property;
|
||||
@@ -225,11 +225,11 @@ module.exports = {
|
||||
if (config.newIsCap) {
|
||||
listeners.NewExpression = function(node) {
|
||||
|
||||
var constructorName = extractNameFromExpression(node);
|
||||
let constructorName = extractNameFromExpression(node);
|
||||
|
||||
if (constructorName) {
|
||||
var capitalization = getCap(constructorName);
|
||||
var isAllowed = capitalization !== "lower" || isCapAllowed(newIsCapExceptions, node, constructorName);
|
||||
let capitalization = getCap(constructorName);
|
||||
let isAllowed = capitalization !== "lower" || isCapAllowed(newIsCapExceptions, node, constructorName);
|
||||
|
||||
if (!isAllowed) {
|
||||
report(node, "A constructor name should not start with a lowercase letter.");
|
||||
@@ -241,11 +241,11 @@ module.exports = {
|
||||
if (config.capIsNew) {
|
||||
listeners.CallExpression = function(node) {
|
||||
|
||||
var calleeName = extractNameFromExpression(node);
|
||||
let calleeName = extractNameFromExpression(node);
|
||||
|
||||
if (calleeName) {
|
||||
var capitalization = getCap(calleeName);
|
||||
var isAllowed = capitalization !== "upper" || isCapAllowed(capIsNewExceptions, node, calleeName);
|
||||
let capitalization = getCap(calleeName);
|
||||
let isAllowed = capitalization !== "upper" || isCapAllowed(capIsNewExceptions, node, calleeName);
|
||||
|
||||
if (!isAllowed) {
|
||||
report(node, "A function with a name starting with an uppercase letter should only be used as a constructor.");
|
||||
|
||||
@@ -21,18 +21,18 @@ module.exports = {
|
||||
},
|
||||
|
||||
create: function(context) {
|
||||
var sourceCode = context.getSourceCode();
|
||||
let sourceCode = context.getSourceCode();
|
||||
|
||||
return {
|
||||
|
||||
NewExpression: function(node) {
|
||||
var tokens = sourceCode.getTokens(node);
|
||||
var prenticesTokens = tokens.filter(function(token) {
|
||||
let tokens = sourceCode.getTokens(node);
|
||||
let prenticesTokens = tokens.filter(function(token) {
|
||||
return token.value === "(" || token.value === ")";
|
||||
});
|
||||
|
||||
if (prenticesTokens.length < 2) {
|
||||
context.report(node, "Missing '()' invoking a constructor");
|
||||
context.report(node, "Missing '()' invoking a constructor.");
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@@ -26,16 +26,16 @@ module.exports = {
|
||||
|
||||
create: function(context) {
|
||||
|
||||
var ALWAYS_MESSAGE = "Expected blank line after variable declarations.",
|
||||
let ALWAYS_MESSAGE = "Expected blank line after variable declarations.",
|
||||
NEVER_MESSAGE = "Unexpected blank line after variable declarations.";
|
||||
|
||||
var sourceCode = context.getSourceCode();
|
||||
let sourceCode = context.getSourceCode();
|
||||
|
||||
// Default `mode` to "always".
|
||||
var mode = context.options[0] === "never" ? "never" : "always";
|
||||
let mode = context.options[0] === "never" ? "never" : "always";
|
||||
|
||||
// Cache starting and ending line numbers of comments for faster lookup
|
||||
var commentEndLine = sourceCode.getAllComments().reduce(function(result, token) {
|
||||
let commentEndLine = sourceCode.getAllComments().reduce(function(result, token) {
|
||||
result[token.loc.start.line] = token.loc.end.line;
|
||||
return result;
|
||||
}, {});
|
||||
@@ -83,7 +83,7 @@ module.exports = {
|
||||
* @returns {boolean} True if `node` is last of their parent block.
|
||||
*/
|
||||
function isLastNode(node) {
|
||||
var token = sourceCode.getTokenAfter(node);
|
||||
let token = sourceCode.getTokenAfter(node);
|
||||
|
||||
return !token || (token.type === "Punctuator" && token.value === "}");
|
||||
}
|
||||
@@ -95,7 +95,7 @@ module.exports = {
|
||||
* @returns {boolean} True if `token` does not start immediately after a comment
|
||||
*/
|
||||
function hasBlankLineAfterComment(token, commentStartLine) {
|
||||
var commentEnd = commentEndLine[commentStartLine];
|
||||
let commentEnd = commentEndLine[commentStartLine];
|
||||
|
||||
// If there's another comment, repeat check for blank line
|
||||
if (commentEndLine[commentEnd + 1]) {
|
||||
@@ -114,7 +114,7 @@ module.exports = {
|
||||
* @returns {void}
|
||||
*/
|
||||
function checkForBlankLine(node) {
|
||||
var lastToken = sourceCode.getLastToken(node),
|
||||
let lastToken = sourceCode.getLastToken(node),
|
||||
nextToken = sourceCode.getTokenAfter(node),
|
||||
nextLineNum = lastToken.loc.end.line + 1,
|
||||
noNextLineToken,
|
||||
|
||||
@@ -20,7 +20,7 @@ module.exports = {
|
||||
},
|
||||
|
||||
create: function(context) {
|
||||
var sourceCode = context.getSourceCode();
|
||||
let sourceCode = context.getSourceCode();
|
||||
|
||||
//--------------------------------------------------------------------------
|
||||
// Helpers
|
||||
@@ -34,7 +34,7 @@ module.exports = {
|
||||
* @private
|
||||
*/
|
||||
function isPrecededByTokens(node, testTokens) {
|
||||
var tokenBefore = sourceCode.getTokenBefore(node);
|
||||
let tokenBefore = sourceCode.getTokenBefore(node);
|
||||
|
||||
return testTokens.some(function(token) {
|
||||
return tokenBefore.value === token;
|
||||
@@ -48,7 +48,7 @@ module.exports = {
|
||||
* @private
|
||||
*/
|
||||
function isFirstNode(node) {
|
||||
var parentType = node.parent.type;
|
||||
let parentType = node.parent.type;
|
||||
|
||||
if (node.parent.body) {
|
||||
return Array.isArray(node.parent.body)
|
||||
@@ -75,7 +75,7 @@ module.exports = {
|
||||
* @private
|
||||
*/
|
||||
function calcCommentLines(node, lineNumTokenBefore) {
|
||||
var comments = sourceCode.getComments(node).leading,
|
||||
let comments = sourceCode.getComments(node).leading,
|
||||
numLinesComments = 0;
|
||||
|
||||
if (!comments.length) {
|
||||
@@ -109,7 +109,7 @@ module.exports = {
|
||||
* @private
|
||||
*/
|
||||
function hasNewlineBefore(node) {
|
||||
var tokenBefore = sourceCode.getTokenBefore(node),
|
||||
let tokenBefore = sourceCode.getTokenBefore(node),
|
||||
lineNumNode = node.loc.start.line,
|
||||
lineNumTokenBefore,
|
||||
commentLines;
|
||||
|
||||
@@ -33,10 +33,10 @@ module.exports = {
|
||||
|
||||
create: function(context) {
|
||||
|
||||
var options = context.options[0] || {},
|
||||
let options = context.options[0] || {},
|
||||
ignoreChainWithDepth = options.ignoreChainWithDepth || 2;
|
||||
|
||||
var sourceCode = context.getSourceCode();
|
||||
let sourceCode = context.getSourceCode();
|
||||
|
||||
/**
|
||||
* Gets the property text of a given MemberExpression node.
|
||||
@@ -46,9 +46,9 @@ module.exports = {
|
||||
* @returns {string} The property text of the node.
|
||||
*/
|
||||
function getPropertyText(node) {
|
||||
var prefix = node.computed ? "[" : ".";
|
||||
var lines = sourceCode.getText(node.property).split(/\r\n|\r|\n/g);
|
||||
var suffix = node.computed && lines.length === 1 ? "]" : "";
|
||||
let prefix = node.computed ? "[" : ".";
|
||||
let lines = sourceCode.getText(node.property).split(/\r\n|\r|\n/g);
|
||||
let suffix = node.computed && lines.length === 1 ? "]" : "";
|
||||
|
||||
return prefix + lines[0] + suffix;
|
||||
}
|
||||
@@ -59,9 +59,9 @@ module.exports = {
|
||||
return;
|
||||
}
|
||||
|
||||
var callee = node.callee;
|
||||
var parent = callee.object;
|
||||
var depth = 1;
|
||||
let callee = node.callee;
|
||||
let parent = callee.object;
|
||||
let depth = 1;
|
||||
|
||||
while (parent && parent.callee) {
|
||||
depth += 1;
|
||||
|
||||
@@ -51,7 +51,7 @@ function getPropertyName(memberExpressionNode) {
|
||||
* @returns {Reference|null} Returns the found reference or null if none were found.
|
||||
*/
|
||||
function findReference(scope, node) {
|
||||
var references = scope.references.filter(function(reference) {
|
||||
let references = scope.references.filter(function(reference) {
|
||||
return reference.identifier.range[0] === node.range[0] &&
|
||||
reference.identifier.range[1] === node.range[1];
|
||||
});
|
||||
@@ -70,7 +70,7 @@ function findReference(scope, node) {
|
||||
* @returns {boolean} Whether or not the name is shadowed.
|
||||
*/
|
||||
function isShadowed(scope, globalScope, node) {
|
||||
var reference = findReference(scope, node);
|
||||
let reference = findReference(scope, node);
|
||||
|
||||
return reference && reference.resolved && reference.resolved.defs.length > 0;
|
||||
}
|
||||
@@ -108,7 +108,7 @@ module.exports = {
|
||||
},
|
||||
|
||||
create: function(context) {
|
||||
var globalScope;
|
||||
let globalScope;
|
||||
|
||||
return {
|
||||
|
||||
@@ -117,7 +117,7 @@ module.exports = {
|
||||
},
|
||||
|
||||
CallExpression: function(node) {
|
||||
var callee = node.callee,
|
||||
let callee = node.callee,
|
||||
identifierName,
|
||||
currentScope = context.getScope();
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
//
|
||||
// Set of bitwise operators.
|
||||
//
|
||||
var BITWISE_OPERATORS = [
|
||||
let BITWISE_OPERATORS = [
|
||||
"^", "|", "&", "<<", ">>", ">>>",
|
||||
"^=", "|=", "&=", "<<=", ">>=", ">>>=",
|
||||
"~"
|
||||
@@ -47,9 +47,9 @@ module.exports = {
|
||||
},
|
||||
|
||||
create: function(context) {
|
||||
var options = context.options[0] || {};
|
||||
var allowed = options.allow || [];
|
||||
var int32Hint = options.int32Hint === true;
|
||||
let options = context.options[0] || {};
|
||||
let allowed = options.allow || [];
|
||||
let int32Hint = options.int32Hint === true;
|
||||
|
||||
/**
|
||||
* Reports an unexpected use of a bitwise operator.
|
||||
|
||||
Loaded 100 of 701 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user