mirror of
https://github.com/nodejs/node.git
synced 2026-11-29 14:27:57 -05:00
tools: update ESLint to 8.0.0
PR-URL: https://github.com/nodejs/node/pull/40394 Reviewed-By: Michaël Zasso <targos@protonmail.com> Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com> Reviewed-By: Luigi Pinca <luigipinca@gmail.com>
This commit is contained in:
1 parent
dd8e219d71
commit
8ca76eba73
814 files changed
+34866
-31939
No files matched your search
+7
@@ -321,6 +321,13 @@ function adjustBlock(block) {
|
||||
* @returns {Message} The same message, but adjusted to the correct location.
|
||||
*/
|
||||
return function adjustMessage(message) {
|
||||
if (!Number.isInteger(message.line)) {
|
||||
return {
|
||||
...message,
|
||||
line: blockStart,
|
||||
column: block.position.start.column
|
||||
};
|
||||
}
|
||||
|
||||
const lineInCode = message.line - leadingCommentLines;
|
||||
|
||||
|
||||
+1
-1
@@ -8,7 +8,7 @@ This package contains type definitions for Mdast (https://github.com/syntax-tree
|
||||
Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/mdast.
|
||||
|
||||
### Additional Details
|
||||
* Last updated: Fri, 16 Jul 2021 17:31:26 GMT
|
||||
* Last updated: Mon, 23 Aug 2021 20:18:29 GMT
|
||||
* Dependencies: [@types/unist](https://npmjs.com/package/@types/unist)
|
||||
* Global values: none
|
||||
|
||||
|
||||
+3
-3
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@types/mdast",
|
||||
"version": "3.0.7",
|
||||
"version": "3.0.10",
|
||||
"description": "TypeScript definitions for Mdast",
|
||||
"homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/mdast",
|
||||
"license": "MIT",
|
||||
@@ -37,6 +37,6 @@
|
||||
"dependencies": {
|
||||
"@types/unist": "*"
|
||||
},
|
||||
"typesPublisherContentHash": "666079441041567c5bdfa2b8ff46e900b18d544357be5b8cdcecfb412129e903",
|
||||
"typeScriptVersion": "3.6"
|
||||
"typesPublisherContentHash": "87d2054120bead1983528802563a50cbb2f2efd6677d446e5ec34071f50bddcc",
|
||||
"typeScriptVersion": "3.7"
|
||||
}
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "eslint-plugin-markdown",
|
||||
"version": "2.2.0",
|
||||
"version": "2.2.1",
|
||||
"description": "An ESLint plugin to lint JavaScript in Markdown code fences.",
|
||||
"license": "MIT",
|
||||
"author": {
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
Copyright JS Foundation and other contributors, https://js.foundation
|
||||
Copyright OpenJS Foundation and other contributors, <www.openjsf.org>
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
|
||||
+5
-5
@@ -43,7 +43,7 @@ ESLint is a tool for identifying and reporting on patterns found in ECMAScript/J
|
||||
|
||||
## <a name="installation-and-usage"></a>Installation and Usage
|
||||
|
||||
Prerequisites: [Node.js](https://nodejs.org/) (`^10.12.0`, or `>=12.0.0`) built with SSL support. (If you are using an official Node.js distribution, SSL is always built in.)
|
||||
Prerequisites: [Node.js](https://nodejs.org/) (`^12.22.0`, `^14.17.0`, or `>=16.0.0`) built with SSL support. (If you are using an official Node.js distribution, SSL is always built in.)
|
||||
|
||||
You can install ESLint using npm:
|
||||
|
||||
@@ -123,7 +123,7 @@ Yes, ESLint natively supports parsing JSX syntax (this must be enabled in [confi
|
||||
|
||||
### What ECMAScript versions does ESLint support?
|
||||
|
||||
ESLint has full support for ECMAScript 3, 5 (default), 2015, 2016, 2017, 2018, 2019, and 2020. You can set your desired ECMAScript syntax (and other settings, like global variables or your target environments) through [configuration](https://eslint.org/docs/user-guide/configuring).
|
||||
ESLint has full support for ECMAScript 3, 5 (default), 2015, 2016, 2017, 2018, 2019, 2020, 2021 and 2022. You can set your desired ECMAScript syntax (and other settings, like global variables or your target environments) through [configuration](https://eslint.org/docs/user-guide/configuring).
|
||||
|
||||
### What about experimental features?
|
||||
|
||||
@@ -296,9 +296,9 @@ The following companies, organizations, and individuals support ESLint's ongoing
|
||||
<!--sponsorsstart-->
|
||||
<h3>Platinum Sponsors</h3>
|
||||
<p><a href="https://automattic.com"><img src="https://images.opencollective.com/photomatt/d0ef3e1/logo.png" alt="Automattic" height="undefined"></a></p><h3>Gold Sponsors</h3>
|
||||
<p><a href="https://nx.dev"><img src="https://images.opencollective.com/nx/0efbe42/logo.png" alt="Nx (by Nrwl)" height="96"></a> <a href="https://google.com/chrome"><img src="https://images.opencollective.com/chrome/dc55bd4/logo.png" alt="Chrome's Web Framework & Tools Performance Fund" height="96"></a> <a href="https://www.salesforce.com"><img src="https://images.opencollective.com/salesforce/ca8f997/logo.png" alt="Salesforce" height="96"></a> <a href="https://www.airbnb.com/"><img src="https://images.opencollective.com/airbnb/d327d66/logo.png" alt="Airbnb" height="96"></a> <a href="https://coinbase.com"><img src="https://avatars.githubusercontent.com/u/1885080?v=4" alt="Coinbase" height="96"></a> <a href="https://substack.com/"><img src="https://avatars.githubusercontent.com/u/53023767?v=4" alt="Substack" height="96"></a></p><h3>Silver Sponsors</h3>
|
||||
<p><a href="https://retool.com/"><img src="https://images.opencollective.com/retool/98ea68e/logo.png" alt="Retool" height="64"></a> <a href="https://liftoff.io/"><img src="https://images.opencollective.com/liftoff/5c4fa84/logo.png" alt="Liftoff" height="64"></a></p><h3>Bronze Sponsors</h3>
|
||||
<p><a href="https://www.crosswordsolver.org/anagram-solver/"><img src="https://images.opencollective.com/anagram-solver/2666271/logo.png" alt="Anagram Solver" height="32"></a> <a href="null"><img src="https://images.opencollective.com/bugsnag-stability-monitoring/c2cef36/logo.png" alt="Bugsnag Stability Monitoring" height="32"></a> <a href="https://mixpanel.com"><img src="https://images.opencollective.com/mixpanel/cd682f7/logo.png" alt="Mixpanel" height="32"></a> <a href="https://www.vpsserver.com"><img src="https://images.opencollective.com/vpsservercom/logo.png" alt="VPS Server" height="32"></a> <a href="https://icons8.com"><img src="https://images.opencollective.com/icons8/7fa1641/logo.png" alt="Icons8: free icons, photos, illustrations, and music" height="32"></a> <a href="https://discord.com"><img src="https://images.opencollective.com/discordapp/f9645d9/logo.png" alt="Discord" height="32"></a> <a href="https://themeisle.com"><img src="https://images.opencollective.com/themeisle/d5592fe/logo.png" alt="ThemeIsle" height="32"></a> <a href="https://www.firesticktricks.com"><img src="https://images.opencollective.com/fire-stick-tricks/b8fbe2c/logo.png" alt="Fire Stick Tricks" height="32"></a> <a href="https://www.practiceignition.com"><img src="https://avatars.githubusercontent.com/u/5753491?v=4" alt="Practice Ignition" height="32"></a></p>
|
||||
<p><a href="https://nx.dev"><img src="https://images.opencollective.com/nx/0efbe42/logo.png" alt="Nx (by Nrwl)" height="96"></a> <a href="https://google.com/chrome"><img src="https://images.opencollective.com/chrome/dc55bd4/logo.png" alt="Chrome's Web Framework & Tools Performance Fund" height="96"></a> <a href="https://www.salesforce.com"><img src="https://images.opencollective.com/salesforce/ca8f997/logo.png" alt="Salesforce" height="96"></a> <a href="https://www.airbnb.com/"><img src="https://images.opencollective.com/airbnb/d327d66/logo.png" alt="Airbnb" height="96"></a> <a href="https://coinbase.com"><img src="https://avatars.githubusercontent.com/u/1885080?v=4" alt="Coinbase" height="96"></a> <a href="https://americanexpress.io"><img src="https://avatars.githubusercontent.com/u/3853301?v=4" alt="American Express" height="96"></a> <a href="https://substack.com/"><img src="https://avatars.githubusercontent.com/u/53023767?v=4" alt="Substack" height="96"></a></p><h3>Silver Sponsors</h3>
|
||||
<p><a href="https://liftoff.io/"><img src="https://images.opencollective.com/liftoff/5c4fa84/logo.png" alt="Liftoff" height="64"></a></p><h3>Bronze Sponsors</h3>
|
||||
<p><a href="https://launchdarkly.com"><img src="https://images.opencollective.com/launchdarkly/574bb9e/logo.png" alt="launchdarkly" height="32"></a> <a href="https://troypoint.com"><img src="https://images.opencollective.com/troypoint/080f96f/avatar.png" alt="TROYPOINT" height="32"></a> <a href="https://mobilen.nu"><img src="https://images.opencollective.com/mobilen/e19860d/logo.png" alt="Mobilen" height="32"></a> <a href="https://www.crosswordsolver.org/anagram-solver/"><img src="https://images.opencollective.com/anagram-solver/2666271/logo.png" alt="Anagram Solver" height="32"></a> <a href="null"><img src="https://images.opencollective.com/bugsnag-stability-monitoring/c2cef36/logo.png" alt="Bugsnag Stability Monitoring" height="32"></a> <a href="https://mixpanel.com"><img src="https://images.opencollective.com/mixpanel/cd682f7/logo.png" alt="Mixpanel" height="32"></a> <a href="https://www.vpsserver.com"><img src="https://images.opencollective.com/vpsservercom/logo.png" alt="VPS Server" height="32"></a> <a href="https://icons8.com"><img src="https://images.opencollective.com/icons8/7fa1641/logo.png" alt="Icons8: free icons, photos, illustrations, and music" height="32"></a> <a href="https://discord.com"><img src="https://images.opencollective.com/discordapp/f9645d9/logo.png" alt="Discord" height="32"></a> <a href="https://themeisle.com"><img src="https://images.opencollective.com/themeisle/d5592fe/logo.png" alt="ThemeIsle" height="32"></a> <a href="https://www.firesticktricks.com"><img src="https://images.opencollective.com/fire-stick-tricks/b8fbe2c/logo.png" alt="Fire Stick Tricks" height="32"></a> <a href="https://www.practiceignition.com"><img src="https://avatars.githubusercontent.com/u/5753491?v=4" alt="Practice Ignition" height="32"></a></p>
|
||||
<!--sponsorsend-->
|
||||
|
||||
## <a name="technology-sponsors"></a>Technology Sponsors
|
||||
|
||||
+1
-1
@@ -5,7 +5,7 @@
|
||||
* @author Nicholas C. Zakas
|
||||
*/
|
||||
|
||||
/* eslint no-console:off */
|
||||
/* eslint no-console:off -- CLI */
|
||||
|
||||
"use strict";
|
||||
|
||||
|
||||
+5
-1
@@ -6,7 +6,7 @@
|
||||
|
||||
"use strict";
|
||||
|
||||
/* eslint sort-keys: ["error", "asc"] */
|
||||
/* eslint sort-keys: ["error", "asc"] -- Long, so make more readable */
|
||||
|
||||
/** @type {import("../lib/shared/types").ConfigData} */
|
||||
module.exports = {
|
||||
@@ -42,9 +42,11 @@ module.exports = {
|
||||
"no-inner-declarations": "error",
|
||||
"no-invalid-regexp": "error",
|
||||
"no-irregular-whitespace": "error",
|
||||
"no-loss-of-precision": "error",
|
||||
"no-misleading-character-class": "error",
|
||||
"no-mixed-spaces-and-tabs": "error",
|
||||
"no-new-symbol": "error",
|
||||
"no-nonoctal-decimal-escape": "error",
|
||||
"no-obj-calls": "error",
|
||||
"no-octal": "error",
|
||||
"no-prototype-builtins": "error",
|
||||
@@ -60,8 +62,10 @@ module.exports = {
|
||||
"no-unreachable": "error",
|
||||
"no-unsafe-finally": "error",
|
||||
"no-unsafe-negation": "error",
|
||||
"no-unsafe-optional-chaining": "error",
|
||||
"no-unused-labels": "error",
|
||||
"no-unused-vars": "error",
|
||||
"no-useless-backreference": "error",
|
||||
"no-useless-catch": "error",
|
||||
"no-useless-escape": "error",
|
||||
"no-with": "error",
|
||||
|
||||
Generated
Vendored
+4
-7
@@ -1,11 +1,8 @@
|
||||
{
|
||||
"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": "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:" }
|
||||
"types": [
|
||||
{ "name": "problem", "displayName": "Possible Problems", "description": "These rules relate to possible logic errors in code:" },
|
||||
{ "name": "suggestion", "displayName": "Suggestions", "description": "These rules suggest alternate ways of doing things:" },
|
||||
{ "name": "layout", "displayName": "Layout & Formatting", "description": "These rules care about how the code looks rather than how it executes:" }
|
||||
],
|
||||
"deprecated": {
|
||||
"name": "Deprecated",
|
||||
+8
-16
@@ -5,30 +5,22 @@
|
||||
|
||||
"use strict";
|
||||
|
||||
const { CLIEngine } = require("./cli-engine");
|
||||
//-----------------------------------------------------------------------------
|
||||
// Requirements
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
const { ESLint } = require("./eslint");
|
||||
const { Linter } = require("./linter");
|
||||
const { RuleTester } = require("./rule-tester");
|
||||
const { SourceCode } = require("./source-code");
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// Exports
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
module.exports = {
|
||||
Linter,
|
||||
CLIEngine,
|
||||
ESLint,
|
||||
RuleTester,
|
||||
SourceCode
|
||||
};
|
||||
|
||||
// DOTO: remove deprecated API.
|
||||
let deprecatedLinterInstance = null;
|
||||
|
||||
Object.defineProperty(module.exports, "linter", {
|
||||
enumerable: false,
|
||||
get() {
|
||||
if (!deprecatedLinterInstance) {
|
||||
deprecatedLinterInstance = new Linter();
|
||||
}
|
||||
|
||||
return deprecatedLinterInstance;
|
||||
}
|
||||
});
|
||||
+35
-11
@@ -41,7 +41,7 @@ const hash = require("./hash");
|
||||
const LintResultCache = require("./lint-result-cache");
|
||||
|
||||
const debug = require("debug")("eslint:cli-engine");
|
||||
const validFixTypes = new Set(["problem", "suggestion", "layout"]);
|
||||
const validFixTypes = new Set(["directive", "problem", "suggestion", "layout"]);
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Typedefs
|
||||
@@ -55,8 +55,8 @@ const validFixTypes = new Set(["problem", "suggestion", "layout"]);
|
||||
/** @typedef {import("../shared/types").Plugin} Plugin */
|
||||
/** @typedef {import("../shared/types").RuleConf} RuleConf */
|
||||
/** @typedef {import("../shared/types").Rule} Rule */
|
||||
/** @typedef {ReturnType<CascadingConfigArrayFactory["getConfigArrayForFile"]>} ConfigArray */
|
||||
/** @typedef {ReturnType<ConfigArray["extractConfig"]>} ExtractedConfig */
|
||||
/** @typedef {ReturnType<CascadingConfigArrayFactory.getConfigArrayForFile>} ConfigArray */
|
||||
/** @typedef {ReturnType<ConfigArray.extractConfig>} ExtractedConfig */
|
||||
|
||||
/**
|
||||
* The options to configure a CLI engine with.
|
||||
@@ -280,7 +280,7 @@ function verifyText({
|
||||
/**
|
||||
* Returns result with warning by ignore settings
|
||||
* @param {string} filePath File path of checked code
|
||||
* @param {string} baseDir Absolute path of base directory
|
||||
* @param {string} baseDir Absolute path of base directory
|
||||
* @returns {LintResult} Result with single warning
|
||||
* @private
|
||||
*/
|
||||
@@ -331,6 +331,23 @@ function getRule(ruleId, configArrays) {
|
||||
return builtInRules.get(ruleId) || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether a message's rule type should be fixed.
|
||||
* @param {LintMessage} message The message to check.
|
||||
* @param {ConfigArray[]} lastConfigArrays The list of config arrays that the last `executeOnFiles` or `executeOnText` used.
|
||||
* @param {string[]} fixTypes An array of fix types to check.
|
||||
* @returns {boolean} Whether the message should be fixed.
|
||||
*/
|
||||
function shouldMessageBeFixed(message, lastConfigArrays, fixTypes) {
|
||||
if (!message.ruleId) {
|
||||
return fixTypes.has("directive");
|
||||
}
|
||||
|
||||
const rule = message.ruleId && getRule(message.ruleId, lastConfigArrays);
|
||||
|
||||
return Boolean(rule && rule.meta && fixTypes.has(rule.meta.type));
|
||||
}
|
||||
|
||||
/**
|
||||
* Collect used deprecated rules.
|
||||
* @param {ConfigArray[]} usedConfigArrays The config arrays which were used.
|
||||
@@ -463,6 +480,7 @@ function getCacheFile(cacheFile, cwd) {
|
||||
* @param {string[]|null} keys The keys to assign true.
|
||||
* @param {boolean} defaultValue The default value for each property.
|
||||
* @param {string} displayName The property name which is used in error message.
|
||||
* @throws {Error} Requires array.
|
||||
* @returns {Record<string,boolean>} The boolean map.
|
||||
*/
|
||||
function toBooleanMap(keys, defaultValue, displayName) {
|
||||
@@ -526,6 +544,7 @@ function createConfigDataFromOptions(options) {
|
||||
/**
|
||||
* Checks whether a directory exists at the given location
|
||||
* @param {string} resolvedPath A path from the CWD
|
||||
* @throws {Error} As thrown by `fs.statSync` or `fs.isDirectory`.
|
||||
* @returns {boolean} `true` if a directory exists
|
||||
*/
|
||||
function directoryExists(resolvedPath) {
|
||||
@@ -543,6 +562,9 @@ function directoryExists(resolvedPath) {
|
||||
// Public Interface
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Core CLI.
|
||||
*/
|
||||
class CLIEngine {
|
||||
|
||||
/**
|
||||
@@ -623,12 +645,7 @@ class CLIEngine {
|
||||
const originalFix = (typeof options.fix === "function")
|
||||
? options.fix : () => true;
|
||||
|
||||
options.fix = message => {
|
||||
const rule = message.ruleId && getRule(message.ruleId, lastConfigArrays);
|
||||
const matches = rule && rule.meta && fixTypes.has(rule.meta.type);
|
||||
|
||||
return matches && originalFix(message);
|
||||
};
|
||||
options.fix = message => shouldMessageBeFixed(message, lastConfigArrays, fixTypes) && originalFix(message);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -730,6 +747,7 @@ class CLIEngine {
|
||||
/**
|
||||
* Executes the current configuration on an array of file and directory names.
|
||||
* @param {string[]} patterns An array of file and directory names.
|
||||
* @throws {Error} As may be thrown by `fs.unlinkSync`.
|
||||
* @returns {LintReport} The results for all files that were linted.
|
||||
*/
|
||||
executeOnFiles(patterns) {
|
||||
@@ -936,6 +954,7 @@ class CLIEngine {
|
||||
* This is the same logic used by the ESLint CLI executable to determine
|
||||
* configuration for each file it processes.
|
||||
* @param {string} filePath The path of the file to retrieve a config object for.
|
||||
* @throws {Error} If filepath a directory path.
|
||||
* @returns {ConfigData} A configuration object for the file.
|
||||
*/
|
||||
getConfigForFile(filePath) {
|
||||
@@ -984,6 +1003,7 @@ class CLIEngine {
|
||||
* Returns the formatter representing the given format or null if the `format` is not a string.
|
||||
* @param {string} [format] The name of the format to load or the path to a
|
||||
* custom formatter.
|
||||
* @throws {any} As may be thrown by requiring of formatter
|
||||
* @returns {(Function|null)} The formatter function or null if the `format` is not a string.
|
||||
*/
|
||||
getFormatter(format) {
|
||||
@@ -1019,7 +1039,11 @@ class CLIEngine {
|
||||
try {
|
||||
return require(formatterPath);
|
||||
} catch (ex) {
|
||||
ex.message = `There was a problem loading formatter: ${formatterPath}\nError: ${ex.message}`;
|
||||
if (format === "table" || format === "codeframe") {
|
||||
ex.message = `The ${format} formatter is no longer part of core ESLint. Install it manually with \`npm install -D eslint-formatter-${format}\``;
|
||||
} else {
|
||||
ex.message = `There was a problem loading formatter: ${formatterPath}\nError: ${ex.message}`;
|
||||
}
|
||||
throw ex;
|
||||
}
|
||||
|
||||
|
||||
+4
-3
@@ -60,7 +60,7 @@ const IGNORED_SILENTLY = 1;
|
||||
const IGNORED = 2;
|
||||
|
||||
// For VSCode intellisense
|
||||
/** @typedef {ReturnType<CascadingConfigArrayFactory["getConfigArrayForFile"]>} ConfigArray */
|
||||
/** @typedef {ReturnType<CascadingConfigArrayFactory.getConfigArrayForFile>} ConfigArray */
|
||||
|
||||
/**
|
||||
* @typedef {Object} FileEnumeratorOptions
|
||||
@@ -114,6 +114,7 @@ function isGlobPattern(pattern) {
|
||||
/**
|
||||
* Get stats of a given path.
|
||||
* @param {string} filePath The path to target file.
|
||||
* @throws {Error} As may be thrown by `fs.statSync`.
|
||||
* @returns {fs.Stats|null} The stats.
|
||||
* @private
|
||||
*/
|
||||
@@ -132,6 +133,7 @@ function statSafeSync(filePath) {
|
||||
/**
|
||||
* Get filenames in a given path to a directory.
|
||||
* @param {string} directoryPath The path to target directory.
|
||||
* @throws {Error} As may be thrown by `fs.readdirSync`.
|
||||
* @returns {import("fs").Dirent[]} The filenames.
|
||||
* @private
|
||||
*/
|
||||
@@ -173,7 +175,6 @@ function createExtensionRegExp(extensions) {
|
||||
*/
|
||||
class NoFilesFoundError extends Error {
|
||||
|
||||
// eslint-disable-next-line jsdoc/require-description
|
||||
/**
|
||||
* @param {string} pattern The glob pattern which was not found.
|
||||
* @param {boolean} globDisabled If `true` then the pattern was a glob pattern, but glob was disabled.
|
||||
@@ -190,7 +191,6 @@ class NoFilesFoundError extends Error {
|
||||
*/
|
||||
class AllFilesIgnoredError extends Error {
|
||||
|
||||
// eslint-disable-next-line jsdoc/require-description
|
||||
/**
|
||||
* @param {string} pattern The glob pattern which was not found.
|
||||
*/
|
||||
@@ -270,6 +270,7 @@ class FileEnumerator {
|
||||
/**
|
||||
* Iterate files which are matched by given glob patterns.
|
||||
* @param {string|string[]} patternOrPatterns The glob patterns to iterate files.
|
||||
* @throws {NoFilesFoundError|AllFilesIgnoredError} On an unmatched pattern.
|
||||
* @returns {IterableIterator<FileAndConfig>} The found files.
|
||||
*/
|
||||
*iterateFiles(patternOrPatterns) {
|
||||
|
||||
-138
@@ -1,138 +0,0 @@
|
||||
/**
|
||||
* @fileoverview Codeframe reporter
|
||||
* @author Vitor Balocco
|
||||
*/
|
||||
"use strict";
|
||||
|
||||
const chalk = require("chalk");
|
||||
const { codeFrameColumns } = require("@babel/code-frame");
|
||||
const path = require("path");
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Helpers
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Given a word and a count, append an s if count is not one.
|
||||
* @param {string} word A word in its singular form.
|
||||
* @param {number} count A number controlling whether word should be pluralized.
|
||||
* @returns {string} The original word with an s on the end if count is not one.
|
||||
*/
|
||||
function pluralize(word, count) {
|
||||
return (count === 1 ? word : `${word}s`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a formatted relative file path from an absolute path and a line/column in the file.
|
||||
* @param {string} filePath The absolute file path to format.
|
||||
* @param {number} line The line from the file to use for formatting.
|
||||
* @param {number} column The column from the file to use for formatting.
|
||||
* @returns {string} The formatted file path.
|
||||
*/
|
||||
function formatFilePath(filePath, line, column) {
|
||||
let relPath = path.relative(process.cwd(), filePath);
|
||||
|
||||
if (line && column) {
|
||||
relPath += `:${line}:${column}`;
|
||||
}
|
||||
|
||||
return chalk.green(relPath);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the formatted output for a given message.
|
||||
* @param {Object} message The object that represents this message.
|
||||
* @param {Object} parentResult The result object that this message belongs to.
|
||||
* @returns {string} The formatted output.
|
||||
*/
|
||||
function formatMessage(message, parentResult) {
|
||||
const type = (message.fatal || message.severity === 2) ? chalk.red("error") : chalk.yellow("warning");
|
||||
const msg = `${chalk.bold(message.message.replace(/([^ ])\.$/u, "$1"))}`;
|
||||
const ruleId = message.fatal ? "" : chalk.dim(`(${message.ruleId})`);
|
||||
const filePath = formatFilePath(parentResult.filePath, message.line, message.column);
|
||||
const sourceCode = parentResult.output ? parentResult.output : parentResult.source;
|
||||
|
||||
const firstLine = [
|
||||
`${type}:`,
|
||||
`${msg}`,
|
||||
ruleId ? `${ruleId}` : "",
|
||||
sourceCode ? `at ${filePath}:` : `at ${filePath}`
|
||||
].filter(String).join(" ");
|
||||
|
||||
const result = [firstLine];
|
||||
|
||||
if (sourceCode) {
|
||||
result.push(
|
||||
codeFrameColumns(sourceCode, { start: { line: message.line, column: message.column } }, { highlightCode: false })
|
||||
);
|
||||
}
|
||||
|
||||
return result.join("\n");
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the formatted output summary for a given number of errors and warnings.
|
||||
* @param {number} errors The number of errors.
|
||||
* @param {number} warnings The number of warnings.
|
||||
* @param {number} fixableErrors The number of fixable errors.
|
||||
* @param {number} fixableWarnings The number of fixable warnings.
|
||||
* @returns {string} The formatted output summary.
|
||||
*/
|
||||
function formatSummary(errors, warnings, fixableErrors, fixableWarnings) {
|
||||
const summaryColor = errors > 0 ? "red" : "yellow";
|
||||
const summary = [];
|
||||
const fixablesSummary = [];
|
||||
|
||||
if (errors > 0) {
|
||||
summary.push(`${errors} ${pluralize("error", errors)}`);
|
||||
}
|
||||
|
||||
if (warnings > 0) {
|
||||
summary.push(`${warnings} ${pluralize("warning", warnings)}`);
|
||||
}
|
||||
|
||||
if (fixableErrors > 0) {
|
||||
fixablesSummary.push(`${fixableErrors} ${pluralize("error", fixableErrors)}`);
|
||||
}
|
||||
|
||||
if (fixableWarnings > 0) {
|
||||
fixablesSummary.push(`${fixableWarnings} ${pluralize("warning", fixableWarnings)}`);
|
||||
}
|
||||
|
||||
let output = chalk[summaryColor].bold(`${summary.join(" and ")} found.`);
|
||||
|
||||
if (fixableErrors || fixableWarnings) {
|
||||
output += chalk[summaryColor].bold(`\n${fixablesSummary.join(" and ")} potentially fixable with the \`--fix\` option.`);
|
||||
}
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Public Interface
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
module.exports = function(results) {
|
||||
let errors = 0;
|
||||
let warnings = 0;
|
||||
let fixableErrors = 0;
|
||||
let fixableWarnings = 0;
|
||||
|
||||
const resultsWithMessages = results.filter(result => result.messages.length > 0);
|
||||
|
||||
let output = resultsWithMessages.reduce((resultsOutput, result) => {
|
||||
const messages = result.messages.map(message => `${formatMessage(message, result)}\n\n`);
|
||||
|
||||
errors += result.errorCount;
|
||||
warnings += result.warningCount;
|
||||
fixableErrors += result.fixableErrorCount;
|
||||
fixableWarnings += result.fixableWarningCount;
|
||||
|
||||
return resultsOutput.concat(messages);
|
||||
}, []).join("\n");
|
||||
|
||||
output += "\n";
|
||||
output += formatSummary(errors, warnings, fixableErrors, fixableWarnings);
|
||||
|
||||
return (errors + warnings) > 0 ? output : "";
|
||||
};
|
||||
+1
-1
@@ -281,8 +281,8 @@ function resultTemplate(it) {
|
||||
`.trimLeft();
|
||||
}
|
||||
|
||||
// eslint-disable-next-line jsdoc/require-description
|
||||
/**
|
||||
* Render the results.
|
||||
* @param {Array} results Test results.
|
||||
* @param {Object} rulesMeta Dictionary containing metadata for each rule executed by the analysis.
|
||||
* @returns {string} HTML string describing the results.
|
||||
|
||||
-159
@@ -1,159 +0,0 @@
|
||||
/**
|
||||
* @fileoverview "table reporter.
|
||||
* @author Gajus Kuizinas <gajus@gajus.com>
|
||||
*/
|
||||
"use strict";
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Requirements
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
const chalk = require("chalk"),
|
||||
table = require("table").table;
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Helpers
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Given a word and a count, append an "s" if count is not one.
|
||||
* @param {string} word A word.
|
||||
* @param {number} count Quantity.
|
||||
* @returns {string} The original word with an s on the end if count is not one.
|
||||
*/
|
||||
function pluralize(word, count) {
|
||||
return (count === 1 ? word : `${word}s`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Draws text table.
|
||||
* @param {Array<Object>} messages Error messages relating to a specific file.
|
||||
* @returns {string} A text table.
|
||||
*/
|
||||
function drawTable(messages) {
|
||||
const rows = [];
|
||||
|
||||
if (messages.length === 0) {
|
||||
return "";
|
||||
}
|
||||
|
||||
rows.push([
|
||||
chalk.bold("Line"),
|
||||
chalk.bold("Column"),
|
||||
chalk.bold("Type"),
|
||||
chalk.bold("Message"),
|
||||
chalk.bold("Rule ID")
|
||||
]);
|
||||
|
||||
messages.forEach(message => {
|
||||
let messageType;
|
||||
|
||||
if (message.fatal || message.severity === 2) {
|
||||
messageType = chalk.red("error");
|
||||
} else {
|
||||
messageType = chalk.yellow("warning");
|
||||
}
|
||||
|
||||
rows.push([
|
||||
message.line || 0,
|
||||
message.column || 0,
|
||||
messageType,
|
||||
message.message,
|
||||
message.ruleId || ""
|
||||
]);
|
||||
});
|
||||
|
||||
return table(rows, {
|
||||
columns: {
|
||||
0: {
|
||||
width: 8,
|
||||
wrapWord: true
|
||||
},
|
||||
1: {
|
||||
width: 8,
|
||||
wrapWord: true
|
||||
},
|
||||
2: {
|
||||
width: 8,
|
||||
wrapWord: true
|
||||
},
|
||||
3: {
|
||||
paddingRight: 5,
|
||||
width: 50,
|
||||
wrapWord: true
|
||||
},
|
||||
4: {
|
||||
width: 20,
|
||||
wrapWord: true
|
||||
}
|
||||
},
|
||||
drawHorizontalLine(index) {
|
||||
return index === 1;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Draws a report (multiple tables).
|
||||
* @param {Array} results Report results for every file.
|
||||
* @returns {string} A column of text tables.
|
||||
*/
|
||||
function drawReport(results) {
|
||||
let files;
|
||||
|
||||
files = results.map(result => {
|
||||
if (!result.messages.length) {
|
||||
return "";
|
||||
}
|
||||
|
||||
return `\n${result.filePath}\n\n${drawTable(result.messages)}`;
|
||||
});
|
||||
|
||||
files = files.filter(content => content.trim());
|
||||
|
||||
return files.join("");
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Public Interface
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
module.exports = function(report) {
|
||||
let result,
|
||||
errorCount,
|
||||
warningCount;
|
||||
|
||||
result = "";
|
||||
errorCount = 0;
|
||||
warningCount = 0;
|
||||
|
||||
report.forEach(fileReport => {
|
||||
errorCount += fileReport.errorCount;
|
||||
warningCount += fileReport.warningCount;
|
||||
});
|
||||
|
||||
if (errorCount || warningCount) {
|
||||
result = drawReport(report);
|
||||
}
|
||||
|
||||
result += `\n${table([
|
||||
[
|
||||
chalk.red(pluralize(`${errorCount} Error`, errorCount))
|
||||
],
|
||||
[
|
||||
chalk.yellow(pluralize(`${warningCount} Warning`, warningCount))
|
||||
]
|
||||
], {
|
||||
columns: {
|
||||
0: {
|
||||
width: 110,
|
||||
wrapWord: true
|
||||
}
|
||||
},
|
||||
drawHorizontalLine() {
|
||||
return true;
|
||||
}
|
||||
})}`;
|
||||
|
||||
return result;
|
||||
};
|
||||
+1
-1
@@ -31,7 +31,7 @@ function outputDiagnostics(diagnostic) {
|
||||
const prefix = " ";
|
||||
let output = `${prefix}---\n`;
|
||||
|
||||
output += prefix + yaml.safeDump(diagnostic).split("\n").join(`\n${prefix}`);
|
||||
output += prefix + yaml.dump(diagnostic).split("\n").join(`\n${prefix}`);
|
||||
output += "...\n";
|
||||
return output;
|
||||
}
|
||||
|
||||
+2
-2
@@ -21,8 +21,8 @@ const murmur = require("imurmurhash");
|
||||
|
||||
/**
|
||||
* hash the given string
|
||||
* @param {string} str the string to hash
|
||||
* @returns {string} the hash
|
||||
* @param {string} str the string to hash
|
||||
* @returns {string} the hash
|
||||
*/
|
||||
function hash(str) {
|
||||
return murmur(str).result().toString(36);
|
||||
|
||||
+1
-1
@@ -15,7 +15,7 @@
|
||||
* @private
|
||||
*/
|
||||
module.exports = function(s) {
|
||||
return (`${s}`).replace(/[<>&"'\x00-\x1F\x7F\u0080-\uFFFF]/gu, c => { // eslint-disable-line no-control-regex
|
||||
return (`${s}`).replace(/[<>&"'\x00-\x1F\x7F\u0080-\uFFFF]/gu, c => { // eslint-disable-line no-control-regex -- Converting controls to entities
|
||||
switch (c) {
|
||||
case "<":
|
||||
return "<";
|
||||
|
||||
+2
-2
@@ -61,7 +61,7 @@ class FlatConfigArray extends ConfigArray {
|
||||
this.unshift(baseConfig);
|
||||
}
|
||||
|
||||
/* eslint-disable class-methods-use-this */
|
||||
/* eslint-disable class-methods-use-this -- Desired as instance method */
|
||||
/**
|
||||
* Replaces a config with another config to allow us to put strings
|
||||
* in the config array that will be replaced by objects before
|
||||
@@ -118,7 +118,7 @@ class FlatConfigArray extends ConfigArray {
|
||||
|
||||
return config;
|
||||
}
|
||||
/* eslint-enable class-methods-use-this */
|
||||
/* eslint-enable class-methods-use-this -- Desired as instance method */
|
||||
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -336,7 +336,7 @@ const rulesSchema = {
|
||||
// avoid hairy edge case
|
||||
if (ruleId === "__proto__") {
|
||||
|
||||
/* eslint-disable-next-line no-proto */
|
||||
/* eslint-disable-next-line no-proto -- Though deprecated, may still be present */
|
||||
delete result.__proto__;
|
||||
continue;
|
||||
}
|
||||
|
||||
+26
-9
@@ -19,6 +19,7 @@ const ajv = require("../shared/ajv")();
|
||||
* Finds a rule with the given ID in the given config.
|
||||
* @param {string} ruleId The ID of the rule to find.
|
||||
* @param {Object} config The config to search in.
|
||||
* @throws {TypeError} For missing plugin or rule.
|
||||
* @returns {{create: Function, schema: (Array|null)}} THe rule object.
|
||||
*/
|
||||
function findRuleDefinition(ruleId, config) {
|
||||
@@ -34,16 +35,33 @@ function findRuleDefinition(ruleId, config) {
|
||||
pluginName = ruleIdParts.join("/");
|
||||
}
|
||||
|
||||
if (!config.plugins || !config.plugins[pluginName]) {
|
||||
throw new TypeError(`Key "rules": Key "${ruleId}": Could not find plugin "${pluginName}".`);
|
||||
const errorMessageHeader = `Key "rules": Key "${ruleId}"`;
|
||||
let errorMessage = `${errorMessageHeader}: Could not find plugin "${pluginName}".`;
|
||||
|
||||
// if the plugin exists then we need to check if the rule exists
|
||||
if (config.plugins && config.plugins[pluginName]) {
|
||||
|
||||
const plugin = config.plugins[pluginName];
|
||||
|
||||
// first check for exact rule match
|
||||
if (plugin.rules && plugin.rules[ruleName]) {
|
||||
return config.plugins[pluginName].rules[ruleName];
|
||||
}
|
||||
|
||||
errorMessage = `${errorMessageHeader}: Could not find "${ruleName}" in plugin "${pluginName}".`;
|
||||
|
||||
// otherwise, let's see if we can find the rule name elsewhere
|
||||
for (const [otherPluginName, otherPlugin] of Object.entries(config.plugins)) {
|
||||
if (otherPlugin.rules && otherPlugin.rules[ruleName]) {
|
||||
errorMessage += ` Did you mean "${otherPluginName}/${ruleName}"?`;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// falls through to throw error
|
||||
}
|
||||
|
||||
if (!config.plugins[pluginName].rules || !config.plugins[pluginName].rules[ruleName]) {
|
||||
throw new TypeError(`Key "rules": Key "${ruleId}": Could not find "${ruleName}" in plugin "${pluginName}".`);
|
||||
}
|
||||
|
||||
return config.plugins[pluginName].rules[ruleName];
|
||||
|
||||
throw new TypeError(errorMessage);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -98,7 +116,6 @@ class RuleValidator {
|
||||
* A collection of compiled validators for rules that have already
|
||||
* been validated.
|
||||
* @type {WeakMap}
|
||||
* @property validators
|
||||
*/
|
||||
this.validators = new WeakMap();
|
||||
}
|
||||
|
||||
+6
-2
@@ -125,7 +125,7 @@ function isArrayOfNonEmptyString(x) {
|
||||
* @returns {boolean} `true` if `x` is valid fix type.
|
||||
*/
|
||||
function isFixType(x) {
|
||||
return x === "problem" || x === "suggestion" || x === "layout";
|
||||
return x === "directive" || x === "problem" || x === "suggestion" || x === "layout";
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -151,6 +151,7 @@ class ESLintInvalidOptionsError extends Error {
|
||||
/**
|
||||
* Validates and normalizes options for the wrapped CLIEngine instance.
|
||||
* @param {ESLintOptions} options The options to process.
|
||||
* @throws {ESLintInvalidOptionsError} If of any of a variety of type errors.
|
||||
* @returns {ESLintOptions} The normalized options.
|
||||
*/
|
||||
function processOptions({
|
||||
@@ -237,7 +238,7 @@ function processOptions({
|
||||
errors.push("'fix' must be a boolean or a function.");
|
||||
}
|
||||
if (fixTypes !== null && !isFixTypeArray(fixTypes)) {
|
||||
errors.push("'fixTypes' must be an array of any of \"problem\", \"suggestion\", and \"layout\".");
|
||||
errors.push("'fixTypes' must be an array of any of \"directive\", \"problem\", \"suggestion\", and \"layout\".");
|
||||
}
|
||||
if (typeof globInputPaths !== "boolean") {
|
||||
errors.push("'globInputPaths' must be a boolean.");
|
||||
@@ -421,6 +422,9 @@ function compareResultsByFilePath(a, b) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Main API.
|
||||
*/
|
||||
class ESLint {
|
||||
|
||||
/**
|
||||
|
||||
+22
-19
@@ -11,7 +11,11 @@
|
||||
|
||||
const equal = require("fast-deep-equal"),
|
||||
recConfig = require("../../conf/eslint-recommended"),
|
||||
ConfigOps = require("@eslint/eslintrc/lib/shared/config-ops"),
|
||||
{
|
||||
Legacy: {
|
||||
ConfigOps
|
||||
}
|
||||
} = require("@eslint/eslintrc"),
|
||||
{ Linter } = require("../linter"),
|
||||
configRule = require("./config-rule");
|
||||
|
||||
@@ -32,9 +36,9 @@ const MAX_CONFIG_COMBINATIONS = 17, // 16 combinations + 1 for severity only
|
||||
/**
|
||||
* Information about a rule configuration, in the context of a Registry.
|
||||
* @typedef {Object} registryItem
|
||||
* @param {ruleConfig} config A valid configuration for the rule
|
||||
* @param {number} specificity The number of elements in the ruleConfig array
|
||||
* @param {number} errorCount The number of errors encountered when linting with the config
|
||||
* @property {ruleConfig} config A valid configuration for the rule
|
||||
* @property {number} specificity The number of elements in the ruleConfig array
|
||||
* @property {number} errorCount The number of errors encountered when linting with the config
|
||||
*/
|
||||
|
||||
/**
|
||||
@@ -45,8 +49,8 @@ const MAX_CONFIG_COMBINATIONS = 17, // 16 combinations + 1 for severity only
|
||||
|
||||
/**
|
||||
* Create registryItems for rules
|
||||
* @param {rulesConfig} rulesConfig Hash of rule names and arrays of ruleConfig items
|
||||
* @returns {Object} registryItems for each rule in provided rulesConfig
|
||||
* @param {rulesConfig} rulesConfig Hash of rule names and arrays of ruleConfig items
|
||||
* @returns {Object} registryItems for each rule in provided rulesConfig
|
||||
*/
|
||||
function makeRegistryItems(rulesConfig) {
|
||||
return Object.keys(rulesConfig).reduce((accumulator, ruleId) => {
|
||||
@@ -69,7 +73,6 @@ function makeRegistryItems(rulesConfig) {
|
||||
*/
|
||||
class Registry {
|
||||
|
||||
// eslint-disable-next-line jsdoc/require-description
|
||||
/**
|
||||
* @param {rulesConfig} [rulesConfig] Hash of rule names and arrays of possible configurations
|
||||
*/
|
||||
@@ -100,7 +103,7 @@ class Registry {
|
||||
* configurations.
|
||||
*
|
||||
* The length of the returned array will be <= MAX_CONFIG_COMBINATIONS.
|
||||
* @returns {Object[]} "rules" configurations to use for linting
|
||||
* @returns {Object[]} "rules" configurations to use for linting
|
||||
*/
|
||||
buildRuleSets() {
|
||||
let idx = 0;
|
||||
@@ -112,7 +115,7 @@ class Registry {
|
||||
*
|
||||
* This is broken out into its own function so that it doesn't need to be
|
||||
* created inside of the while loop.
|
||||
* @param {string} rule The ruleId to add.
|
||||
* @param {string} rule The ruleId to add.
|
||||
* @returns {void}
|
||||
*/
|
||||
const addRuleToRuleSet = function(rule) {
|
||||
@@ -199,7 +202,7 @@ class Registry {
|
||||
* Creates a registry of rules which had no error-free configs.
|
||||
* The new registry is intended to be analyzed to determine whether its rules
|
||||
* should be disabled or set to warning.
|
||||
* @returns {Registry} A registry of failing rules.
|
||||
* @returns {Registry} A registry of failing rules.
|
||||
*/
|
||||
getFailingRulesRegistry() {
|
||||
const ruleIds = Object.keys(this.rules),
|
||||
@@ -236,8 +239,8 @@ class Registry {
|
||||
|
||||
/**
|
||||
* Return a cloned registry containing only configs with a desired specificity
|
||||
* @param {number} specificity Only keep configs with this specificity
|
||||
* @returns {Registry} A registry of rules
|
||||
* @param {number} specificity Only keep configs with this specificity
|
||||
* @returns {Registry} A registry of rules
|
||||
*/
|
||||
filterBySpecificity(specificity) {
|
||||
const ruleIds = Object.keys(this.rules),
|
||||
@@ -253,10 +256,10 @@ class Registry {
|
||||
|
||||
/**
|
||||
* Lint SourceCodes against all configurations in the registry, and record results
|
||||
* @param {Object[]} sourceCodes SourceCode objects for each filename
|
||||
* @param {Object} config ESLint config object
|
||||
* @param {progressCallback} [cb] Optional callback for reporting execution status
|
||||
* @returns {Registry} New registry with errorCount populated
|
||||
* @param {Object[]} sourceCodes SourceCode objects for each filename
|
||||
* @param {Object} config ESLint config object
|
||||
* @param {progressCallback} [cb] Optional callback for reporting execution status
|
||||
* @returns {Registry} New registry with errorCount populated
|
||||
*/
|
||||
lintSourceCode(sourceCodes, config, cb) {
|
||||
let lintedRegistry = new Registry();
|
||||
@@ -301,7 +304,7 @@ class Registry {
|
||||
ruleSetIdx += 1;
|
||||
|
||||
if (cb) {
|
||||
cb(totalFilesLinting); // eslint-disable-line node/callback-return
|
||||
cb(totalFilesLinting); // eslint-disable-line node/callback-return -- End of function
|
||||
}
|
||||
});
|
||||
|
||||
@@ -318,8 +321,8 @@ class Registry {
|
||||
*
|
||||
* This will return a new config with `["extends": [ ..., "eslint:recommended"]` and
|
||||
* only the rules which have configurations different from the recommended config.
|
||||
* @param {Object} config config object
|
||||
* @returns {Object} config object using `"extends": ["eslint:recommended"]`
|
||||
* @param {Object} config config object
|
||||
* @returns {Object} config object using `"extends": ["eslint:recommended"]`
|
||||
*/
|
||||
function extendFromRecommended(config) {
|
||||
const newConfig = Object.assign({}, config);
|
||||
|
||||
+4
-4
@@ -23,9 +23,9 @@ const debug = require("debug")("eslint:config-file");
|
||||
* Determines sort order for object keys for json-stable-stringify
|
||||
*
|
||||
* see: https://github.com/samn/json-stable-stringify#cmp
|
||||
* @param {Object} a The first comparison object ({key: akey, value: avalue})
|
||||
* @param {Object} b The second comparison object ({key: bkey, value: bvalue})
|
||||
* @returns {number} 1 or -1, used in stringify cmp method
|
||||
* @param {Object} a The first comparison object ({key: akey, value: avalue})
|
||||
* @param {Object} b The second comparison object ({key: bkey, value: bvalue})
|
||||
* @returns {number} 1 or -1, used in stringify cmp method
|
||||
*/
|
||||
function sortByKey(a, b) {
|
||||
return a.key > b.key ? 1 : -1;
|
||||
@@ -63,7 +63,7 @@ function writeYAMLConfigFile(config, filePath) {
|
||||
// lazy load YAML to improve performance when not used
|
||||
const yaml = require("js-yaml");
|
||||
|
||||
const content = yaml.safeDump(config, { sortKeys: true });
|
||||
const content = yaml.dump(config, { sortKeys: true });
|
||||
|
||||
fs.writeFileSync(filePath, content, "utf8");
|
||||
}
|
||||
|
||||
+17
-12
@@ -18,9 +18,13 @@ const util = require("util"),
|
||||
semver = require("semver"),
|
||||
espree = require("espree"),
|
||||
recConfig = require("../../conf/eslint-recommended"),
|
||||
ConfigOps = require("@eslint/eslintrc/lib/shared/config-ops"),
|
||||
{
|
||||
Legacy: {
|
||||
ConfigOps,
|
||||
naming
|
||||
}
|
||||
} = require("@eslint/eslintrc"),
|
||||
log = require("../shared/logging"),
|
||||
naming = require("@eslint/eslintrc/lib/shared/naming"),
|
||||
ModuleResolver = require("../shared/relative-module-resolver"),
|
||||
autoconfig = require("./autoconfig.js"),
|
||||
ConfigFile = require("./config-file"),
|
||||
@@ -98,8 +102,8 @@ getPeerDependencies.cache = new Map();
|
||||
|
||||
/**
|
||||
* Return necessary plugins, configs, parsers, etc. based on the config
|
||||
* @param {Object} config config object
|
||||
* @param {boolean} [installESLint=true] If `false` is given, it does not install eslint.
|
||||
* @param {Object} config config object
|
||||
* @param {boolean} [installESLint=true] If `false` is given, it does not install eslint.
|
||||
* @returns {string[]} An array of modules to be installed.
|
||||
*/
|
||||
function getModulesList(config, installESLint) {
|
||||
@@ -157,9 +161,10 @@ function getModulesList(config, installESLint) {
|
||||
*
|
||||
* Note: This clones the config object and returns a new config to avoid mutating
|
||||
* the original config parameter.
|
||||
* @param {Object} answers answers received from enquirer
|
||||
* @param {Object} config config object
|
||||
* @returns {Object} config object with configured rules
|
||||
* @param {Object} answers answers received from enquirer
|
||||
* @param {Object} config config object
|
||||
* @throws {Error} If source code retrieval fails or source code file count is 0.
|
||||
* @returns {Object} config object with configured rules
|
||||
*/
|
||||
function configureRules(answers, config) {
|
||||
const BAR_TOTAL = 20,
|
||||
@@ -411,7 +416,7 @@ function hasESLintVersionConflict(answers) {
|
||||
|
||||
/**
|
||||
* Install modules.
|
||||
* @param {string[]} modules Modules to be installed.
|
||||
* @param {string[]} modules Modules to be installed.
|
||||
* @returns {void}
|
||||
*/
|
||||
function installModules(modules) {
|
||||
@@ -422,9 +427,9 @@ function installModules(modules) {
|
||||
/* istanbul ignore next: no need to test enquirer */
|
||||
/**
|
||||
* Ask user to install modules.
|
||||
* @param {string[]} modules Array of modules to be installed.
|
||||
* @param {boolean} packageJsonExists Indicates if package.json is existed.
|
||||
* @returns {Promise} Answer that indicates if user wants to install.
|
||||
* @param {string[]} modules Array of modules to be installed.
|
||||
* @param {boolean} packageJsonExists Indicates if package.json is existed.
|
||||
* @returns {Promise<void>} Answer that indicates if user wants to install.
|
||||
*/
|
||||
function askInstallModules(modules, packageJsonExists) {
|
||||
|
||||
@@ -460,7 +465,7 @@ function askInstallModules(modules, packageJsonExists) {
|
||||
/* istanbul ignore next: no need to test enquirer */
|
||||
/**
|
||||
* Ask use a few questions on command prompt
|
||||
* @returns {Promise} The promise with the result of the prompt
|
||||
* @returns {Promise<void>} The promise with the result of the prompt
|
||||
*/
|
||||
function promptUser() {
|
||||
|
||||
|
||||
+15
-16
@@ -17,8 +17,8 @@ const builtInRules = require("../rules");
|
||||
|
||||
/**
|
||||
* Wrap all of the elements of an array into arrays.
|
||||
* @param {*[]} xs Any array.
|
||||
* @returns {Array[]} An array of arrays.
|
||||
* @param {*[]} xs Any array.
|
||||
* @returns {Array[]} An array of arrays.
|
||||
*/
|
||||
function explodeArray(xs) {
|
||||
return xs.reduce((accumulator, x) => {
|
||||
@@ -33,9 +33,9 @@ function explodeArray(xs) {
|
||||
*
|
||||
* For example:
|
||||
* combineArrays([a, [b, c]], [x, y]); // -> [[a, x], [a, y], [b, c, x], [b, c, y]]
|
||||
* @param {Array} arr1 The first array to combine.
|
||||
* @param {Array} arr2 The second array to combine.
|
||||
* @returns {Array} A mixture of the elements of the first and second arrays.
|
||||
* @param {Array} arr1 The first array to combine.
|
||||
* @param {Array} arr2 The second array to combine.
|
||||
* @returns {Array} A mixture of the elements of the first and second arrays.
|
||||
*/
|
||||
function combineArrays(arr1, arr2) {
|
||||
const res = [];
|
||||
@@ -70,8 +70,8 @@ function combineArrays(arr1, arr2) {
|
||||
* [{before: true}, {before: false}],
|
||||
* [{after: true}, {after: false}]
|
||||
* ]
|
||||
* @param {Object[]} objects Array of objects, each with one property/value pair
|
||||
* @returns {Array[]} Array of arrays of objects grouped by property
|
||||
* @param {Object[]} objects Array of objects, each with one property/value pair
|
||||
* @returns {Array[]} Array of arrays of objects grouped by property
|
||||
*/
|
||||
function groupByProperty(objects) {
|
||||
const groupedObj = objects.reduce((accumulator, obj) => {
|
||||
@@ -97,7 +97,7 @@ function groupByProperty(objects) {
|
||||
* Configs may also have one or more additional elements to specify rule
|
||||
* configuration or options.
|
||||
* @typedef {Array|number} ruleConfig
|
||||
* @param {number} 0 The rule's severity (0, 1, 2).
|
||||
* @param {number} 0 The rule's severity (0, 1, 2).
|
||||
*/
|
||||
|
||||
/**
|
||||
@@ -131,9 +131,9 @@ function groupByProperty(objects) {
|
||||
* {before: false, after: true},
|
||||
* {before: false, after: false}
|
||||
* ]
|
||||
* @param {Object[]} objArr1 Single key/value objects, all with the same key
|
||||
* @param {Object[]} objArr2 Single key/value objects, all with another key
|
||||
* @returns {Object[]} Combined objects for each combination of input properties and values
|
||||
* @param {Object[]} objArr1 Single key/value objects, all with the same key
|
||||
* @param {Object[]} objArr2 Single key/value objects, all with another key
|
||||
* @returns {Object[]} Combined objects for each combination of input properties and values
|
||||
*/
|
||||
function combinePropertyObjects(objArr1, objArr2) {
|
||||
const res = [];
|
||||
@@ -174,7 +174,6 @@ function combinePropertyObjects(objArr1, objArr2) {
|
||||
*/
|
||||
class RuleConfigSet {
|
||||
|
||||
// eslint-disable-next-line jsdoc/require-description
|
||||
/**
|
||||
* @param {ruleConfig[]} configs Valid rule configurations
|
||||
*/
|
||||
@@ -206,7 +205,7 @@ class RuleConfigSet {
|
||||
|
||||
/**
|
||||
* Add rule configs from an array of strings (schema enums)
|
||||
* @param {string[]} enums Array of valid rule options (e.g. ["always", "never"])
|
||||
* @param {string[]} enums Array of valid rule options (e.g. ["always", "never"])
|
||||
* @returns {void}
|
||||
*/
|
||||
addEnums(enums) {
|
||||
@@ -215,7 +214,7 @@ class RuleConfigSet {
|
||||
|
||||
/**
|
||||
* Add rule configurations from a schema object
|
||||
* @param {Object} obj Schema item with type === "object"
|
||||
* @param {Object} obj Schema item with type === "object"
|
||||
* @returns {boolean} true if at least one schema for the object could be generated, false otherwise
|
||||
*/
|
||||
addObject(obj) {
|
||||
@@ -260,8 +259,8 @@ class RuleConfigSet {
|
||||
|
||||
/**
|
||||
* Generate valid rule configurations based on a schema object
|
||||
* @param {Object} schema A rule's schema object
|
||||
* @returns {Array[]} Valid rule configurations
|
||||
* @param {Object} schema A rule's schema object
|
||||
* @returns {Array[]} Valid rule configurations
|
||||
*/
|
||||
function generateConfigsFromSchema(schema) {
|
||||
const configSet = new RuleConfigSet();
|
||||
|
||||
+16
-15
@@ -21,8 +21,8 @@ const fs = require("fs"),
|
||||
/**
|
||||
* Find the closest package.json file, starting at process.cwd (by default),
|
||||
* and working up to root.
|
||||
* @param {string} [startDir=process.cwd()] Starting directory
|
||||
* @returns {string} Absolute path to closest package.json file
|
||||
* @param {string} [startDir=process.cwd()] Starting directory
|
||||
* @returns {string} Absolute path to closest package.json file
|
||||
*/
|
||||
function findPackageJson(startDir) {
|
||||
let dir = path.resolve(startDir || process.cwd());
|
||||
@@ -45,7 +45,7 @@ function findPackageJson(startDir) {
|
||||
|
||||
/**
|
||||
* Install node modules synchronously and save to devDependencies in package.json
|
||||
* @param {string|string[]} packages Node module or modules to install
|
||||
* @param {string|string[]} packages Node module or modules to install
|
||||
* @returns {void}
|
||||
*/
|
||||
function installSyncSaveDev(packages) {
|
||||
@@ -86,12 +86,13 @@ function fetchPeerDependencies(packageName) {
|
||||
|
||||
/**
|
||||
* Check whether node modules are include in a project's package.json.
|
||||
* @param {string[]} packages Array of node module names
|
||||
* @param {Object} opt Options Object
|
||||
* @param {boolean} opt.dependencies Set to true to check for direct dependencies
|
||||
* @param {boolean} opt.devDependencies Set to true to check for development dependencies
|
||||
* @param {boolean} opt.startdir Directory to begin searching from
|
||||
* @returns {Object} An object whose keys are the module names
|
||||
* @param {string[]} packages Array of node module names
|
||||
* @param {Object} opt Options Object
|
||||
* @param {boolean} opt.dependencies Set to true to check for direct dependencies
|
||||
* @param {boolean} opt.devDependencies Set to true to check for development dependencies
|
||||
* @param {boolean} opt.startdir Directory to begin searching from
|
||||
* @throws {Error} If cannot find valid `package.json` file.
|
||||
* @returns {Object} An object whose keys are the module names
|
||||
* and values are booleans indicating installation.
|
||||
*/
|
||||
function check(packages, opt) {
|
||||
@@ -133,9 +134,9 @@ function check(packages, opt) {
|
||||
* package.json.
|
||||
*
|
||||
* Convenience wrapper around check().
|
||||
* @param {string[]} packages Array of node modules to check.
|
||||
* @param {string} rootDir The directory containing a package.json
|
||||
* @returns {Object} An object whose keys are the module names
|
||||
* @param {string[]} packages Array of node modules to check.
|
||||
* @param {string} rootDir The directory containing a package.json
|
||||
* @returns {Object} An object whose keys are the module names
|
||||
* and values are booleans indicating installation.
|
||||
*/
|
||||
function checkDeps(packages, rootDir) {
|
||||
@@ -147,8 +148,8 @@ function checkDeps(packages, rootDir) {
|
||||
* package.json.
|
||||
*
|
||||
* Convenience wrapper around check().
|
||||
* @param {string[]} packages Array of node modules to check.
|
||||
* @returns {Object} An object whose keys are the module names
|
||||
* @param {string[]} packages Array of node modules to check.
|
||||
* @returns {Object} An object whose keys are the module names
|
||||
* and values are booleans indicating installation.
|
||||
*/
|
||||
function checkDevDeps(packages) {
|
||||
@@ -157,7 +158,7 @@ function checkDevDeps(packages) {
|
||||
|
||||
/**
|
||||
* Check whether package.json is found in current path.
|
||||
* @param {string} [startDir] Starting directory
|
||||
* @param {string} [startDir] Starting directory
|
||||
* @returns {boolean} Whether a package.json is found in current path.
|
||||
*/
|
||||
function checkPackageJson(startDir) {
|
||||
|
||||
+6
-5
@@ -23,7 +23,7 @@ const { CLIEngine } = require("../cli-engine");
|
||||
* TODO1: Expose the API that enumerates target files.
|
||||
* TODO2: Extract the creation logic of `SourceCode` from `Linter` class.
|
||||
*/
|
||||
const { getCLIEngineInternalSlots } = require("../cli-engine/cli-engine"); // eslint-disable-line node/no-restricted-require
|
||||
const { getCLIEngineInternalSlots } = require("../cli-engine/cli-engine"); // eslint-disable-line node/no-restricted-require -- Todo
|
||||
|
||||
const debug = require("debug")("eslint:source-code-utils");
|
||||
|
||||
@@ -33,9 +33,10 @@ const debug = require("debug")("eslint:source-code-utils");
|
||||
|
||||
/**
|
||||
* Get the SourceCode object for a single file
|
||||
* @param {string} filename The fully resolved filename to get SourceCode from.
|
||||
* @param {Object} engine A CLIEngine.
|
||||
* @returns {Array} Array of the SourceCode object representing the file
|
||||
* @param {string} filename The fully resolved filename to get SourceCode from.
|
||||
* @param {Object} engine A CLIEngine.
|
||||
* @throws {Error} Upon fatal errors from execution.
|
||||
* @returns {Array} Array of the SourceCode object representing the file
|
||||
* and fatal error message.
|
||||
*/
|
||||
function getSourceCodeOfFile(filename, engine) {
|
||||
@@ -97,7 +98,7 @@ function getSourceCodeOfFiles(patterns, options, callback) {
|
||||
sourceCodes[filename] = sourceCode;
|
||||
}
|
||||
if (callback) {
|
||||
callback(filenames.length); // eslint-disable-line node/callback-return
|
||||
callback(filenames.length); // eslint-disable-line node/callback-return -- End of function
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
+191
-24
@@ -5,6 +5,8 @@
|
||||
|
||||
"use strict";
|
||||
|
||||
const escapeRegExp = require("escape-string-regexp");
|
||||
|
||||
/**
|
||||
* Compares the locations of two objects in a source file
|
||||
* @param {{line: number, column: number}} itemA The first object
|
||||
@@ -16,6 +18,177 @@ function compareLocations(itemA, itemB) {
|
||||
return itemA.line - itemB.line || itemA.column - itemB.column;
|
||||
}
|
||||
|
||||
/**
|
||||
* Groups a set of directives into sub-arrays by their parent comment.
|
||||
* @param {Directive[]} directives Unused directives to be removed.
|
||||
* @returns {Directive[][]} Directives grouped by their parent comment.
|
||||
*/
|
||||
function groupByParentComment(directives) {
|
||||
const groups = new Map();
|
||||
|
||||
for (const directive of directives) {
|
||||
const { unprocessedDirective: { parentComment } } = directive;
|
||||
|
||||
if (groups.has(parentComment)) {
|
||||
groups.get(parentComment).push(directive);
|
||||
} else {
|
||||
groups.set(parentComment, [directive]);
|
||||
}
|
||||
}
|
||||
|
||||
return [...groups.values()];
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates removal details for a set of directives within the same comment.
|
||||
* @param {Directive[]} directives Unused directives to be removed.
|
||||
* @param {Token} commentToken The backing Comment token.
|
||||
* @returns {{ description, fix, position }[]} Details for later creation of output Problems.
|
||||
*/
|
||||
function createIndividualDirectivesRemoval(directives, commentToken) {
|
||||
|
||||
/*
|
||||
* `commentToken.value` starts right after `//` or `/*`.
|
||||
* All calculated offsets will be relative to this index.
|
||||
*/
|
||||
const commentValueStart = commentToken.range[0] + "//".length;
|
||||
|
||||
// Find where the list of rules starts. `\S+` matches with the directive name (e.g. `eslint-disable-line`)
|
||||
const listStartOffset = /^\s*\S+\s+/u.exec(commentToken.value)[0].length;
|
||||
|
||||
/*
|
||||
* Get the list text without any surrounding whitespace. In order to preserve the original
|
||||
* formatting, we don't want to change that whitespace.
|
||||
*
|
||||
* // eslint-disable-line rule-one , rule-two , rule-three -- comment
|
||||
* ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
*/
|
||||
const listText = commentToken.value
|
||||
.slice(listStartOffset) // remove directive name and all whitespace before the list
|
||||
.split(/\s-{2,}\s/u)[0] // remove `-- comment`, if it exists
|
||||
.trimRight(); // remove all whitespace after the list
|
||||
|
||||
/*
|
||||
* We can assume that `listText` contains multiple elements.
|
||||
* Otherwise, this function wouldn't be called - if there is
|
||||
* only one rule in the list, then the whole comment must be removed.
|
||||
*/
|
||||
|
||||
return directives.map(directive => {
|
||||
const { ruleId } = directive;
|
||||
|
||||
const regex = new RegExp(String.raw`(?:^|\s*,\s*)${escapeRegExp(ruleId)}(?:\s*,\s*|$)`, "u");
|
||||
const match = regex.exec(listText);
|
||||
const matchedText = match[0];
|
||||
const matchStartOffset = listStartOffset + match.index;
|
||||
const matchEndOffset = matchStartOffset + matchedText.length;
|
||||
|
||||
const firstIndexOfComma = matchedText.indexOf(",");
|
||||
const lastIndexOfComma = matchedText.lastIndexOf(",");
|
||||
|
||||
let removalStartOffset, removalEndOffset;
|
||||
|
||||
if (firstIndexOfComma !== lastIndexOfComma) {
|
||||
|
||||
/*
|
||||
* Since there are two commas, this must one of the elements in the middle of the list.
|
||||
* Matched range starts where the previous rule name ends, and ends where the next rule name starts.
|
||||
*
|
||||
* // eslint-disable-line rule-one , rule-two , rule-three -- comment
|
||||
* ^^^^^^^^^^^^^^
|
||||
*
|
||||
* We want to remove only the content between the two commas, and also one of the commas.
|
||||
*
|
||||
* // eslint-disable-line rule-one , rule-two , rule-three -- comment
|
||||
* ^^^^^^^^^^^
|
||||
*/
|
||||
removalStartOffset = matchStartOffset + firstIndexOfComma;
|
||||
removalEndOffset = matchStartOffset + lastIndexOfComma;
|
||||
|
||||
} else {
|
||||
|
||||
/*
|
||||
* This is either the first element or the last element.
|
||||
*
|
||||
* If this is the first element, matched range starts where the first rule name starts
|
||||
* and ends where the second rule name starts. This is exactly the range we want
|
||||
* to remove so that the second rule name will start where the first one was starting
|
||||
* and thus preserve the original formatting.
|
||||
*
|
||||
* // eslint-disable-line rule-one , rule-two , rule-three -- comment
|
||||
* ^^^^^^^^^^^
|
||||
*
|
||||
* Similarly, if this is the last element, we've already matched the range we want to
|
||||
* remove. The previous rule name will end where the last one was ending, relative
|
||||
* to the content on the right side.
|
||||
*
|
||||
* // eslint-disable-line rule-one , rule-two , rule-three -- comment
|
||||
* ^^^^^^^^^^^^^
|
||||
*/
|
||||
removalStartOffset = matchStartOffset;
|
||||
removalEndOffset = matchEndOffset;
|
||||
}
|
||||
|
||||
return {
|
||||
description: `'${ruleId}'`,
|
||||
fix: {
|
||||
range: [
|
||||
commentValueStart + removalStartOffset,
|
||||
commentValueStart + removalEndOffset
|
||||
],
|
||||
text: ""
|
||||
},
|
||||
position: directive.unprocessedDirective
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a description of deleting an entire unused disable comment.
|
||||
* @param {Directive[]} directives Unused directives to be removed.
|
||||
* @param {Token} commentToken The backing Comment token.
|
||||
* @returns {{ description, fix, position }} Details for later creation of an output Problem.
|
||||
*/
|
||||
function createCommentRemoval(directives, commentToken) {
|
||||
const { range } = commentToken;
|
||||
const ruleIds = directives.filter(directive => directive.ruleId).map(directive => `'${directive.ruleId}'`);
|
||||
|
||||
return {
|
||||
description: ruleIds.length <= 2
|
||||
? ruleIds.join(" or ")
|
||||
: `${ruleIds.slice(0, ruleIds.length - 1).join(", ")}, or ${ruleIds[ruleIds.length - 1]}`,
|
||||
fix: {
|
||||
range,
|
||||
text: " "
|
||||
},
|
||||
position: directives[0].unprocessedDirective
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses details from directives to create output Problems.
|
||||
* @param {Directive[]} allDirectives Unused directives to be removed.
|
||||
* @returns {{ description, fix, position }[]} Details for later creation of output Problems.
|
||||
*/
|
||||
function processUnusedDisableDirectives(allDirectives) {
|
||||
const directiveGroups = groupByParentComment(allDirectives);
|
||||
|
||||
return directiveGroups.flatMap(
|
||||
directives => {
|
||||
const { parentComment } = directives[0].unprocessedDirective;
|
||||
const remainingRuleIds = new Set(parentComment.ruleIds);
|
||||
|
||||
for (const directive of directives) {
|
||||
remainingRuleIds.delete(directive.ruleId);
|
||||
}
|
||||
|
||||
return remainingRuleIds.size
|
||||
? createIndividualDirectivesRemoval(directives, parentComment.commentToken)
|
||||
: [createCommentRemoval(directives, parentComment.commentToken)];
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* This is the same as the exported function, except that it
|
||||
* doesn't handle disable-line and disable-next-line directives, and it always reports unused
|
||||
@@ -82,17 +255,22 @@ function applyDirectives(options) {
|
||||
}
|
||||
}
|
||||
|
||||
const unusedDisableDirectives = options.directives
|
||||
.filter(directive => directive.type === "disable" && !usedDisableDirectives.has(directive))
|
||||
.map(directive => ({
|
||||
const unusedDisableDirectivesToReport = options.directives
|
||||
.filter(directive => directive.type === "disable" && !usedDisableDirectives.has(directive));
|
||||
|
||||
const processed = processUnusedDisableDirectives(unusedDisableDirectivesToReport);
|
||||
|
||||
const unusedDisableDirectives = processed
|
||||
.map(({ description, fix, position }) => ({
|
||||
ruleId: null,
|
||||
message: directive.ruleId
|
||||
? `Unused eslint-disable directive (no problems were reported from '${directive.ruleId}').`
|
||||
message: description
|
||||
? `Unused eslint-disable directive (no problems were reported from ${description}).`
|
||||
: "Unused eslint-disable directive (no problems were reported).",
|
||||
line: directive.unprocessedDirective.line,
|
||||
column: directive.unprocessedDirective.column,
|
||||
line: position.line,
|
||||
column: position.column,
|
||||
severity: options.reportUnusedDisableDirectives === "warn" ? 1 : 2,
|
||||
nodeType: null
|
||||
nodeType: null,
|
||||
...options.disableFixes ? {} : { fix }
|
||||
}));
|
||||
|
||||
return { problems, unusedDisableDirectives };
|
||||
@@ -113,30 +291,17 @@ function applyDirectives(options) {
|
||||
* @param {{ruleId: (string|null), line: number, column: number}[]} options.problems
|
||||
* A list of problems reported by rules, sorted by increasing location in the file, with one-based columns.
|
||||
* @param {"off" | "warn" | "error"} options.reportUnusedDisableDirectives If `"warn"` or `"error"`, adds additional problems for unused directives
|
||||
* @param {boolean} options.disableFixes If true, it doesn't make `fix` properties.
|
||||
* @returns {{ruleId: (string|null), line: number, column: number}[]}
|
||||
* A list of reported problems that were not disabled by the directive comments.
|
||||
*/
|
||||
module.exports = ({ directives, problems, reportUnusedDisableDirectives = "off" }) => {
|
||||
module.exports = ({ directives, disableFixes, problems, reportUnusedDisableDirectives = "off" }) => {
|
||||
const blockDirectives = directives
|
||||
.filter(directive => directive.type === "disable" || directive.type === "enable")
|
||||
.map(directive => Object.assign({}, directive, { unprocessedDirective: directive }))
|
||||
.sort(compareLocations);
|
||||
|
||||
/**
|
||||
* Returns a new array formed by applying a given callback function to each element of the array, and then flattening the result by one level.
|
||||
* TODO(stephenwade): Replace this with array.flatMap when we drop support for Node v10
|
||||
* @param {any[]} array The array to process
|
||||
* @param {Function} fn The function to use
|
||||
* @returns {any[]} The result array
|
||||
*/
|
||||
function flatMap(array, fn) {
|
||||
const mapped = array.map(fn);
|
||||
const flattened = [].concat(...mapped);
|
||||
|
||||
return flattened;
|
||||
}
|
||||
|
||||
const lineDirectives = flatMap(directives, directive => {
|
||||
const lineDirectives = directives.flatMap(directive => {
|
||||
switch (directive.type) {
|
||||
case "disable":
|
||||
case "enable":
|
||||
@@ -162,11 +327,13 @@ module.exports = ({ directives, problems, reportUnusedDisableDirectives = "off"
|
||||
const blockDirectivesResult = applyDirectives({
|
||||
problems,
|
||||
directives: blockDirectives,
|
||||
disableFixes,
|
||||
reportUnusedDisableDirectives
|
||||
});
|
||||
const lineDirectivesResult = applyDirectives({
|
||||
problems: blockDirectivesResult.problems,
|
||||
directives: lineDirectives,
|
||||
disableFixes,
|
||||
reportUnusedDisableDirectives
|
||||
});
|
||||
|
||||
|
||||
+115
-36
@@ -29,6 +29,18 @@ function isCaseNode(node) {
|
||||
return Boolean(node.test);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if a given node appears as the value of a PropertyDefinition node.
|
||||
* @param {ASTNode} node THe node to check.
|
||||
* @returns {boolean} `true` if the node is a PropertyDefinition value,
|
||||
* false if not.
|
||||
*/
|
||||
function isPropertyDefinitionValue(node) {
|
||||
const parent = node.parent;
|
||||
|
||||
return parent && parent.type === "PropertyDefinition" && parent.value === node;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether the given logical operator is taken into account for the code
|
||||
* path analysis.
|
||||
@@ -138,6 +150,7 @@ function isIdentifierReference(node) {
|
||||
return parent.id !== node;
|
||||
|
||||
case "Property":
|
||||
case "PropertyDefinition":
|
||||
case "MethodDefinition":
|
||||
return (
|
||||
parent.key !== node ||
|
||||
@@ -388,29 +401,64 @@ function processCodePathToEnter(analyzer, node) {
|
||||
let state = codePath && CodePath.getState(codePath);
|
||||
const parent = node.parent;
|
||||
|
||||
/**
|
||||
* Creates a new code path and trigger the onCodePathStart event
|
||||
* based on the currently selected node.
|
||||
* @param {string} origin The reason the code path was started.
|
||||
* @returns {void}
|
||||
*/
|
||||
function startCodePath(origin) {
|
||||
if (codePath) {
|
||||
|
||||
// Emits onCodePathSegmentStart events if updated.
|
||||
forwardCurrentToHead(analyzer, node);
|
||||
debug.dumpState(node, state, false);
|
||||
}
|
||||
|
||||
// Create the code path of this scope.
|
||||
codePath = analyzer.codePath = new CodePath({
|
||||
id: analyzer.idGenerator.next(),
|
||||
origin,
|
||||
upper: codePath,
|
||||
onLooped: analyzer.onLooped
|
||||
});
|
||||
state = CodePath.getState(codePath);
|
||||
|
||||
// Emits onCodePathStart events.
|
||||
debug.dump(`onCodePathStart ${codePath.id}`);
|
||||
analyzer.emitter.emit("onCodePathStart", codePath, node);
|
||||
}
|
||||
|
||||
/*
|
||||
* Special case: The right side of class field initializer is considered
|
||||
* to be its own function, so we need to start a new code path in this
|
||||
* case.
|
||||
*/
|
||||
if (isPropertyDefinitionValue(node)) {
|
||||
startCodePath("class-field-initializer");
|
||||
|
||||
/*
|
||||
* Intentional fall through because `node` needs to also be
|
||||
* processed by the code below. For example, if we have:
|
||||
*
|
||||
* class Foo {
|
||||
* a = () => {}
|
||||
* }
|
||||
*
|
||||
* In this case, we also need start a second code path.
|
||||
*/
|
||||
|
||||
}
|
||||
|
||||
switch (node.type) {
|
||||
case "Program":
|
||||
startCodePath("program");
|
||||
break;
|
||||
|
||||
case "FunctionDeclaration":
|
||||
case "FunctionExpression":
|
||||
case "ArrowFunctionExpression":
|
||||
if (codePath) {
|
||||
|
||||
// Emits onCodePathSegmentStart events if updated.
|
||||
forwardCurrentToHead(analyzer, node);
|
||||
debug.dumpState(node, state, false);
|
||||
}
|
||||
|
||||
// Create the code path of this scope.
|
||||
codePath = analyzer.codePath = new CodePath(
|
||||
analyzer.idGenerator.next(),
|
||||
codePath,
|
||||
analyzer.onLooped
|
||||
);
|
||||
state = CodePath.getState(codePath);
|
||||
|
||||
// Emits onCodePathStart events.
|
||||
debug.dump(`onCodePathStart ${codePath.id}`);
|
||||
analyzer.emitter.emit("onCodePathStart", codePath, node);
|
||||
startCodePath("function");
|
||||
break;
|
||||
|
||||
case "ChainExpression":
|
||||
@@ -503,6 +551,7 @@ function processCodePathToEnter(analyzer, node) {
|
||||
* @returns {void}
|
||||
*/
|
||||
function processCodePathToExit(analyzer, node) {
|
||||
|
||||
const codePath = analyzer.codePath;
|
||||
const state = CodePath.getState(codePath);
|
||||
let dontForward = false;
|
||||
@@ -627,28 +676,38 @@ function processCodePathToExit(analyzer, node) {
|
||||
* @returns {void}
|
||||
*/
|
||||
function postprocess(analyzer, node) {
|
||||
|
||||
/**
|
||||
* Ends the code path for the current node.
|
||||
* @returns {void}
|
||||
*/
|
||||
function endCodePath() {
|
||||
let codePath = analyzer.codePath;
|
||||
|
||||
// Mark the current path as the final node.
|
||||
CodePath.getState(codePath).makeFinal();
|
||||
|
||||
// Emits onCodePathSegmentEnd event of the current segments.
|
||||
leaveFromCurrentSegment(analyzer, node);
|
||||
|
||||
// Emits onCodePathEnd event of this code path.
|
||||
debug.dump(`onCodePathEnd ${codePath.id}`);
|
||||
analyzer.emitter.emit("onCodePathEnd", codePath, node);
|
||||
debug.dumpDot(codePath);
|
||||
|
||||
codePath = analyzer.codePath = analyzer.codePath.upper;
|
||||
if (codePath) {
|
||||
debug.dumpState(node, CodePath.getState(codePath), true);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
switch (node.type) {
|
||||
case "Program":
|
||||
case "FunctionDeclaration":
|
||||
case "FunctionExpression":
|
||||
case "ArrowFunctionExpression": {
|
||||
let codePath = analyzer.codePath;
|
||||
|
||||
// Mark the current path as the final node.
|
||||
CodePath.getState(codePath).makeFinal();
|
||||
|
||||
// Emits onCodePathSegmentEnd event of the current segments.
|
||||
leaveFromCurrentSegment(analyzer, node);
|
||||
|
||||
// Emits onCodePathEnd event of this code path.
|
||||
debug.dump(`onCodePathEnd ${codePath.id}`);
|
||||
analyzer.emitter.emit("onCodePathEnd", codePath, node);
|
||||
debug.dumpDot(codePath);
|
||||
|
||||
codePath = analyzer.codePath = analyzer.codePath.upper;
|
||||
if (codePath) {
|
||||
debug.dumpState(node, CodePath.getState(codePath), true);
|
||||
}
|
||||
endCodePath();
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -662,6 +721,27 @@ function postprocess(analyzer, node) {
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
/*
|
||||
* Special case: The right side of class field initializer is considered
|
||||
* to be its own function, so we need to end a code path in this
|
||||
* case.
|
||||
*
|
||||
* We need to check after the other checks in order to close the
|
||||
* code paths in the correct order for code like this:
|
||||
*
|
||||
*
|
||||
* class Foo {
|
||||
* a = () => {}
|
||||
* }
|
||||
*
|
||||
* In this case, The ArrowFunctionExpression code path is closed first
|
||||
* and then we need to close the code path for the PropertyDefinition
|
||||
* value.
|
||||
*/
|
||||
if (isPropertyDefinitionValue(node)) {
|
||||
endCodePath();
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
@@ -674,7 +754,6 @@ function postprocess(analyzer, node) {
|
||||
*/
|
||||
class CodePathAnalyzer {
|
||||
|
||||
// eslint-disable-next-line jsdoc/require-description
|
||||
/**
|
||||
* @param {EventGenerator} eventGenerator An event generator to wrap.
|
||||
*/
|
||||
|
||||
-1
@@ -33,7 +33,6 @@ function isReachable(segment) {
|
||||
*/
|
||||
class CodePathSegment {
|
||||
|
||||
// eslint-disable-next-line jsdoc/require-description
|
||||
/**
|
||||
* @param {string} id An identifier.
|
||||
* @param {CodePathSegment[]} allPrevSegments An array of the previous segments.
|
||||
|
||||
+4
-1
@@ -219,7 +219,6 @@ function finalizeTestSegmentsOfFor(context, choiceContext, head) {
|
||||
*/
|
||||
class CodePathState {
|
||||
|
||||
// eslint-disable-next-line jsdoc/require-description
|
||||
/**
|
||||
* @param {IdGenerator} idGenerator An id generator to generate id for code
|
||||
* path segments.
|
||||
@@ -360,6 +359,7 @@ class CodePathState {
|
||||
|
||||
/**
|
||||
* Pops the last choice context and finalizes it.
|
||||
* @throws {Error} (Unreachable.)
|
||||
* @returns {ChoiceContext} The popped context.
|
||||
*/
|
||||
popChoiceContext() {
|
||||
@@ -450,6 +450,7 @@ class CodePathState {
|
||||
/**
|
||||
* Makes a code path segment of the right-hand operand of a logical
|
||||
* expression.
|
||||
* @throws {Error} (Unreachable.)
|
||||
* @returns {void}
|
||||
*/
|
||||
makeLogicalRight() {
|
||||
@@ -965,6 +966,7 @@ class CodePathState {
|
||||
* `WhileStatement`, `DoWhileStatement`, `ForStatement`, `ForInStatement`,
|
||||
* and `ForStatement`.
|
||||
* @param {string|null} label A label of the node which was triggered.
|
||||
* @throws {Error} (Unreachable - unknown type.)
|
||||
* @returns {void}
|
||||
*/
|
||||
pushLoopContext(type, label) {
|
||||
@@ -1036,6 +1038,7 @@ class CodePathState {
|
||||
|
||||
/**
|
||||
* Pops the last context of a loop statement and finalizes it.
|
||||
* @throws {Error} (Unreachable - unknown type.)
|
||||
* @returns {void}
|
||||
*/
|
||||
popLoopContext() {
|
||||
|
||||
+14
-5
@@ -21,13 +21,15 @@ const IdGenerator = require("./id-generator");
|
||||
*/
|
||||
class CodePath {
|
||||
|
||||
// eslint-disable-next-line jsdoc/require-description
|
||||
/**
|
||||
* @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.
|
||||
* Creates a new instance.
|
||||
* @param {Object} options Options for the function (see below).
|
||||
* @param {string} options.id An identifier.
|
||||
* @param {string} options.origin The type of code path origin.
|
||||
* @param {CodePath|null} options.upper The code path of the upper function scope.
|
||||
* @param {Function} options.onLooped A callback function to notify looping.
|
||||
*/
|
||||
constructor(id, upper, onLooped) {
|
||||
constructor({ id, origin, upper, onLooped }) {
|
||||
|
||||
/**
|
||||
* The identifier of this code path.
|
||||
@@ -36,6 +38,13 @@ class CodePath {
|
||||
*/
|
||||
this.id = id;
|
||||
|
||||
/**
|
||||
* The reason that this code path was started. May be "program",
|
||||
* "function", or "class-field-initializer".
|
||||
* @type {string}
|
||||
*/
|
||||
this.origin = origin;
|
||||
|
||||
/**
|
||||
* The code path of the upper function scope.
|
||||
* @type {CodePath|null}
|
||||
|
||||
+2
-2
@@ -21,7 +21,7 @@ const debug = require("debug")("eslint:code-path");
|
||||
* @returns {string} Id of the segment.
|
||||
*/
|
||||
/* istanbul ignore next */
|
||||
function getId(segment) { // eslint-disable-line jsdoc/require-jsdoc
|
||||
function getId(segment) { // eslint-disable-line jsdoc/require-jsdoc -- Ignoring
|
||||
return segment.id + (segment.reachable ? "" : "!");
|
||||
}
|
||||
|
||||
@@ -115,7 +115,7 @@ module.exports = {
|
||||
const traceMap = Object.create(null);
|
||||
const arrows = this.makeDotArrows(codePath, traceMap);
|
||||
|
||||
for (const id in traceMap) { // eslint-disable-line guard-for-in
|
||||
for (const id in traceMap) { // eslint-disable-line guard-for-in -- Want ability to traverse prototype
|
||||
const segment = traceMap[id];
|
||||
|
||||
text += `${id}[`;
|
||||
|
||||
-1
@@ -97,7 +97,6 @@ function mergeExtraSegments(context, segments) {
|
||||
*/
|
||||
class ForkContext {
|
||||
|
||||
// eslint-disable-next-line jsdoc/require-description
|
||||
/**
|
||||
* @param {IdGenerator} idGenerator An identifier generator for segments.
|
||||
* @param {ForkContext|null} upper An upper fork context.
|
||||
|
||||
-1
@@ -18,7 +18,6 @@
|
||||
*/
|
||||
class IdGenerator {
|
||||
|
||||
// eslint-disable-next-line jsdoc/require-description
|
||||
/**
|
||||
* @param {string} prefix Optional. A prefix of generated ids.
|
||||
*/
|
||||
|
||||
+6
-2
@@ -3,7 +3,7 @@
|
||||
* @author Nicholas C. Zakas
|
||||
*/
|
||||
|
||||
/* eslint-disable class-methods-use-this*/
|
||||
/* eslint class-methods-use-this: off -- Methods desired on instance */
|
||||
"use strict";
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
@@ -11,7 +11,11 @@
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
const levn = require("levn"),
|
||||
ConfigOps = require("@eslint/eslintrc/lib/shared/config-ops");
|
||||
{
|
||||
Legacy: {
|
||||
ConfigOps
|
||||
}
|
||||
} = require("@eslint/eslintrc/universal"); // eslint-disable-line node/no-missing-require -- false positive
|
||||
|
||||
const debug = require("debug")("eslint:config-comment-parser");
|
||||
|
||||
|
||||
+73
-30
@@ -16,11 +16,15 @@ const
|
||||
evk = require("eslint-visitor-keys"),
|
||||
espree = require("espree"),
|
||||
merge = require("lodash.merge"),
|
||||
BuiltInEnvironments = require("@eslint/eslintrc/conf/environments"),
|
||||
pkg = require("../../package.json"),
|
||||
astUtils = require("../shared/ast-utils"),
|
||||
ConfigOps = require("@eslint/eslintrc/lib/shared/config-ops"),
|
||||
ConfigValidator = require("@eslint/eslintrc/lib/shared/config-validator"),
|
||||
{
|
||||
Legacy: {
|
||||
ConfigOps,
|
||||
ConfigValidator,
|
||||
environments: BuiltInEnvironments
|
||||
}
|
||||
} = require("@eslint/eslintrc/universal"), // eslint-disable-line node/no-missing-require -- false positive
|
||||
Traverser = require("../shared/traverser"),
|
||||
{ SourceCode } = require("../source-code"),
|
||||
CodePathAnalyzer = require("./code-path-analysis/code-path-analyzer"),
|
||||
@@ -46,8 +50,8 @@ const parserSymbol = Symbol.for("eslint.RuleTester.parser");
|
||||
// Typedefs
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
/** @typedef {InstanceType<import("../cli-engine/config-array")["ConfigArray"]>} ConfigArray */
|
||||
/** @typedef {InstanceType<import("../cli-engine/config-array")["ExtractedConfig"]>} ExtractedConfig */
|
||||
/** @typedef {InstanceType<import("../cli-engine/config-array").ConfigArray>} ConfigArray */
|
||||
/** @typedef {InstanceType<import("../cli-engine/config-array").ExtractedConfig>} ExtractedConfig */
|
||||
/** @typedef {import("../shared/types").ConfigData} ConfigData */
|
||||
/** @typedef {import("../shared/types").Environment} Environment */
|
||||
/** @typedef {import("../shared/types").GlobalConf} GlobalConf */
|
||||
@@ -56,17 +60,19 @@ const parserSymbol = Symbol.for("eslint.RuleTester.parser");
|
||||
/** @typedef {import("../shared/types").Processor} Processor */
|
||||
/** @typedef {import("../shared/types").Rule} Rule */
|
||||
|
||||
/* eslint-disable jsdoc/valid-types -- https://github.com/jsdoc-type-pratt-parser/jsdoc-type-pratt-parser/issues/4#issuecomment-778805577 */
|
||||
/**
|
||||
* @template T
|
||||
* @typedef {{ [P in keyof T]-?: T[P] }} Required
|
||||
*/
|
||||
/* eslint-enable jsdoc/valid-types -- https://github.com/jsdoc-type-pratt-parser/jsdoc-type-pratt-parser/issues/4#issuecomment-778805577 */
|
||||
|
||||
/**
|
||||
* @typedef {Object} DisableDirective
|
||||
* @property {("disable"|"enable"|"disable-line"|"disable-next-line")} type
|
||||
* @property {number} line
|
||||
* @property {number} column
|
||||
* @property {(string|null)} ruleId
|
||||
* @property {("disable"|"enable"|"disable-line"|"disable-next-line")} type Type of directive
|
||||
* @property {number} line The line number
|
||||
* @property {number} column The column number
|
||||
* @property {(string|null)} ruleId The rule ID
|
||||
*/
|
||||
|
||||
/**
|
||||
@@ -94,12 +100,12 @@ const parserSymbol = Symbol.for("eslint.RuleTester.parser");
|
||||
* @typedef {Object} ProcessorOptions
|
||||
* @property {(filename:string, text:string) => boolean} [filterCodeBlock] the
|
||||
* predicate function that selects adopt code blocks.
|
||||
* @property {Processor["postprocess"]} [postprocess] postprocessor for report
|
||||
* @property {Processor.postprocess} [postprocess] postprocessor for report
|
||||
* messages. If provided, this should accept an array of the message lists
|
||||
* for each code block returned from the preprocessor, apply a mapping to
|
||||
* the messages as appropriate, and return a one-dimensional array of
|
||||
* messages.
|
||||
* @property {Processor["preprocess"]} [preprocess] preprocessor for source text.
|
||||
* @property {Processor.preprocess} [preprocess] preprocessor for source text.
|
||||
* If provided, this should accept a string of source text, and return an
|
||||
* array of code blocks to lint.
|
||||
*/
|
||||
@@ -242,14 +248,14 @@ function createLintingProblem(options) {
|
||||
* Creates a collection of disable directives from a comment
|
||||
* @param {Object} options to create disable directives
|
||||
* @param {("disable"|"enable"|"disable-line"|"disable-next-line")} options.type The type of directive comment
|
||||
* @param {{line: number, column: number}} options.loc The 0-based location of the comment token
|
||||
* @param {token} options.commentToken The Comment token
|
||||
* @param {string} options.value The value after the directive in the comment
|
||||
* comment specified no specific rules, so it applies to all rules (e.g. `eslint-disable`)
|
||||
* @param {function(string): {create: Function}} options.ruleMapper A map from rule IDs to defined rules
|
||||
* @returns {Object} Directives and problems from the comment
|
||||
*/
|
||||
function createDisableDirectives(options) {
|
||||
const { type, loc, value, ruleMapper } = options;
|
||||
const { commentToken, type, value, ruleMapper } = options;
|
||||
const ruleIds = Object.keys(commentParser.parseListConfig(value));
|
||||
const directiveRules = ruleIds.length ? ruleIds : [null];
|
||||
const result = {
|
||||
@@ -257,13 +263,15 @@ function createDisableDirectives(options) {
|
||||
directiveProblems: [] // problems in directives
|
||||
};
|
||||
|
||||
const parentComment = { commentToken, ruleIds };
|
||||
|
||||
for (const ruleId of directiveRules) {
|
||||
|
||||
// push to directives, if the rule is defined(including null, e.g. /*eslint enable*/)
|
||||
if (ruleId === null || ruleMapper(ruleId) !== null) {
|
||||
result.directives.push({ type, line: loc.start.line, column: loc.start.column + 1, ruleId });
|
||||
result.directives.push({ parentComment, type, line: commentToken.loc.start.line, column: commentToken.loc.start.column + 1, ruleId });
|
||||
} else {
|
||||
result.directiveProblems.push(createLintingProblem({ ruleId, loc }));
|
||||
result.directiveProblems.push(createLintingProblem({ ruleId, loc: commentToken.loc }));
|
||||
}
|
||||
}
|
||||
return result;
|
||||
@@ -344,7 +352,7 @@ function getDirectiveComments(filename, ast, ruleMapper, warnInlineConfig) {
|
||||
case "eslint-disable-next-line":
|
||||
case "eslint-disable-line": {
|
||||
const directiveType = directiveText.slice("eslint-".length);
|
||||
const options = { type: directiveType, loc: comment.loc, value: directiveValue, ruleMapper };
|
||||
const options = { commentToken: comment, type: directiveType, value: directiveValue, ruleMapper };
|
||||
const { directives, directiveProblems } = createDisableDirectives(options);
|
||||
|
||||
disableDirectives.push(...directives);
|
||||
@@ -452,7 +460,7 @@ function normalizeEcmaVersion(parser, ecmaVersion) {
|
||||
return ecmaVersion >= 2015 ? ecmaVersion - 2009 : ecmaVersion;
|
||||
}
|
||||
|
||||
const eslintEnvPattern = /\/\*\s*eslint-env\s(.+?)\*\//gsu;
|
||||
const eslintEnvPattern = /\/\*\s*eslint-env\s(.+?)(?:\*\/|$)/gsu;
|
||||
|
||||
/**
|
||||
* Checks whether or not there is a comment which has "eslint-env *" in a given text.
|
||||
@@ -465,10 +473,12 @@ function findEslintEnv(text) {
|
||||
eslintEnvPattern.lastIndex = 0;
|
||||
|
||||
while ((match = eslintEnvPattern.exec(text)) !== null) {
|
||||
retv = Object.assign(
|
||||
retv || {},
|
||||
commentParser.parseListConfig(stripDirectiveComment(match[1]))
|
||||
);
|
||||
if (match[0].endsWith("*/")) {
|
||||
retv = Object.assign(
|
||||
retv || {},
|
||||
commentParser.parseListConfig(stripDirectiveComment(match[1]))
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return retv;
|
||||
@@ -758,6 +768,7 @@ function markVariableAsUsed(scopeManager, currentNode, parserOptions, name) {
|
||||
* Runs a rule, and gets its listeners
|
||||
* @param {Rule} rule A normalized rule with a `create` method
|
||||
* @param {Context} ruleContext The context that should be passed to the rule
|
||||
* @throws {any} Any error during the rule's `create`
|
||||
* @returns {Object} A map of selector listeners provided by the rule
|
||||
*/
|
||||
function createRuleListeners(rule, ruleContext) {
|
||||
@@ -925,8 +936,16 @@ function runRules(sourceCode, configuredRules, ruleMapper, parserOptions, parser
|
||||
}
|
||||
const problem = reportTranslator(...args);
|
||||
|
||||
if (problem.fix && rule.meta && !rule.meta.fixable) {
|
||||
throw new Error("Fixable rules should export a `meta.fixable` property.");
|
||||
if (problem.fix && !(rule.meta && rule.meta.fixable)) {
|
||||
throw new Error("Fixable rules must set the `meta.fixable` property to \"code\" or \"whitespace\".");
|
||||
}
|
||||
if (problem.suggestions && !(rule.meta && rule.meta.hasSuggestions === true)) {
|
||||
if (rule.meta && rule.meta.docs && typeof rule.meta.docs.suggestion !== "undefined") {
|
||||
|
||||
// Encourage migration from the former property name.
|
||||
throw new Error("Rules with suggestions must set the `meta.hasSuggestions` property to `true`. `meta.docs.suggestion` is ignored by ESLint.");
|
||||
}
|
||||
throw new Error("Rules with suggestions must set the `meta.hasSuggestions` property to `true`.");
|
||||
}
|
||||
lintingProblems.push(problem);
|
||||
}
|
||||
@@ -936,13 +955,31 @@ function runRules(sourceCode, configuredRules, ruleMapper, parserOptions, parser
|
||||
|
||||
const ruleListeners = createRuleListeners(rule, ruleContext);
|
||||
|
||||
/**
|
||||
* Include `ruleId` in error logs
|
||||
* @param {Function} ruleListener A rule method that listens for a node.
|
||||
* @returns {Function} ruleListener wrapped in error handler
|
||||
*/
|
||||
function addRuleErrorHandler(ruleListener) {
|
||||
return function ruleErrorHandler(...listenerArgs) {
|
||||
try {
|
||||
return ruleListener(...listenerArgs);
|
||||
} catch (e) {
|
||||
e.ruleId = ruleId;
|
||||
throw e;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// add all the selectors from the rule as listeners
|
||||
Object.keys(ruleListeners).forEach(selector => {
|
||||
const ruleListener = timing.enabled
|
||||
? timing.time(ruleId, ruleListeners[selector])
|
||||
: ruleListeners[selector];
|
||||
|
||||
emitter.on(
|
||||
selector,
|
||||
timing.enabled
|
||||
? timing.time(ruleId, ruleListeners[selector])
|
||||
: ruleListeners[selector]
|
||||
addRuleErrorHandler(ruleListener)
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1027,7 +1064,7 @@ function normalizeCwd(cwd) {
|
||||
}
|
||||
|
||||
// It's more explicit to assign the undefined
|
||||
// eslint-disable-next-line no-undefined
|
||||
// eslint-disable-next-line no-undefined -- Consistently returning a value
|
||||
return undefined;
|
||||
}
|
||||
|
||||
@@ -1050,7 +1087,7 @@ class Linter {
|
||||
/**
|
||||
* Initialize the Linter.
|
||||
* @param {Object} [config] the config object
|
||||
* @param {string} [config.cwd] path to a directory that should be considered as the current working directory, can be undefined.
|
||||
* @param {string} [config.cwd] path to a directory that should be considered as the current working directory, can be undefined.
|
||||
*/
|
||||
constructor({ cwd } = {}) {
|
||||
internalSlotsMap.set(this, {
|
||||
@@ -1078,6 +1115,7 @@ class Linter {
|
||||
* @param {string|SourceCode} textOrSourceCode The text to parse or a SourceCode object.
|
||||
* @param {ConfigData} providedConfig An ESLintConfig instance to configure everything.
|
||||
* @param {VerifyOptions} [providedOptions] The optional filename of the file being checked.
|
||||
* @throws {Error} If during rule execution.
|
||||
* @returns {LintMessage[]} The results as an array of messages or an empty array if no messages.
|
||||
*/
|
||||
_verifyWithoutProcessors(textOrSourceCode, providedConfig, providedOptions) {
|
||||
@@ -1203,11 +1241,17 @@ class Linter {
|
||||
debug("Parser Options:", parserOptions);
|
||||
debug("Parser Path:", parserName);
|
||||
debug("Settings:", settings);
|
||||
|
||||
if (err.ruleId) {
|
||||
err.message += `\nRule: "${err.ruleId}"`;
|
||||
}
|
||||
|
||||
throw err;
|
||||
}
|
||||
|
||||
return applyDisableDirectives({
|
||||
directives: commentDirectives.disableDirectives,
|
||||
disableFixes: options.disableFixes,
|
||||
problems: lintingProblems
|
||||
.concat(commentDirectives.problems)
|
||||
.sort((problemA, problemB) => problemA.line - problemB.line || problemA.column - problemB.column),
|
||||
@@ -1295,8 +1339,7 @@ class Linter {
|
||||
const text = ensureText(textOrSourceCode);
|
||||
const preprocess = options.preprocess || (rawText => [rawText]);
|
||||
|
||||
// TODO(stephenwade): Replace this with array.flat() when we drop support for Node v10
|
||||
const postprocess = options.postprocess || (array => [].concat(...array));
|
||||
const postprocess = options.postprocess || (messagesList => messagesList.flat());
|
||||
const filterCodeBlock =
|
||||
options.filterCodeBlock ||
|
||||
(blockFilename => blockFilename.endsWith(".js"));
|
||||
|
||||
+1
-4
@@ -37,9 +37,7 @@ const esquery = require("esquery");
|
||||
* @returns {any[]} The union of the input arrays
|
||||
*/
|
||||
function union(...arrays) {
|
||||
|
||||
// TODO(stephenwade): Replace this with arrays.flat() when we drop support for Node v10
|
||||
return [...new Set([].concat(...arrays))];
|
||||
return [...new Set(arrays.flat())];
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -239,7 +237,6 @@ function parseSelector(rawSelector) {
|
||||
*/
|
||||
class NodeEventGenerator {
|
||||
|
||||
// eslint-disable-next-line jsdoc/require-description
|
||||
/**
|
||||
* @param {SafeEmitter} emitter
|
||||
* An SafeEmitter which is the destination of events. This emitter must already
|
||||
|
||||
+12
-12
@@ -32,18 +32,18 @@ const interpolate = require("./interpolate");
|
||||
/**
|
||||
* Information about the report
|
||||
* @typedef {Object} ReportInfo
|
||||
* @property {string} ruleId
|
||||
* @property {(0|1|2)} severity
|
||||
* @property {(string|undefined)} message
|
||||
* @property {(string|undefined)} [messageId]
|
||||
* @property {number} line
|
||||
* @property {number} column
|
||||
* @property {(number|undefined)} [endLine]
|
||||
* @property {(number|undefined)} [endColumn]
|
||||
* @property {(string|null)} nodeType
|
||||
* @property {string} source
|
||||
* @property {({text: string, range: (number[]|null)}|null)} [fix]
|
||||
* @property {Array<{text: string, range: (number[]|null)}|null>} [suggestions]
|
||||
* @property {string} ruleId The rule ID
|
||||
* @property {(0|1|2)} severity Severity of the error
|
||||
* @property {(string|undefined)} message The message
|
||||
* @property {(string|undefined)} [messageId] The message ID
|
||||
* @property {number} line The line number
|
||||
* @property {number} column The column number
|
||||
* @property {(number|undefined)} [endLine] The ending line number
|
||||
* @property {(number|undefined)} [endColumn] The ending column number
|
||||
* @property {(string|null)} nodeType Type of node
|
||||
* @property {string} source Source text
|
||||
* @property {({text: string, range: (number[]|null)}|null)} [fix] The fix object
|
||||
* @property {Array<{text: string, range: (number[]|null)}|null>} [suggestions] Suggestion info
|
||||
*/
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
+3
@@ -30,6 +30,9 @@ function normalizeRule(rule) {
|
||||
// Public Interface
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* A storage for rules.
|
||||
*/
|
||||
class Rules {
|
||||
constructor() {
|
||||
this._rules = Object.create(null);
|
||||
|
||||
+2
-2
@@ -12,8 +12,8 @@
|
||||
/**
|
||||
* An event emitter
|
||||
* @typedef {Object} SafeEmitter
|
||||
* @property {function(eventName: string, listenerFunc: Function): void} on Adds a listener for a given event name
|
||||
* @property {function(eventName: string, arg1?: any, arg2?: any, arg3?: any)} emit Emits an event with a given name.
|
||||
* @property {(eventName: string, listenerFunc: Function) => void} on Adds a listener for a given event name
|
||||
* @property {(eventName: string, arg1?: any, arg2?: any, arg3?: any) => void} emit Emits an event with a given name.
|
||||
* This calls all the listeners that were listening for that name, with `arg1`, `arg2`, and `arg3` as arguments.
|
||||
* @property {function(): string[]} eventNames Gets the list of event names that have registered listeners.
|
||||
*/
|
||||
|
||||
+2
-2
@@ -80,8 +80,8 @@ SourceCodeFixer.applyFixes = function(sourceText, messages, shouldFix) {
|
||||
|
||||
/**
|
||||
* Try to use the 'fix' from a problem.
|
||||
* @param {Message} problem The message object to apply fixes from
|
||||
* @returns {boolean} Whether fix was successfully applied
|
||||
* @param {Message} problem The message object to apply fixes from
|
||||
* @returns {boolean} Whether fix was successfully applied
|
||||
*/
|
||||
function attemptFix(problem) {
|
||||
const fix = problem.fix;
|
||||
|
||||
+2
-2
@@ -116,7 +116,7 @@ function display(data) {
|
||||
return ALIGN[index](":", width + extraAlignment, "-");
|
||||
}).join("|"));
|
||||
|
||||
console.log(table.join("\n")); // eslint-disable-line no-console
|
||||
console.log(table.join("\n")); // eslint-disable-line no-console -- Debugging function
|
||||
}
|
||||
|
||||
/* istanbul ignore next */
|
||||
@@ -126,7 +126,7 @@ module.exports = (function() {
|
||||
|
||||
/**
|
||||
* Time the run
|
||||
* @param {*} key key from the data object
|
||||
* @param {any} key key from the data object
|
||||
* @param {Function} fn function to be called
|
||||
* @returns {Function} function to be executed
|
||||
* @private
|
||||
|
||||
+2
-2
@@ -32,7 +32,7 @@ const optionator = require("optionator");
|
||||
* @property {string[]} [ext] Specify JavaScript file extensions
|
||||
* @property {boolean} fix Automatically fix problems
|
||||
* @property {boolean} fixDryRun Automatically fix problems without saving the changes to the file system
|
||||
* @property {("problem" | "suggestion" | "layout")[]} [fixType] Specify the types of fixes to apply (problem, suggestion, layout)
|
||||
* @property {("directive" | "problem" | "suggestion" | "layout")[]} [fixType] Specify the types of fixes to apply (directive, problem, suggestion, layout)
|
||||
* @property {string} format Use a specific output format
|
||||
* @property {string[]} [global] Define global variables
|
||||
* @property {boolean} [help] Show help
|
||||
@@ -151,7 +151,7 @@ module.exports = optionator({
|
||||
{
|
||||
option: "fix-type",
|
||||
type: "Array",
|
||||
description: "Specify the types of fixes to apply (problem, suggestion, layout)"
|
||||
description: "Specify the types of fixes to apply (directive, problem, suggestion, layout)"
|
||||
},
|
||||
{
|
||||
heading: "Ignoring files"
|
||||
|
||||
+35
-13
@@ -4,7 +4,7 @@
|
||||
*/
|
||||
"use strict";
|
||||
|
||||
/* global describe, it */
|
||||
/* eslint-env mocha -- Mocha wrapper */
|
||||
|
||||
/*
|
||||
* This is a wrapper around mocha to allow for DRY unittests for eslint
|
||||
@@ -55,12 +55,15 @@ const ajv = require("../shared/ajv")({ strictDefaults: true });
|
||||
const espreePath = require.resolve("espree");
|
||||
const parserSymbol = Symbol.for("eslint.RuleTester.parser");
|
||||
|
||||
const { SourceCode } = require("../source-code");
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Typedefs
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
/** @typedef {import("../shared/types").Parser} Parser */
|
||||
|
||||
/* eslint-disable jsdoc/valid-types -- https://github.com/jsdoc-type-pratt-parser/jsdoc-type-pratt-parser/issues/4#issuecomment-778805577 */
|
||||
/**
|
||||
* A test case that is expected to pass lint.
|
||||
* @typedef {Object} ValidTestCase
|
||||
@@ -103,6 +106,7 @@ const parserSymbol = Symbol.for("eslint.RuleTester.parser");
|
||||
* @property {number} [endLine] The 1-based line number of the reported end location.
|
||||
* @property {number} [endColumn] The 1-based column number of the reported end location.
|
||||
*/
|
||||
/* eslint-enable jsdoc/valid-types -- https://github.com/jsdoc-type-pratt-parser/jsdoc-type-pratt-parser/issues/4#issuecomment-778805577 */
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Private Members
|
||||
@@ -210,7 +214,7 @@ function freezeDeeply(x) {
|
||||
*/
|
||||
function sanitize(text) {
|
||||
return text.replace(
|
||||
/[\u0000-\u0009\u000b-\u001a]/gu, // eslint-disable-line no-control-regex
|
||||
/[\u0000-\u0009\u000b-\u001a]/gu, // eslint-disable-line no-control-regex -- Escaping controls
|
||||
c => `\\u${c.codePointAt(0).toString(16).padStart(4, "0")}`
|
||||
);
|
||||
}
|
||||
@@ -284,6 +288,17 @@ function wrapParser(parser) {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Function to replace `SourceCode.prototype.getComments`.
|
||||
* @returns {void}
|
||||
* @throws {Error} Deprecation message.
|
||||
*/
|
||||
function getCommentsDeprecation() {
|
||||
throw new Error(
|
||||
"`SourceCode#getComments()` is deprecated and will be removed in a future major version. Use `getCommentsBefore()`, `getCommentsAfter()`, and `getCommentsInside()` instead."
|
||||
);
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Public Interface
|
||||
//------------------------------------------------------------------------------
|
||||
@@ -298,6 +313,7 @@ const IT_ONLY = Symbol("itOnly");
|
||||
* @this {Mocha}
|
||||
* @param {string} text The description of the test case.
|
||||
* @param {Function} method The logic of the test case.
|
||||
* @throws {Error} Any error upon execution of `method`.
|
||||
* @returns {any} Returned value of `method`.
|
||||
*/
|
||||
function itDefaultHandler(text, method) {
|
||||
@@ -322,6 +338,9 @@ function describeDefaultHandler(text, method) {
|
||||
return method.call(this);
|
||||
}
|
||||
|
||||
/**
|
||||
* Mocha test wrapper.
|
||||
*/
|
||||
class RuleTester {
|
||||
|
||||
/**
|
||||
@@ -353,6 +372,7 @@ class RuleTester {
|
||||
/**
|
||||
* Set the configuration to use for all future tests
|
||||
* @param {Object} config the configuration to use.
|
||||
* @throws {TypeError} If non-object config.
|
||||
* @returns {void}
|
||||
*/
|
||||
static setDefaultConfig(config) {
|
||||
@@ -468,6 +488,8 @@ class RuleTester {
|
||||
* valid: (ValidTestCase | string)[],
|
||||
* invalid: InvalidTestCase[]
|
||||
* }} test The collection of tests to run.
|
||||
* @throws {TypeError|Error} If non-object `test`, or if a required
|
||||
* scenario of the given type is missing.
|
||||
* @returns {void}
|
||||
*/
|
||||
run(ruleName, rule, test) {
|
||||
@@ -511,6 +533,7 @@ class RuleTester {
|
||||
/**
|
||||
* Run the rule for the given item
|
||||
* @param {string|Object} item Item to run the rule against
|
||||
* @throws {Error} If an invalid schema.
|
||||
* @returns {Object} Eslint run result
|
||||
* @private
|
||||
*/
|
||||
@@ -607,7 +630,16 @@ class RuleTester {
|
||||
validate(config, "rule-tester", id => (id === ruleName ? rule : null));
|
||||
|
||||
// Verify the code.
|
||||
const messages = linter.verify(code, config, filename);
|
||||
const { getComments } = SourceCode.prototype;
|
||||
let messages;
|
||||
|
||||
try {
|
||||
SourceCode.prototype.getComments = getCommentsDeprecation;
|
||||
messages = linter.verify(code, config, filename);
|
||||
} finally {
|
||||
SourceCode.prototype.getComments = getComments;
|
||||
}
|
||||
|
||||
const fatalErrorMessage = messages.find(m => m.fatal);
|
||||
|
||||
assert(!fatalErrorMessage, `A fatal parsing error occurred: ${fatalErrorMessage && fatalErrorMessage.message}`);
|
||||
@@ -921,16 +953,6 @@ class RuleTester {
|
||||
);
|
||||
}
|
||||
|
||||
// Rules that produce fixes must have `meta.fixable` property.
|
||||
if (result.output !== item.code) {
|
||||
assert.ok(
|
||||
hasOwnProperty(rule, "meta"),
|
||||
"Fixable rules should export a `meta.fixable` property."
|
||||
);
|
||||
|
||||
// Linter throws if a rule that produced a fix has `meta` but doesn't have `meta.fixable`.
|
||||
}
|
||||
|
||||
assertASTDidntChange(result.beforeAST, result.afterAST);
|
||||
}
|
||||
|
||||
|
||||
-1
@@ -140,7 +140,6 @@ module.exports = {
|
||||
|
||||
docs: {
|
||||
description: "enforce getter and setter pairs in objects and classes",
|
||||
category: "Best Practices",
|
||||
recommended: false,
|
||||
url: "https://eslint.org/docs/rules/accessor-pairs"
|
||||
},
|
||||
|
||||
-1
@@ -17,7 +17,6 @@ module.exports = {
|
||||
|
||||
docs: {
|
||||
description: "enforce linebreaks after opening and before closing array brackets",
|
||||
category: "Stylistic Issues",
|
||||
recommended: false,
|
||||
url: "https://eslint.org/docs/rules/array-bracket-newline"
|
||||
},
|
||||
|
||||
-1
@@ -16,7 +16,6 @@ module.exports = {
|
||||
|
||||
docs: {
|
||||
description: "enforce consistent spacing inside array brackets",
|
||||
category: "Stylistic Issues",
|
||||
recommended: false,
|
||||
url: "https://eslint.org/docs/rules/array-bracket-spacing"
|
||||
},
|
||||
|
||||
-1
@@ -139,7 +139,6 @@ module.exports = {
|
||||
|
||||
docs: {
|
||||
description: "enforce `return` statements in callbacks of array methods",
|
||||
category: "Best Practices",
|
||||
recommended: false,
|
||||
url: "https://eslint.org/docs/rules/array-callback-return"
|
||||
},
|
||||
|
||||
-1
@@ -17,7 +17,6 @@ module.exports = {
|
||||
|
||||
docs: {
|
||||
description: "enforce line breaks after each array element",
|
||||
category: "Stylistic Issues",
|
||||
recommended: false,
|
||||
url: "https://eslint.org/docs/rules/array-element-newline"
|
||||
},
|
||||
|
||||
-1
@@ -20,7 +20,6 @@ module.exports = {
|
||||
|
||||
docs: {
|
||||
description: "require braces around arrow function bodies",
|
||||
category: "ECMAScript 6",
|
||||
recommended: false,
|
||||
url: "https://eslint.org/docs/rules/arrow-body-style"
|
||||
},
|
||||
|
||||
-1
@@ -33,7 +33,6 @@ module.exports = {
|
||||
|
||||
docs: {
|
||||
description: "require parentheses around arrow function arguments",
|
||||
category: "ECMAScript 6",
|
||||
recommended: false,
|
||||
url: "https://eslint.org/docs/rules/arrow-parens"
|
||||
},
|
||||
|
||||
-1
@@ -20,7 +20,6 @@ module.exports = {
|
||||
|
||||
docs: {
|
||||
description: "enforce consistent spacing before and after the arrow in arrow functions",
|
||||
category: "ECMAScript 6",
|
||||
recommended: false,
|
||||
url: "https://eslint.org/docs/rules/arrow-spacing"
|
||||
},
|
||||
|
||||
-1
@@ -14,7 +14,6 @@ module.exports = {
|
||||
|
||||
docs: {
|
||||
description: "enforce the use of variables within the scope they are defined",
|
||||
category: "Best Practices",
|
||||
recommended: false,
|
||||
url: "https://eslint.org/docs/rules/block-scoped-var"
|
||||
},
|
||||
|
||||
-1
@@ -17,7 +17,6 @@ module.exports = {
|
||||
|
||||
docs: {
|
||||
description: "disallow or enforce spaces inside of blocks after opening block and before closing block",
|
||||
category: "Stylistic Issues",
|
||||
recommended: false,
|
||||
url: "https://eslint.org/docs/rules/block-spacing"
|
||||
},
|
||||
|
||||
-1
@@ -17,7 +17,6 @@ module.exports = {
|
||||
|
||||
docs: {
|
||||
description: "enforce consistent brace style for blocks",
|
||||
category: "Stylistic Issues",
|
||||
recommended: false,
|
||||
url: "https://eslint.org/docs/rules/brace-style"
|
||||
},
|
||||
|
||||
+1
-1
@@ -1,6 +1,7 @@
|
||||
/**
|
||||
* @fileoverview Enforce return after a callback.
|
||||
* @author Jamund Ferguson
|
||||
* @deprecated in ESLint v7.0.0
|
||||
*/
|
||||
"use strict";
|
||||
|
||||
@@ -18,7 +19,6 @@ module.exports = {
|
||||
|
||||
docs: {
|
||||
description: "require `return` statements after callbacks",
|
||||
category: "Node.js and CommonJS",
|
||||
recommended: false,
|
||||
url: "https://eslint.org/docs/rules/callback-return"
|
||||
},
|
||||
|
||||
+251
-185
@@ -15,7 +15,6 @@ module.exports = {
|
||||
|
||||
docs: {
|
||||
description: "enforce camelcase naming convention",
|
||||
category: "Stylistic Issues",
|
||||
recommended: false,
|
||||
url: "https://eslint.org/docs/rules/camelcase"
|
||||
},
|
||||
@@ -55,32 +54,25 @@ module.exports = {
|
||||
],
|
||||
|
||||
messages: {
|
||||
notCamelCase: "Identifier '{{name}}' is not in camel case."
|
||||
notCamelCase: "Identifier '{{name}}' is not in camel case.",
|
||||
notCamelCasePrivate: "#{{name}} is not in camel case."
|
||||
}
|
||||
},
|
||||
|
||||
create(context) {
|
||||
|
||||
const options = context.options[0] || {};
|
||||
let properties = options.properties || "";
|
||||
const properties = options.properties === "never" ? "never" : "always";
|
||||
const ignoreDestructuring = options.ignoreDestructuring;
|
||||
const ignoreImports = options.ignoreImports;
|
||||
const ignoreGlobals = options.ignoreGlobals;
|
||||
const allow = options.allow || [];
|
||||
|
||||
let globalScope;
|
||||
|
||||
if (properties !== "always" && properties !== "never") {
|
||||
properties = "always";
|
||||
}
|
||||
|
||||
//--------------------------------------------------------------------------
|
||||
// Helpers
|
||||
//--------------------------------------------------------------------------
|
||||
|
||||
// contains reported nodes to avoid reporting twice on destructuring with shorthand notation
|
||||
const reported = [];
|
||||
const ALLOWED_PARENT_TYPES = new Set(["CallExpression", "NewExpression"]);
|
||||
const reported = new Set();
|
||||
|
||||
/**
|
||||
* Checks if a string contains an underscore and isn't all upper-case
|
||||
@@ -89,9 +81,10 @@ module.exports = {
|
||||
* @private
|
||||
*/
|
||||
function isUnderscored(name) {
|
||||
const nameBody = name.replace(/^_+|_+$/gu, "");
|
||||
|
||||
// if there's an underscore, it might be A_CONSTANT, which is okay
|
||||
return name.includes("_") && name !== name.toUpperCase();
|
||||
return nameBody.includes("_") && nameBody !== nameBody.toUpperCase();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -107,94 +100,76 @@ module.exports = {
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if a parent of a node is an ObjectPattern.
|
||||
* @param {ASTNode} node The node to check.
|
||||
* @returns {boolean} if the node is inside an ObjectPattern
|
||||
* Checks if a given name is good or not.
|
||||
* @param {string} name The name to check.
|
||||
* @returns {boolean} `true` if the name is good.
|
||||
* @private
|
||||
*/
|
||||
function isInsideObjectPattern(node) {
|
||||
let current = node;
|
||||
|
||||
while (current) {
|
||||
const parent = current.parent;
|
||||
|
||||
if (parent && parent.type === "Property" && parent.computed && parent.key === current) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (current.type === "ObjectPattern") {
|
||||
return true;
|
||||
}
|
||||
|
||||
current = parent;
|
||||
}
|
||||
|
||||
return false;
|
||||
function isGoodName(name) {
|
||||
return !isUnderscored(name) || isAllowed(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether the given node represents assignment target property in destructuring.
|
||||
*
|
||||
* For examples:
|
||||
* ({a: b.foo} = c); // => true for `foo`
|
||||
* ([a.foo] = b); // => true for `foo`
|
||||
* ([a.foo = 1] = b); // => true for `foo`
|
||||
* ({...a.foo} = b); // => true for `foo`
|
||||
* @param {ASTNode} node An Identifier node to check
|
||||
* @returns {boolean} True if the node is an assignment target property in destructuring.
|
||||
* Checks if a given identifier reference or member expression is an assignment
|
||||
* target.
|
||||
* @param {ASTNode} node The node to check.
|
||||
* @returns {boolean} `true` if the node is an assignment target.
|
||||
*/
|
||||
function isAssignmentTargetPropertyInDestructuring(node) {
|
||||
if (
|
||||
node.parent.type === "MemberExpression" &&
|
||||
node.parent.property === node &&
|
||||
!node.parent.computed
|
||||
) {
|
||||
const effectiveParent = node.parent.parent;
|
||||
|
||||
return (
|
||||
effectiveParent.type === "Property" &&
|
||||
effectiveParent.value === node.parent &&
|
||||
effectiveParent.parent.type === "ObjectPattern" ||
|
||||
effectiveParent.type === "ArrayPattern" ||
|
||||
effectiveParent.type === "RestElement" ||
|
||||
(
|
||||
effectiveParent.type === "AssignmentPattern" &&
|
||||
effectiveParent.left === node.parent
|
||||
)
|
||||
);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether the given node represents a reference to a global variable that is not declared in the source code.
|
||||
* These identifiers will be allowed, as it is assumed that user has no control over the names of external global variables.
|
||||
* @param {ASTNode} node `Identifier` node to check.
|
||||
* @returns {boolean} `true` if the node is a reference to a global variable.
|
||||
*/
|
||||
function isReferenceToGlobalVariable(node) {
|
||||
const variable = globalScope.set.get(node.name);
|
||||
|
||||
return variable && variable.defs.length === 0 &&
|
||||
variable.references.some(ref => ref.identifier === node);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether the given node represents a reference to a property of an object in an object literal expression.
|
||||
* This allows to differentiate between a global variable that is allowed to be used as a reference, and the key
|
||||
* of the expressed object (which shouldn't be allowed).
|
||||
* @param {ASTNode} node `Identifier` node to check.
|
||||
* @returns {boolean} `true` if the node is a property name of an object literal expression
|
||||
*/
|
||||
function isPropertyNameInObjectLiteral(node) {
|
||||
function isAssignmentTarget(node) {
|
||||
const parent = node.parent;
|
||||
|
||||
return (
|
||||
parent.type === "Property" &&
|
||||
parent.parent.type === "ObjectExpression" &&
|
||||
!parent.computed &&
|
||||
parent.key === node
|
||||
);
|
||||
switch (parent.type) {
|
||||
case "AssignmentExpression":
|
||||
case "AssignmentPattern":
|
||||
return parent.left === node;
|
||||
|
||||
case "Property":
|
||||
return (
|
||||
parent.parent.type === "ObjectPattern" &&
|
||||
parent.value === node
|
||||
);
|
||||
case "ArrayPattern":
|
||||
case "RestElement":
|
||||
return true;
|
||||
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if a given binding identifier uses the original name as-is.
|
||||
* - If it's in object destructuring, the original name is its property name.
|
||||
* - If it's in import declaration, the original name is its exported name.
|
||||
* @param {ASTNode} node The `Identifier` node to check.
|
||||
* @returns {boolean} `true` if the identifier uses the original name as-is.
|
||||
*/
|
||||
function equalsToOriginalName(node) {
|
||||
const localName = node.name;
|
||||
const valueNode = node.parent.type === "AssignmentPattern"
|
||||
? node.parent
|
||||
: node;
|
||||
const parent = valueNode.parent;
|
||||
|
||||
switch (parent.type) {
|
||||
case "Property":
|
||||
return (
|
||||
parent.parent.type === "ObjectPattern" &&
|
||||
parent.value === valueNode &&
|
||||
!parent.computed &&
|
||||
parent.key.type === "Identifier" &&
|
||||
parent.key.name === localName
|
||||
);
|
||||
|
||||
case "ImportSpecifier":
|
||||
return (
|
||||
parent.local === node &&
|
||||
parent.imported.name === localName
|
||||
);
|
||||
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -204,122 +179,213 @@ module.exports = {
|
||||
* @private
|
||||
*/
|
||||
function report(node) {
|
||||
if (!reported.includes(node)) {
|
||||
reported.push(node);
|
||||
context.report({ node, messageId: "notCamelCase", data: { name: node.name } });
|
||||
if (reported.has(node.range[0])) {
|
||||
return;
|
||||
}
|
||||
reported.add(node.range[0]);
|
||||
|
||||
// Report it.
|
||||
context.report({
|
||||
node,
|
||||
messageId: node.type === "PrivateIdentifier"
|
||||
? "notCamelCasePrivate"
|
||||
: "notCamelCase",
|
||||
data: { name: node.name }
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reports an identifier reference or a binding identifier.
|
||||
* @param {ASTNode} node The `Identifier` node to report.
|
||||
* @returns {void}
|
||||
*/
|
||||
function reportReferenceId(node) {
|
||||
|
||||
/*
|
||||
* For backward compatibility, if it's in callings then ignore it.
|
||||
* Not sure why it is.
|
||||
*/
|
||||
if (
|
||||
node.parent.type === "CallExpression" ||
|
||||
node.parent.type === "NewExpression"
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
/*
|
||||
* For backward compatibility, if it's a default value of
|
||||
* destructuring/parameters then ignore it.
|
||||
* Not sure why it is.
|
||||
*/
|
||||
if (
|
||||
node.parent.type === "AssignmentPattern" &&
|
||||
node.parent.right === node
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
/*
|
||||
* The `ignoreDestructuring` flag skips the identifiers that uses
|
||||
* the property name as-is.
|
||||
*/
|
||||
if (ignoreDestructuring && equalsToOriginalName(node)) {
|
||||
return;
|
||||
}
|
||||
|
||||
report(node);
|
||||
}
|
||||
|
||||
return {
|
||||
|
||||
// Report camelcase of global variable references ------------------
|
||||
Program() {
|
||||
globalScope = context.getScope();
|
||||
const scope = context.getScope();
|
||||
|
||||
if (!ignoreGlobals) {
|
||||
|
||||
// Defined globals in config files or directive comments.
|
||||
for (const variable of scope.variables) {
|
||||
if (
|
||||
variable.identifiers.length > 0 ||
|
||||
isGoodName(variable.name)
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
for (const reference of variable.references) {
|
||||
|
||||
/*
|
||||
* For backward compatibility, this rule reports read-only
|
||||
* references as well.
|
||||
*/
|
||||
reportReferenceId(reference.identifier);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Undefined globals.
|
||||
for (const reference of scope.through) {
|
||||
const id = reference.identifier;
|
||||
|
||||
if (isGoodName(id.name)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
/*
|
||||
* For backward compatibility, this rule reports read-only
|
||||
* references as well.
|
||||
*/
|
||||
reportReferenceId(id);
|
||||
}
|
||||
},
|
||||
|
||||
Identifier(node) {
|
||||
// Report camelcase of declared variables --------------------------
|
||||
[[
|
||||
"VariableDeclaration",
|
||||
"FunctionDeclaration",
|
||||
"FunctionExpression",
|
||||
"ArrowFunctionExpression",
|
||||
"ClassDeclaration",
|
||||
"ClassExpression",
|
||||
"CatchClause"
|
||||
]](node) {
|
||||
for (const variable of context.getDeclaredVariables(node)) {
|
||||
if (isGoodName(variable.name)) {
|
||||
continue;
|
||||
}
|
||||
const id = variable.identifiers[0];
|
||||
|
||||
/*
|
||||
* Leading and trailing underscores are commonly used to flag
|
||||
* private/protected identifiers, strip them before checking if underscored
|
||||
*/
|
||||
const name = node.name,
|
||||
nameIsUnderscored = isUnderscored(name.replace(/^_+|_+$/gu, "")),
|
||||
effectiveParent = (node.parent.type === "MemberExpression") ? node.parent.parent : node.parent;
|
||||
// Report declaration.
|
||||
if (!(ignoreDestructuring && equalsToOriginalName(id))) {
|
||||
report(id);
|
||||
}
|
||||
|
||||
// First, we ignore the node if it match the ignore list
|
||||
if (isAllowed(name)) {
|
||||
/*
|
||||
* For backward compatibility, report references as well.
|
||||
* It looks unnecessary because declarations are reported.
|
||||
*/
|
||||
for (const reference of variable.references) {
|
||||
if (reference.init) {
|
||||
continue; // Skip the write references of initializers.
|
||||
}
|
||||
reportReferenceId(reference.identifier);
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
// Report camelcase in properties ----------------------------------
|
||||
[[
|
||||
"ObjectExpression > Property[computed!=true] > Identifier.key",
|
||||
"MethodDefinition[computed!=true] > Identifier.key",
|
||||
"PropertyDefinition[computed!=true] > Identifier.key",
|
||||
"MethodDefinition > PrivateIdentifier.key",
|
||||
"PropertyDefinition > PrivateIdentifier.key"
|
||||
]](node) {
|
||||
if (properties === "never" || isGoodName(node.name)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if it's a global variable
|
||||
if (ignoreGlobals && isReferenceToGlobalVariable(node) && !isPropertyNameInObjectLiteral(node)) {
|
||||
report(node);
|
||||
},
|
||||
"MemberExpression[computed!=true] > Identifier.property"(node) {
|
||||
if (
|
||||
properties === "never" ||
|
||||
!isAssignmentTarget(node.parent) || // ← ignore read-only references.
|
||||
isGoodName(node.name)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
report(node);
|
||||
},
|
||||
|
||||
// MemberExpressions get special rules
|
||||
if (node.parent.type === "MemberExpression") {
|
||||
// Report camelcase in import --------------------------------------
|
||||
ImportDeclaration(node) {
|
||||
for (const variable of context.getDeclaredVariables(node)) {
|
||||
if (isGoodName(variable.name)) {
|
||||
continue;
|
||||
}
|
||||
const id = variable.identifiers[0];
|
||||
|
||||
// "never" check properties
|
||||
if (properties === "never") {
|
||||
return;
|
||||
// Report declaration.
|
||||
if (!(ignoreImports && equalsToOriginalName(id))) {
|
||||
report(id);
|
||||
}
|
||||
|
||||
// Always report underscored object names
|
||||
if (node.parent.object.type === "Identifier" && node.parent.object.name === node.name && nameIsUnderscored) {
|
||||
report(node);
|
||||
|
||||
// Report AssignmentExpressions only if they are the left side of the assignment
|
||||
} else if (effectiveParent.type === "AssignmentExpression" && nameIsUnderscored && (effectiveParent.right.type !== "MemberExpression" || effectiveParent.left.type === "MemberExpression" && effectiveParent.left.property.name === node.name)) {
|
||||
report(node);
|
||||
|
||||
} else if (isAssignmentTargetPropertyInDestructuring(node) && nameIsUnderscored) {
|
||||
report(node);
|
||||
/*
|
||||
* For backward compatibility, report references as well.
|
||||
* It looks unnecessary because declarations are reported.
|
||||
*/
|
||||
for (const reference of variable.references) {
|
||||
reportReferenceId(reference.identifier);
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
// Report camelcase in re-export -----------------------------------
|
||||
[[
|
||||
"ExportAllDeclaration > Identifier.exported",
|
||||
"ExportSpecifier > Identifier.exported"
|
||||
]](node) {
|
||||
if (isGoodName(node.name)) {
|
||||
return;
|
||||
}
|
||||
report(node);
|
||||
},
|
||||
|
||||
// Report camelcase in labels --------------------------------------
|
||||
[[
|
||||
"LabeledStatement > Identifier.label",
|
||||
|
||||
/*
|
||||
* Properties have their own rules, and
|
||||
* AssignmentPattern nodes can be treated like Properties:
|
||||
* e.g.: const { no_camelcased = false } = bar;
|
||||
* For backward compatibility, report references as well.
|
||||
* It looks unnecessary because declarations are reported.
|
||||
*/
|
||||
} else if (node.parent.type === "Property" || node.parent.type === "AssignmentPattern") {
|
||||
|
||||
if (node.parent.parent && node.parent.parent.type === "ObjectPattern") {
|
||||
if (node.parent.shorthand && node.parent.value.left && nameIsUnderscored) {
|
||||
report(node);
|
||||
}
|
||||
|
||||
const assignmentKeyEqualsValue = node.parent.key.name === node.parent.value.name;
|
||||
|
||||
if (nameIsUnderscored && node.parent.computed) {
|
||||
report(node);
|
||||
}
|
||||
|
||||
// prevent checking righthand side of destructured object
|
||||
if (node.parent.key === node && node.parent.value !== node) {
|
||||
return;
|
||||
}
|
||||
|
||||
const valueIsUnderscored = node.parent.value.name && nameIsUnderscored;
|
||||
|
||||
// ignore destructuring if the option is set, unless a new identifier is created
|
||||
if (valueIsUnderscored && !(assignmentKeyEqualsValue && ignoreDestructuring)) {
|
||||
report(node);
|
||||
}
|
||||
}
|
||||
|
||||
// "never" check properties or always ignore destructuring
|
||||
if (properties === "never" || (ignoreDestructuring && isInsideObjectPattern(node))) {
|
||||
return;
|
||||
}
|
||||
|
||||
// don't check right hand side of AssignmentExpression to prevent duplicate warnings
|
||||
if (nameIsUnderscored && !ALLOWED_PARENT_TYPES.has(effectiveParent.type) && !(node.parent.right === node)) {
|
||||
report(node);
|
||||
}
|
||||
|
||||
// Check if it's an import specifier
|
||||
} else if (["ImportSpecifier", "ImportNamespaceSpecifier", "ImportDefaultSpecifier"].includes(node.parent.type)) {
|
||||
|
||||
if (node.parent.type === "ImportSpecifier" && ignoreImports) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Report only if the local imported identifier is underscored
|
||||
if (
|
||||
node.parent.local &&
|
||||
node.parent.local.name === node.name &&
|
||||
nameIsUnderscored
|
||||
) {
|
||||
report(node);
|
||||
}
|
||||
|
||||
// Report anything that is underscored that isn't a CallExpression
|
||||
} else if (nameIsUnderscored && !ALLOWED_PARENT_TYPES.has(effectiveParent.type)) {
|
||||
report(node);
|
||||
"BreakStatement > Identifier.label",
|
||||
"ContinueStatement > Identifier.label"
|
||||
]](node) {
|
||||
if (isGoodName(node.name)) {
|
||||
return;
|
||||
}
|
||||
report(node);
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
}
|
||||
};
|
||||
-1
@@ -105,7 +105,6 @@ module.exports = {
|
||||
|
||||
docs: {
|
||||
description: "enforce or disallow capitalization of the first letter of a comment",
|
||||
category: "Stylistic Issues",
|
||||
recommended: false,
|
||||
url: "https://eslint.org/docs/rules/capitalized-comments"
|
||||
},
|
||||
|
||||
+59
-7
@@ -21,7 +21,6 @@ module.exports = {
|
||||
|
||||
docs: {
|
||||
description: "enforce that class methods utilize `this`",
|
||||
category: "Best Practices",
|
||||
recommended: false,
|
||||
url: "https://eslint.org/docs/rules/class-methods-use-this"
|
||||
},
|
||||
@@ -34,6 +33,10 @@ module.exports = {
|
||||
items: {
|
||||
type: "string"
|
||||
}
|
||||
},
|
||||
enforceForClassFields: {
|
||||
type: "boolean",
|
||||
default: true
|
||||
}
|
||||
},
|
||||
additionalProperties: false
|
||||
@@ -45,10 +48,27 @@ module.exports = {
|
||||
},
|
||||
create(context) {
|
||||
const config = Object.assign({}, context.options[0]);
|
||||
const enforceForClassFields = config.enforceForClassFields !== false;
|
||||
const exceptMethods = new Set(config.exceptMethods || []);
|
||||
|
||||
const stack = [];
|
||||
|
||||
/**
|
||||
* Push `this` used flag initialized with `false` onto the stack.
|
||||
* @returns {void}
|
||||
*/
|
||||
function pushContext() {
|
||||
stack.push(false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Pop `this` used flag from the stack.
|
||||
* @returns {boolean | undefined} `this` used flag
|
||||
*/
|
||||
function popContext() {
|
||||
return stack.pop();
|
||||
}
|
||||
|
||||
/**
|
||||
* Initializes the current context to false and pushes it onto the stack.
|
||||
* These booleans represent whether 'this' has been used in the context.
|
||||
@@ -56,7 +76,7 @@ module.exports = {
|
||||
* @private
|
||||
*/
|
||||
function enterFunction() {
|
||||
stack.push(false);
|
||||
pushContext();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -66,7 +86,14 @@ module.exports = {
|
||||
* @private
|
||||
*/
|
||||
function isInstanceMethod(node) {
|
||||
return !node.static && node.kind !== "constructor" && node.type === "MethodDefinition";
|
||||
switch (node.type) {
|
||||
case "MethodDefinition":
|
||||
return !node.static && node.kind !== "constructor";
|
||||
case "PropertyDefinition":
|
||||
return !node.static && enforceForClassFields;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -76,8 +103,19 @@ module.exports = {
|
||||
* @private
|
||||
*/
|
||||
function isIncludedInstanceMethod(node) {
|
||||
return isInstanceMethod(node) &&
|
||||
(node.computed || !exceptMethods.has(node.key.name));
|
||||
if (isInstanceMethod(node)) {
|
||||
if (node.computed) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const hashIfNeeded = node.key.type === "PrivateIdentifier" ? "#" : "";
|
||||
const name = node.key.type === "Literal"
|
||||
? astUtils.getStaticStringValue(node.key)
|
||||
: (node.key.name || "");
|
||||
|
||||
return !exceptMethods.has(hashIfNeeded + name);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -89,11 +127,12 @@ module.exports = {
|
||||
* @private
|
||||
*/
|
||||
function exitFunction(node) {
|
||||
const methodUsesThis = stack.pop();
|
||||
const methodUsesThis = popContext();
|
||||
|
||||
if (isIncludedInstanceMethod(node.parent) && !methodUsesThis) {
|
||||
context.report({
|
||||
node,
|
||||
loc: astUtils.getFunctionHeadLoc(node, context.getSourceCode()),
|
||||
messageId: "missingThis",
|
||||
data: {
|
||||
name: astUtils.getFunctionNameWithKind(node)
|
||||
@@ -118,8 +157,21 @@ module.exports = {
|
||||
"FunctionDeclaration:exit": exitFunction,
|
||||
FunctionExpression: enterFunction,
|
||||
"FunctionExpression:exit": exitFunction,
|
||||
|
||||
/*
|
||||
* Class field value are implicit functions.
|
||||
*/
|
||||
"PropertyDefinition:exit": popContext,
|
||||
"PropertyDefinition > *.key:exit": pushContext,
|
||||
|
||||
ThisExpression: markThisUsed,
|
||||
Super: markThisUsed
|
||||
Super: markThisUsed,
|
||||
...(
|
||||
enforceForClassFields && {
|
||||
"PropertyDefinition > ArrowFunctionExpression.value": enterFunction,
|
||||
"PropertyDefinition > ArrowFunctionExpression.value:exit": exitFunction
|
||||
}
|
||||
)
|
||||
};
|
||||
}
|
||||
};
|
||||
+2
-2
@@ -76,7 +76,6 @@ module.exports = {
|
||||
|
||||
docs: {
|
||||
description: "require or disallow trailing commas",
|
||||
category: "Stylistic Issues",
|
||||
recommended: false,
|
||||
url: "https://eslint.org/docs/rules/comma-dangle"
|
||||
},
|
||||
@@ -123,7 +122,8 @@ module.exports = {
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
],
|
||||
additionalItems: false
|
||||
},
|
||||
|
||||
messages: {
|
||||
|
||||
-1
@@ -16,7 +16,6 @@ module.exports = {
|
||||
|
||||
docs: {
|
||||
description: "enforce consistent spacing before and after commas",
|
||||
category: "Stylistic Issues",
|
||||
recommended: false,
|
||||
url: "https://eslint.org/docs/rules/comma-spacing"
|
||||
},
|
||||
|
||||
-1
@@ -17,7 +17,6 @@ module.exports = {
|
||||
|
||||
docs: {
|
||||
description: "enforce consistent comma style",
|
||||
category: "Stylistic Issues",
|
||||
recommended: false,
|
||||
url: "https://eslint.org/docs/rules/comma-style"
|
||||
},
|
||||
|
||||
+47
-56
@@ -23,7 +23,6 @@ module.exports = {
|
||||
|
||||
docs: {
|
||||
description: "enforce a maximum cyclomatic complexity allowed in a program",
|
||||
category: "Best Practices",
|
||||
recommended: false,
|
||||
url: "https://eslint.org/docs/rules/complexity"
|
||||
},
|
||||
@@ -75,60 +74,16 @@ module.exports = {
|
||||
// Helpers
|
||||
//--------------------------------------------------------------------------
|
||||
|
||||
// Using a stack to store complexity (handling nested functions)
|
||||
const fns = [];
|
||||
// Using a stack to store complexity per code path
|
||||
const complexities = [];
|
||||
|
||||
/**
|
||||
* When parsing a new function, store it in our function stack
|
||||
* @returns {void}
|
||||
* @private
|
||||
*/
|
||||
function startFunction() {
|
||||
fns.push(1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Evaluate the node at the end of function
|
||||
* @param {ASTNode} node node to evaluate
|
||||
* @returns {void}
|
||||
* @private
|
||||
*/
|
||||
function endFunction(node) {
|
||||
const name = upperCaseFirst(astUtils.getFunctionNameWithKind(node));
|
||||
const complexity = fns.pop();
|
||||
|
||||
if (complexity > THRESHOLD) {
|
||||
context.report({
|
||||
node,
|
||||
messageId: "complex",
|
||||
data: { name, complexity, max: THRESHOLD }
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Increase the complexity of the function in context
|
||||
* Increase the complexity of the code path in context
|
||||
* @returns {void}
|
||||
* @private
|
||||
*/
|
||||
function increaseComplexity() {
|
||||
if (fns.length) {
|
||||
fns[fns.length - 1]++;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Increase the switch complexity in context
|
||||
* @param {ASTNode} node node to evaluate
|
||||
* @returns {void}
|
||||
* @private
|
||||
*/
|
||||
function increaseSwitchComplexity(node) {
|
||||
|
||||
// Avoiding `default`
|
||||
if (node.test) {
|
||||
increaseComplexity();
|
||||
}
|
||||
complexities[complexities.length - 1]++;
|
||||
}
|
||||
|
||||
//--------------------------------------------------------------------------
|
||||
@@ -136,13 +91,14 @@ module.exports = {
|
||||
//--------------------------------------------------------------------------
|
||||
|
||||
return {
|
||||
FunctionDeclaration: startFunction,
|
||||
FunctionExpression: startFunction,
|
||||
ArrowFunctionExpression: startFunction,
|
||||
"FunctionDeclaration:exit": endFunction,
|
||||
"FunctionExpression:exit": endFunction,
|
||||
"ArrowFunctionExpression:exit": endFunction,
|
||||
|
||||
onCodePathStart() {
|
||||
|
||||
// The initial complexity is 1, representing one execution path in the CodePath
|
||||
complexities.push(1);
|
||||
},
|
||||
|
||||
// Each branching in the code adds 1 to the complexity
|
||||
CatchClause: increaseComplexity,
|
||||
ConditionalExpression: increaseComplexity,
|
||||
LogicalExpression: increaseComplexity,
|
||||
@@ -150,14 +106,49 @@ module.exports = {
|
||||
ForInStatement: increaseComplexity,
|
||||
ForOfStatement: increaseComplexity,
|
||||
IfStatement: increaseComplexity,
|
||||
SwitchCase: increaseSwitchComplexity,
|
||||
WhileStatement: increaseComplexity,
|
||||
DoWhileStatement: increaseComplexity,
|
||||
|
||||
// Avoid `default`
|
||||
"SwitchCase[test]": increaseComplexity,
|
||||
|
||||
// Logical assignment operators have short-circuiting behavior
|
||||
AssignmentExpression(node) {
|
||||
if (astUtils.isLogicalAssignmentOperator(node.operator)) {
|
||||
increaseComplexity();
|
||||
}
|
||||
},
|
||||
|
||||
onCodePathEnd(codePath, node) {
|
||||
const complexity = complexities.pop();
|
||||
|
||||
/*
|
||||
* This rule only evaluates complexity of functions, so "program" is excluded.
|
||||
* Class field initializers are implicit functions. Therefore, they shouldn't contribute
|
||||
* to the enclosing function's complexity, but their own complexity should be evaluated.
|
||||
*/
|
||||
if (
|
||||
codePath.origin !== "function" &&
|
||||
codePath.origin !== "class-field-initializer"
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (complexity > THRESHOLD) {
|
||||
const name = codePath.origin === "class-field-initializer"
|
||||
? "class field initializer"
|
||||
: astUtils.getFunctionNameWithKind(node);
|
||||
|
||||
context.report({
|
||||
node,
|
||||
messageId: "complex",
|
||||
data: {
|
||||
name: upperCaseFirst(name),
|
||||
complexity,
|
||||
max: THRESHOLD
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
+2
-2
@@ -16,7 +16,6 @@ module.exports = {
|
||||
|
||||
docs: {
|
||||
description: "enforce consistent spacing inside computed property brackets",
|
||||
category: "Stylistic Issues",
|
||||
recommended: false,
|
||||
url: "https://eslint.org/docs/rules/computed-property-spacing"
|
||||
},
|
||||
@@ -195,7 +194,8 @@ module.exports = {
|
||||
};
|
||||
|
||||
if (enforceForClassMembers) {
|
||||
listeners.MethodDefinition = checkSpacing("key");
|
||||
listeners.MethodDefinition =
|
||||
listeners.PropertyDefinition = listeners.Property;
|
||||
}
|
||||
|
||||
return listeners;
|
||||
|
||||
-1
@@ -46,7 +46,6 @@ module.exports = {
|
||||
|
||||
docs: {
|
||||
description: "require `return` statements to either always or never specify values",
|
||||
category: "Best Practices",
|
||||
recommended: false,
|
||||
url: "https://eslint.org/docs/rules/consistent-return"
|
||||
},
|
||||
|
||||
+1
-2
@@ -14,7 +14,6 @@ module.exports = {
|
||||
|
||||
docs: {
|
||||
description: "enforce consistent naming when capturing the current execution context",
|
||||
category: "Stylistic Issues",
|
||||
recommended: false,
|
||||
url: "https://eslint.org/docs/rules/consistent-this"
|
||||
},
|
||||
@@ -47,7 +46,7 @@ module.exports = {
|
||||
* Reports that a variable declarator or assignment expression is assigning
|
||||
* a non-'this' value to the specified alias.
|
||||
* @param {ASTNode} node The assigning node.
|
||||
* @param {string} name the name of the alias that was incorrectly used.
|
||||
* @param {string} name the name of the alias that was incorrectly used.
|
||||
* @returns {void}
|
||||
*/
|
||||
function reportBadAssignment(node, name) {
|
||||
|
||||
-1
@@ -122,7 +122,6 @@ module.exports = {
|
||||
|
||||
docs: {
|
||||
description: "require `super()` calls in constructors",
|
||||
category: "ECMAScript 6",
|
||||
recommended: true,
|
||||
url: "https://eslint.org/docs/rules/constructor-super"
|
||||
},
|
||||
|
||||
-1
@@ -20,7 +20,6 @@ module.exports = {
|
||||
|
||||
docs: {
|
||||
description: "enforce consistent brace style for all control statements",
|
||||
category: "Best Practices",
|
||||
recommended: false,
|
||||
url: "https://eslint.org/docs/rules/curly"
|
||||
},
|
||||
|
||||
-1
@@ -15,7 +15,6 @@ module.exports = {
|
||||
|
||||
docs: {
|
||||
description: "enforce default clauses in switch statements to be last",
|
||||
category: "Best Practices",
|
||||
recommended: false,
|
||||
url: "https://eslint.org/docs/rules/default-case-last"
|
||||
},
|
||||
|
||||
+2
-3
@@ -16,7 +16,6 @@ module.exports = {
|
||||
|
||||
docs: {
|
||||
description: "require `default` cases in `switch` statements",
|
||||
category: "Best Practices",
|
||||
recommended: false,
|
||||
url: "https://eslint.org/docs/rules/default-case"
|
||||
},
|
||||
@@ -50,8 +49,8 @@ module.exports = {
|
||||
|
||||
/**
|
||||
* Shortcut to get last element of array
|
||||
* @param {*[]} collection Array
|
||||
* @returns {*} Last element
|
||||
* @param {*[]} collection Array
|
||||
* @returns {any} Last element
|
||||
*/
|
||||
function last(collection) {
|
||||
return collection[collection.length - 1];
|
||||
|
||||
+1
-2
@@ -11,7 +11,6 @@ module.exports = {
|
||||
|
||||
docs: {
|
||||
description: "enforce default parameters to be last",
|
||||
category: "Best Practices",
|
||||
recommended: false,
|
||||
url: "https://eslint.org/docs/rules/default-param-last"
|
||||
},
|
||||
@@ -25,8 +24,8 @@ module.exports = {
|
||||
|
||||
create(context) {
|
||||
|
||||
// eslint-disable-next-line jsdoc/require-description
|
||||
/**
|
||||
* Handler for function contexts.
|
||||
* @param {ASTNode} node function node
|
||||
* @returns {void}
|
||||
*/
|
||||
|
||||
-1
@@ -17,7 +17,6 @@ module.exports = {
|
||||
|
||||
docs: {
|
||||
description: "enforce consistent newlines before and after dots",
|
||||
category: "Best Practices",
|
||||
recommended: false,
|
||||
url: "https://eslint.org/docs/rules/dot-location"
|
||||
},
|
||||
|
||||
+1
-1
@@ -26,7 +26,6 @@ module.exports = {
|
||||
|
||||
docs: {
|
||||
description: "enforce dot notation whenever possible",
|
||||
category: "Best Practices",
|
||||
recommended: false,
|
||||
url: "https://eslint.org/docs/rules/dot-notation"
|
||||
},
|
||||
@@ -141,6 +140,7 @@ module.exports = {
|
||||
if (
|
||||
!allowKeywords &&
|
||||
!node.computed &&
|
||||
node.property.type === "Identifier" &&
|
||||
keywords.indexOf(String(node.property.name)) !== -1
|
||||
) {
|
||||
context.report({
|
||||
|
||||
+6
-2
@@ -14,7 +14,6 @@ module.exports = {
|
||||
|
||||
docs: {
|
||||
description: "require or disallow newline at the end of files",
|
||||
category: "Stylistic Issues",
|
||||
recommended: false,
|
||||
url: "https://eslint.org/docs/rules/eol-last"
|
||||
},
|
||||
@@ -86,10 +85,15 @@ module.exports = {
|
||||
});
|
||||
} else if (mode === "never" && endsWithNewline) {
|
||||
|
||||
const secondLastLine = sourceCode.lines[sourceCode.lines.length - 2];
|
||||
|
||||
// File is newline-terminated, but shouldn't be
|
||||
context.report({
|
||||
node,
|
||||
loc: location,
|
||||
loc: {
|
||||
start: { line: sourceCode.lines.length - 1, column: secondLastLine.length },
|
||||
end: { line: sourceCode.lines.length, column: 0 }
|
||||
},
|
||||
messageId: "unexpected",
|
||||
fix(fixer) {
|
||||
const finalEOLs = /(?:\r?\n)+$/u,
|
||||
|
||||
+1
-2
@@ -21,7 +21,6 @@ module.exports = {
|
||||
|
||||
docs: {
|
||||
description: "require the use of `===` and `!==`",
|
||||
category: "Best Practices",
|
||||
recommended: false,
|
||||
url: "https://eslint.org/docs/rules/eqeqeq"
|
||||
},
|
||||
@@ -78,7 +77,7 @@ module.exports = {
|
||||
|
||||
/**
|
||||
* Checks if an expression is a typeof expression
|
||||
* @param {ASTNode} node The node to check
|
||||
* @param {ASTNode} node The node to check
|
||||
* @returns {boolean} if the node is a typeof expression
|
||||
*/
|
||||
function isTypeOf(node) {
|
||||
|
||||
-1
@@ -15,7 +15,6 @@ module.exports = {
|
||||
|
||||
docs: {
|
||||
description: "enforce \"for\" loop update clause moving the counter in the right direction.",
|
||||
category: "Possible Errors",
|
||||
recommended: true,
|
||||
url: "https://eslint.org/docs/rules/for-direction"
|
||||
},
|
||||
|
||||
-1
@@ -21,7 +21,6 @@ module.exports = {
|
||||
|
||||
docs: {
|
||||
description: "require or disallow spacing between function identifiers and their invocations",
|
||||
category: "Stylistic Issues",
|
||||
recommended: false,
|
||||
url: "https://eslint.org/docs/rules/func-call-spacing"
|
||||
},
|
||||
|
||||
+9
-6
@@ -74,7 +74,6 @@ module.exports = {
|
||||
|
||||
docs: {
|
||||
description: "require function names to match the name of the variable or property to which they are assigned",
|
||||
category: "Stylistic Issues",
|
||||
recommended: false,
|
||||
url: "https://eslint.org/docs/rules/func-name-matching"
|
||||
},
|
||||
@@ -196,21 +195,25 @@ module.exports = {
|
||||
const isProp = node.left.type === "MemberExpression";
|
||||
const name = isProp ? astUtils.getStaticPropertyName(node.left) : node.left.name;
|
||||
|
||||
if (node.right.id && isIdentifier(name) && shouldWarn(name, node.right.id.name)) {
|
||||
if (node.right.id && name && isIdentifier(name) && shouldWarn(name, node.right.id.name)) {
|
||||
report(node, name, node.right.id.name, isProp);
|
||||
}
|
||||
},
|
||||
|
||||
Property(node) {
|
||||
if (node.value.type !== "FunctionExpression" || !node.value.id || node.computed && !isStringLiteral(node.key)) {
|
||||
"Property, PropertyDefinition[value]"(node) {
|
||||
if (!(node.value.type === "FunctionExpression" && node.value.id)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (node.key.type === "Identifier") {
|
||||
if (node.key.type === "Identifier" && !node.computed) {
|
||||
const functionName = node.value.id.name;
|
||||
let propertyName = node.key.name;
|
||||
|
||||
if (considerPropertyDescriptor && propertyName === "value") {
|
||||
if (
|
||||
considerPropertyDescriptor &&
|
||||
propertyName === "value" &&
|
||||
node.parent.type === "ObjectExpression"
|
||||
) {
|
||||
if (isPropertyCall("Object", "defineProperty", node.parent.parent) || isPropertyCall("Reflect", "defineProperty", node.parent.parent)) {
|
||||
const property = node.parent.parent.arguments[1];
|
||||
|
||||
|
||||
+1
-1
@@ -30,7 +30,6 @@ module.exports = {
|
||||
|
||||
docs: {
|
||||
description: "require or disallow named `function` expressions",
|
||||
category: "Stylistic Issues",
|
||||
recommended: false,
|
||||
url: "https://eslint.org/docs/rules/func-names"
|
||||
},
|
||||
@@ -118,6 +117,7 @@ module.exports = {
|
||||
return isObjectOrClassMethod(node) ||
|
||||
(parent.type === "VariableDeclarator" && parent.id.type === "Identifier" && parent.init === node) ||
|
||||
(parent.type === "Property" && parent.value === node) ||
|
||||
(parent.type === "PropertyDefinition" && parent.value === node) ||
|
||||
(parent.type === "AssignmentExpression" && parent.left.type === "Identifier" && parent.right === node) ||
|
||||
(parent.type === "AssignmentPattern" && parent.left.type === "Identifier" && parent.right === node);
|
||||
}
|
||||
|
||||
-1
@@ -14,7 +14,6 @@ module.exports = {
|
||||
|
||||
docs: {
|
||||
description: "enforce the consistent use of either `function` declarations or expressions",
|
||||
category: "Stylistic Issues",
|
||||
recommended: false,
|
||||
url: "https://eslint.org/docs/rules/func-style"
|
||||
},
|
||||
|
||||
-1
@@ -15,7 +15,6 @@ module.exports = {
|
||||
|
||||
docs: {
|
||||
description: "enforce line breaks between arguments of a function call",
|
||||
category: "Stylistic Issues",
|
||||
recommended: false,
|
||||
url: "https://eslint.org/docs/rules/function-call-argument-newline"
|
||||
},
|
||||
|
||||
+1
-1
@@ -20,7 +20,6 @@ module.exports = {
|
||||
|
||||
docs: {
|
||||
description: "enforce consistent line breaks inside function parentheses",
|
||||
category: "Stylistic Issues",
|
||||
recommended: false,
|
||||
url: "https://eslint.org/docs/rules/function-paren-newline"
|
||||
},
|
||||
@@ -183,6 +182,7 @@ module.exports = {
|
||||
/**
|
||||
* Gets the left paren and right paren tokens of a node.
|
||||
* @param {ASTNode} node The node with parens
|
||||
* @throws {TypeError} Unexecpted node type.
|
||||
* @returns {Object} An object with keys `leftParen` for the left paren token, and `rightParen` for the right paren token.
|
||||
* Can also return `null` if an expression has no parens (e.g. a NewExpression with no arguments, or an ArrowFunctionExpression
|
||||
* with a single parameter)
|
||||
|
||||
-1
@@ -31,7 +31,6 @@ module.exports = {
|
||||
|
||||
docs: {
|
||||
description: "enforce consistent spacing around `*` operators in generator functions",
|
||||
category: "ECMAScript 6",
|
||||
recommended: false,
|
||||
url: "https://eslint.org/docs/rules/generator-star-spacing"
|
||||
},
|
||||
|
||||
-1
@@ -35,7 +35,6 @@ module.exports = {
|
||||
|
||||
docs: {
|
||||
description: "enforce `return` statements in getters",
|
||||
category: "Possible Errors",
|
||||
recommended: true,
|
||||
url: "https://eslint.org/docs/rules/getter-return"
|
||||
},
|
||||
|
||||
+1
-1
@@ -1,6 +1,7 @@
|
||||
/**
|
||||
* @fileoverview Rule for disallowing require() outside of the top-level module context
|
||||
* @author Jamund Ferguson
|
||||
* @deprecated in ESLint v7.0.0
|
||||
*/
|
||||
|
||||
"use strict";
|
||||
@@ -57,7 +58,6 @@ module.exports = {
|
||||
|
||||
docs: {
|
||||
description: "require `require()` calls to be placed at top-level module scope",
|
||||
category: "Node.js and CommonJS",
|
||||
recommended: false,
|
||||
url: "https://eslint.org/docs/rules/global-require"
|
||||
},
|
||||
|
||||
-1
@@ -96,7 +96,6 @@ module.exports = {
|
||||
|
||||
docs: {
|
||||
description: "require grouped accessor pairs in object literals and classes",
|
||||
category: "Best Practices",
|
||||
recommended: false,
|
||||
url: "https://eslint.org/docs/rules/grouped-accessor-pairs"
|
||||
},
|
||||
|
||||
-1
@@ -15,7 +15,6 @@ module.exports = {
|
||||
|
||||
docs: {
|
||||
description: "require `for-in` loops to include an `if` statement",
|
||||
category: "Best Practices",
|
||||
recommended: false,
|
||||
url: "https://eslint.org/docs/rules/guard-for-in"
|
||||
},
|
||||
|
||||
+1
-1
@@ -1,6 +1,7 @@
|
||||
/**
|
||||
* @fileoverview Ensure handling of errors when we know they exist.
|
||||
* @author Jamund Ferguson
|
||||
* @deprecated in ESLint v7.0.0
|
||||
*/
|
||||
|
||||
"use strict";
|
||||
@@ -19,7 +20,6 @@ module.exports = {
|
||||
|
||||
docs: {
|
||||
description: "require error handling in callbacks",
|
||||
category: "Node.js and CommonJS",
|
||||
recommended: false,
|
||||
url: "https://eslint.org/docs/rules/handle-callback-err"
|
||||
},
|
||||
|
||||
+14
-3
@@ -2,6 +2,7 @@
|
||||
* @fileoverview Rule that warns when identifier names that are
|
||||
* specified in the configuration are used.
|
||||
* @author Keith Cirkel (http://keithcirkel.co.uk)
|
||||
* @deprecated in ESLint v7.5.0
|
||||
*/
|
||||
|
||||
"use strict";
|
||||
@@ -118,7 +119,6 @@ module.exports = {
|
||||
|
||||
docs: {
|
||||
description: "disallow specified identifiers",
|
||||
category: "Stylistic Issues",
|
||||
recommended: false,
|
||||
url: "https://eslint.org/docs/rules/id-blacklist"
|
||||
},
|
||||
@@ -205,7 +205,17 @@ module.exports = {
|
||||
* @private
|
||||
*/
|
||||
function report(node) {
|
||||
if (!reportedNodes.has(node)) {
|
||||
|
||||
/*
|
||||
* We used the range instead of the node because it's possible
|
||||
* for the same identifier to be represented by two different
|
||||
* nodes, with the most clear example being shorthand properties:
|
||||
* { foo }
|
||||
* In this case, "foo" is represented by one node for the name
|
||||
* and one for the value. The only way to know they are the same
|
||||
* is to look at the range.
|
||||
*/
|
||||
if (!reportedNodes.has(node.range.toString())) {
|
||||
context.report({
|
||||
node,
|
||||
messageId: "restricted",
|
||||
@@ -213,8 +223,9 @@ module.exports = {
|
||||
name: node.name
|
||||
}
|
||||
});
|
||||
reportedNodes.add(node);
|
||||
reportedNodes.add(node.range.toString());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
return {
|
||||
|
||||
+27
-31
@@ -69,14 +69,14 @@ function isRenamedImport(node) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether the given node is a renamed identifier node in an ObjectPattern destructuring.
|
||||
* Checks whether the given node is an ObjectPattern destructuring.
|
||||
*
|
||||
* Examples:
|
||||
* const { a : b } = foo; // node `a` is renamed node.
|
||||
* const { a : b } = foo;
|
||||
* @param {ASTNode} node `Identifier` node to check.
|
||||
* @returns {boolean} `true` if the node is a renamed node in an ObjectPattern destructuring.
|
||||
* @returns {boolean} `true` if the node is in an ObjectPattern destructuring.
|
||||
*/
|
||||
function isRenamedInDestructuring(node) {
|
||||
function isPropertyNameInDestructuring(node) {
|
||||
const parent = node.parent;
|
||||
|
||||
return (
|
||||
@@ -84,27 +84,11 @@ function isRenamedInDestructuring(node) {
|
||||
!parent.computed &&
|
||||
parent.type === "Property" &&
|
||||
parent.parent.type === "ObjectPattern" &&
|
||||
parent.value !== node &&
|
||||
parent.key === node
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether the given node represents shorthand definition of a property in an object literal.
|
||||
* @param {ASTNode} node `Identifier` node to check.
|
||||
* @returns {boolean} `true` if the node is a shorthand property definition.
|
||||
*/
|
||||
function isShorthandPropertyDefinition(node) {
|
||||
const parent = node.parent;
|
||||
|
||||
return (
|
||||
parent.type === "Property" &&
|
||||
parent.parent.type === "ObjectExpression" &&
|
||||
parent.shorthand
|
||||
);
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Rule Definition
|
||||
//------------------------------------------------------------------------------
|
||||
@@ -115,7 +99,6 @@ module.exports = {
|
||||
|
||||
docs: {
|
||||
description: "disallow specified identifiers",
|
||||
category: "Stylistic Issues",
|
||||
recommended: false,
|
||||
url: "https://eslint.org/docs/rules/id-denylist"
|
||||
},
|
||||
@@ -128,7 +111,8 @@ module.exports = {
|
||||
uniqueItems: true
|
||||
},
|
||||
messages: {
|
||||
restricted: "Identifier '{{name}}' is restricted."
|
||||
restricted: "Identifier '{{name}}' is restricted.",
|
||||
restrictedPrivate: "Identifier '#{{name}}' is restricted."
|
||||
}
|
||||
},
|
||||
|
||||
@@ -187,11 +171,8 @@ module.exports = {
|
||||
parent.type !== "CallExpression" &&
|
||||
parent.type !== "NewExpression" &&
|
||||
!isRenamedImport(node) &&
|
||||
!isRenamedInDestructuring(node) &&
|
||||
!(
|
||||
isReferenceToGlobalVariable(node) &&
|
||||
!isShorthandPropertyDefinition(node)
|
||||
)
|
||||
!isPropertyNameInDestructuring(node) &&
|
||||
!isReferenceToGlobalVariable(node)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -202,15 +183,27 @@ module.exports = {
|
||||
* @private
|
||||
*/
|
||||
function report(node) {
|
||||
if (!reportedNodes.has(node)) {
|
||||
|
||||
/*
|
||||
* We used the range instead of the node because it's possible
|
||||
* for the same identifier to be represented by two different
|
||||
* nodes, with the most clear example being shorthand properties:
|
||||
* { foo }
|
||||
* In this case, "foo" is represented by one node for the name
|
||||
* and one for the value. The only way to know they are the same
|
||||
* is to look at the range.
|
||||
*/
|
||||
if (!reportedNodes.has(node.range.toString())) {
|
||||
const isPrivate = node.type === "PrivateIdentifier";
|
||||
|
||||
context.report({
|
||||
node,
|
||||
messageId: "restricted",
|
||||
messageId: isPrivate ? "restrictedPrivate" : "restricted",
|
||||
data: {
|
||||
name: node.name
|
||||
}
|
||||
});
|
||||
reportedNodes.add(node);
|
||||
reportedNodes.add(node.range.toString());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -220,7 +213,10 @@ module.exports = {
|
||||
globalScope = context.getScope();
|
||||
},
|
||||
|
||||
Identifier(node) {
|
||||
[[
|
||||
"Identifier",
|
||||
"PrivateIdentifier"
|
||||
]](node) {
|
||||
if (isRestricted(node.name) && shouldCheck(node)) {
|
||||
report(node);
|
||||
}
|
||||
|
||||
+33
-10
@@ -16,7 +16,6 @@ module.exports = {
|
||||
|
||||
docs: {
|
||||
description: "enforce minimum and maximum identifier lengths",
|
||||
category: "Stylistic Issues",
|
||||
recommended: false,
|
||||
url: "https://eslint.org/docs/rules/id-length"
|
||||
},
|
||||
@@ -55,7 +54,9 @@ module.exports = {
|
||||
],
|
||||
messages: {
|
||||
tooShort: "Identifier name '{{name}}' is too short (< {{min}}).",
|
||||
tooLong: "Identifier name '{{name}}' is too long (> {{max}})."
|
||||
tooShortPrivate: "Identifier name '#{{name}}' is too short (< {{min}}).",
|
||||
tooLong: "Identifier name '{{name}}' is too long (> {{max}}).",
|
||||
tooLongPrivate: "Identifier name #'{{name}}' is too long (> {{max}})."
|
||||
}
|
||||
},
|
||||
|
||||
@@ -66,7 +67,7 @@ module.exports = {
|
||||
const properties = options.properties !== "never";
|
||||
const exceptions = new Set(options.exceptions);
|
||||
const exceptionPatterns = (options.exceptionPatterns || []).map(pattern => new RegExp(pattern, "u"));
|
||||
const reportedNode = new Set();
|
||||
const reportedNodes = new Set();
|
||||
|
||||
/**
|
||||
* Checks if a string matches the provided exception patterns
|
||||
@@ -99,12 +100,14 @@ module.exports = {
|
||||
Property(parent, node) {
|
||||
|
||||
if (parent.parent.type === "ObjectPattern") {
|
||||
const isKeyAndValueSame = parent.value.name === parent.key.name;
|
||||
|
||||
return (
|
||||
parent.value !== parent.key && parent.value === node ||
|
||||
parent.value === parent.key && parent.key === node && properties
|
||||
!isKeyAndValueSame && parent.value === node ||
|
||||
isKeyAndValueSame && parent.key === node && properties
|
||||
);
|
||||
}
|
||||
return properties && !parent.computed && parent.key === node;
|
||||
return properties && !parent.computed && parent.key.name === node.name;
|
||||
},
|
||||
ImportDefaultSpecifier: true,
|
||||
RestElement: true,
|
||||
@@ -113,12 +116,16 @@ module.exports = {
|
||||
ClassDeclaration: true,
|
||||
FunctionDeclaration: true,
|
||||
MethodDefinition: true,
|
||||
PropertyDefinition: true,
|
||||
CatchClause: true,
|
||||
ArrayPattern: true
|
||||
};
|
||||
|
||||
return {
|
||||
Identifier(node) {
|
||||
[[
|
||||
"Identifier",
|
||||
"PrivateIdentifier"
|
||||
]](node) {
|
||||
const name = node.name;
|
||||
const parent = node.parent;
|
||||
|
||||
@@ -131,11 +138,27 @@ module.exports = {
|
||||
|
||||
const isValidExpression = SUPPORTED_EXPRESSIONS[parent.type];
|
||||
|
||||
if (isValidExpression && !reportedNode.has(node) && (isValidExpression === true || isValidExpression(parent, node))) {
|
||||
reportedNode.add(node);
|
||||
/*
|
||||
* We used the range instead of the node because it's possible
|
||||
* for the same identifier to be represented by two different
|
||||
* nodes, with the most clear example being shorthand properties:
|
||||
* { foo }
|
||||
* In this case, "foo" is represented by one node for the name
|
||||
* and one for the value. The only way to know they are the same
|
||||
* is to look at the range.
|
||||
*/
|
||||
if (isValidExpression && !reportedNodes.has(node.range.toString()) && (isValidExpression === true || isValidExpression(parent, node))) {
|
||||
reportedNodes.add(node.range.toString());
|
||||
|
||||
let messageId = isShort ? "tooShort" : "tooLong";
|
||||
|
||||
if (node.type === "PrivateIdentifier") {
|
||||
messageId += "Private";
|
||||
}
|
||||
|
||||
context.report({
|
||||
node,
|
||||
messageId: isShort ? "tooShort" : "tooLong",
|
||||
messageId,
|
||||
data: { name, min: minLength, max: maxLength }
|
||||
});
|
||||
}
|
||||
|
||||
+48
-11
@@ -15,7 +15,6 @@ module.exports = {
|
||||
|
||||
docs: {
|
||||
description: "require identifiers to match a specified regular expression",
|
||||
category: "Stylistic Issues",
|
||||
recommended: false,
|
||||
url: "https://eslint.org/docs/rules/id-match"
|
||||
},
|
||||
@@ -31,6 +30,10 @@ module.exports = {
|
||||
type: "boolean",
|
||||
default: false
|
||||
},
|
||||
classFields: {
|
||||
type: "boolean",
|
||||
default: false
|
||||
},
|
||||
onlyDeclarations: {
|
||||
type: "boolean",
|
||||
default: false
|
||||
@@ -44,7 +47,8 @@ module.exports = {
|
||||
}
|
||||
],
|
||||
messages: {
|
||||
notMatch: "Identifier '{{name}}' does not match the pattern '{{pattern}}'."
|
||||
notMatch: "Identifier '{{name}}' does not match the pattern '{{pattern}}'.",
|
||||
notMatchPrivate: "Identifier '#{{name}}' does not match the pattern '{{pattern}}'."
|
||||
}
|
||||
},
|
||||
|
||||
@@ -57,7 +61,8 @@ module.exports = {
|
||||
regexp = new RegExp(pattern, "u");
|
||||
|
||||
const options = context.options[1] || {},
|
||||
properties = !!options.properties,
|
||||
checkProperties = !!options.properties,
|
||||
checkClassFields = !!options.classFields,
|
||||
onlyDeclarations = !!options.onlyDeclarations,
|
||||
ignoreDestructuring = !!options.ignoreDestructuring;
|
||||
|
||||
@@ -66,7 +71,7 @@ module.exports = {
|
||||
//--------------------------------------------------------------------------
|
||||
|
||||
// contains reported nodes to avoid reporting twice on destructuring with shorthand notation
|
||||
const reported = new Map();
|
||||
const reportedNodes = new Set();
|
||||
const ALLOWED_PARENT_TYPES = new Set(["CallExpression", "NewExpression"]);
|
||||
const DECLARATION_TYPES = new Set(["FunctionDeclaration", "VariableDeclarator"]);
|
||||
const IMPORT_TYPES = new Set(["ImportSpecifier", "ImportNamespaceSpecifier", "ImportDefaultSpecifier"]);
|
||||
@@ -120,16 +125,30 @@ module.exports = {
|
||||
* @private
|
||||
*/
|
||||
function report(node) {
|
||||
if (!reported.has(node)) {
|
||||
|
||||
/*
|
||||
* We used the range instead of the node because it's possible
|
||||
* for the same identifier to be represented by two different
|
||||
* nodes, with the most clear example being shorthand properties:
|
||||
* { foo }
|
||||
* In this case, "foo" is represented by one node for the name
|
||||
* and one for the value. The only way to know they are the same
|
||||
* is to look at the range.
|
||||
*/
|
||||
if (!reportedNodes.has(node.range.toString())) {
|
||||
|
||||
const messageId = (node.type === "PrivateIdentifier")
|
||||
? "notMatchPrivate" : "notMatch";
|
||||
|
||||
context.report({
|
||||
node,
|
||||
messageId: "notMatch",
|
||||
messageId,
|
||||
data: {
|
||||
name: node.name,
|
||||
pattern
|
||||
}
|
||||
});
|
||||
reported.set(node, true);
|
||||
reportedNodes.add(node.range.toString());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -142,7 +161,7 @@ module.exports = {
|
||||
|
||||
if (parent.type === "MemberExpression") {
|
||||
|
||||
if (!properties) {
|
||||
if (!checkProperties) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -176,8 +195,7 @@ module.exports = {
|
||||
} else if (parent.type === "Property" || parent.type === "AssignmentPattern") {
|
||||
|
||||
if (parent.parent && parent.parent.type === "ObjectPattern") {
|
||||
if (parent.shorthand && parent.value.left && isInvalid(name)) {
|
||||
|
||||
if (!ignoreDestructuring && parent.shorthand && parent.value.left && isInvalid(name)) {
|
||||
report(node);
|
||||
}
|
||||
|
||||
@@ -197,7 +215,7 @@ module.exports = {
|
||||
}
|
||||
|
||||
// never check properties or always ignore destructuring
|
||||
if (!properties || (ignoreDestructuring && isInsideObjectPattern(node))) {
|
||||
if (!checkProperties || (ignoreDestructuring && isInsideObjectPattern(node))) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -214,10 +232,29 @@ module.exports = {
|
||||
report(node);
|
||||
}
|
||||
|
||||
} else if (parent.type === "PropertyDefinition") {
|
||||
|
||||
if (checkClassFields && isInvalid(name)) {
|
||||
report(node);
|
||||
}
|
||||
|
||||
// Report anything that is invalid that isn't a CallExpression
|
||||
} else if (shouldReport(effectiveParent, name)) {
|
||||
report(node);
|
||||
}
|
||||
},
|
||||
|
||||
"PrivateIdentifier"(node) {
|
||||
|
||||
const isClassField = node.parent.type === "PropertyDefinition";
|
||||
|
||||
if (isClassField && !checkClassFields) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (isInvalid(node.name)) {
|
||||
report(node);
|
||||
}
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
-1
@@ -15,7 +15,6 @@ module.exports = {
|
||||
|
||||
docs: {
|
||||
description: "enforce the location of arrow function bodies",
|
||||
category: "Stylistic Issues",
|
||||
recommended: false,
|
||||
url: "https://eslint.org/docs/rules/implicit-arrow-linebreak"
|
||||
},
|
||||
|
||||
+1
-1
@@ -4,6 +4,7 @@
|
||||
* This rule has been ported and modified from nodeca.
|
||||
* @author Vitaly Puzrin
|
||||
* @author Gyandeep Singh
|
||||
* @deprecated in ESLint v4.0.0
|
||||
*/
|
||||
|
||||
"use strict";
|
||||
@@ -25,7 +26,6 @@ module.exports = {
|
||||
|
||||
docs: {
|
||||
description: "enforce consistent indentation",
|
||||
category: "Stylistic Issues",
|
||||
recommended: false,
|
||||
url: "https://eslint.org/docs/rules/indent-legacy"
|
||||
},
|
||||
|
||||
+48
-10
@@ -60,8 +60,10 @@ const KNOWN_NODES = new Set([
|
||||
"NewExpression",
|
||||
"ObjectExpression",
|
||||
"ObjectPattern",
|
||||
"PrivateIdentifier",
|
||||
"Program",
|
||||
"Property",
|
||||
"PropertyDefinition",
|
||||
"RestElement",
|
||||
"ReturnStatement",
|
||||
"SequenceExpression",
|
||||
@@ -138,7 +140,7 @@ class BinarySearchTree {
|
||||
/**
|
||||
* Inserts an entry into the tree.
|
||||
* @param {number} key The entry's key
|
||||
* @param {*} value The entry's value
|
||||
* @param {any} value The entry's value
|
||||
* @returns {void}
|
||||
*/
|
||||
insert(key, value) {
|
||||
@@ -188,7 +190,6 @@ class BinarySearchTree {
|
||||
*/
|
||||
class TokenInfo {
|
||||
|
||||
// eslint-disable-next-line jsdoc/require-description
|
||||
/**
|
||||
* @param {SourceCode} sourceCode A SourceCode object
|
||||
*/
|
||||
@@ -238,7 +239,6 @@ class TokenInfo {
|
||||
*/
|
||||
class OffsetStorage {
|
||||
|
||||
// eslint-disable-next-line jsdoc/require-description
|
||||
/**
|
||||
* @param {TokenInfo} tokenInfo a TokenInfo instance
|
||||
* @param {number} indentSize The desired size of each indentation level
|
||||
@@ -263,7 +263,7 @@ class OffsetStorage {
|
||||
|
||||
/**
|
||||
* Sets the offset column of token B to match the offset column of token A.
|
||||
* **WARNING**: This matches a *column*, even if baseToken is not the first token on its line. In
|
||||
* - **WARNING**: This matches a *column*, even if baseToken is not the first token on its line. In
|
||||
* most cases, `setDesiredOffset` should be used instead.
|
||||
* @param {Token} baseToken The first token
|
||||
* @param {Token} offsetToken The second token, whose offset should be matched to the first token
|
||||
@@ -352,11 +352,11 @@ class OffsetStorage {
|
||||
* Instead, the offset tree is represented as a collection of contiguous offset ranges in a file. For example, the following
|
||||
* list could represent the state of the offset tree at a given point:
|
||||
*
|
||||
* * Tokens starting in the interval [0, 15) are aligned with the beginning of the file
|
||||
* * Tokens starting in the interval [15, 30) are offset by 1 indent level from the `bar` token
|
||||
* * Tokens starting in the interval [30, 43) are offset by 1 indent level from the `foo` token
|
||||
* * Tokens starting in the interval [43, 820) are offset by 2 indent levels from the `bar` token
|
||||
* * Tokens starting in the interval [820, ∞) are offset by 1 indent level from the `baz` token
|
||||
* - Tokens starting in the interval [0, 15) are aligned with the beginning of the file
|
||||
* - Tokens starting in the interval [15, 30) are offset by 1 indent level from the `bar` token
|
||||
* - Tokens starting in the interval [30, 43) are offset by 1 indent level from the `foo` token
|
||||
* - Tokens starting in the interval [43, 820) are offset by 2 indent levels from the `bar` token
|
||||
* - Tokens starting in the interval [820, ∞) are offset by 1 indent level from the `baz` token
|
||||
*
|
||||
* The `setDesiredOffsets` methods inserts ranges like the ones above. The third line above would be inserted by using:
|
||||
* `setDesiredOffsets([30, 43], fooToken, 1);`
|
||||
@@ -499,7 +499,6 @@ module.exports = {
|
||||
|
||||
docs: {
|
||||
description: "enforce consistent indentation",
|
||||
category: "Stylistic Issues",
|
||||
recommended: false,
|
||||
url: "https://eslint.org/docs/rules/indent"
|
||||
},
|
||||
@@ -1359,6 +1358,45 @@ module.exports = {
|
||||
}
|
||||
},
|
||||
|
||||
PropertyDefinition(node) {
|
||||
const firstToken = sourceCode.getFirstToken(node);
|
||||
const maybeSemicolonToken = sourceCode.getLastToken(node);
|
||||
let keyLastToken = null;
|
||||
|
||||
// Indent key.
|
||||
if (node.computed) {
|
||||
const bracketTokenL = sourceCode.getTokenBefore(node.key, astUtils.isOpeningBracketToken);
|
||||
const bracketTokenR = keyLastToken = sourceCode.getTokenAfter(node.key, astUtils.isClosingBracketToken);
|
||||
const keyRange = [bracketTokenL.range[1], bracketTokenR.range[0]];
|
||||
|
||||
if (bracketTokenL !== firstToken) {
|
||||
offsets.setDesiredOffset(bracketTokenL, firstToken, 0);
|
||||
}
|
||||
offsets.setDesiredOffsets(keyRange, bracketTokenL, 1);
|
||||
offsets.setDesiredOffset(bracketTokenR, bracketTokenL, 0);
|
||||
} else {
|
||||
const idToken = keyLastToken = sourceCode.getFirstToken(node.key);
|
||||
|
||||
if (idToken !== firstToken) {
|
||||
offsets.setDesiredOffset(idToken, firstToken, 1);
|
||||
}
|
||||
}
|
||||
|
||||
// Indent initializer.
|
||||
if (node.value) {
|
||||
const eqToken = sourceCode.getTokenBefore(node.value, astUtils.isEqToken);
|
||||
const valueToken = sourceCode.getTokenAfter(eqToken);
|
||||
|
||||
offsets.setDesiredOffset(eqToken, keyLastToken, 1);
|
||||
offsets.setDesiredOffset(valueToken, eqToken, 1);
|
||||
if (astUtils.isSemicolonToken(maybeSemicolonToken)) {
|
||||
offsets.setDesiredOffset(maybeSemicolonToken, eqToken, 1);
|
||||
}
|
||||
} else if (astUtils.isSemicolonToken(maybeSemicolonToken)) {
|
||||
offsets.setDesiredOffset(maybeSemicolonToken, keyLastToken, 1);
|
||||
}
|
||||
},
|
||||
|
||||
SwitchStatement(node) {
|
||||
const openingCurly = sourceCode.getTokenAfter(node.discriminant, astUtils.isOpeningBraceToken);
|
||||
const closingCurly = sourceCode.getLastToken(node);
|
||||
|
||||
+1
-1
@@ -6,7 +6,7 @@
|
||||
|
||||
"use strict";
|
||||
|
||||
/* eslint sort-keys: ["error", "asc"] */
|
||||
/* eslint sort-keys: ["error", "asc"] -- More readable for long list */
|
||||
|
||||
const { LazyLoadingRuleMap } = require("./utils/lazy-loading-rule-map");
|
||||
|
||||
|
||||
-1
@@ -48,7 +48,6 @@ module.exports = {
|
||||
|
||||
docs: {
|
||||
description: "require or disallow initialization in variable declarations",
|
||||
category: "Variables",
|
||||
recommended: false,
|
||||
url: "https://eslint.org/docs/rules/init-declarations"
|
||||
},
|
||||
|
||||
-1
@@ -42,7 +42,6 @@ module.exports = {
|
||||
|
||||
docs: {
|
||||
description: "enforce the consistent use of either double or single quotes in JSX attributes",
|
||||
category: "Stylistic Issues",
|
||||
recommended: false,
|
||||
url: "https://eslint.org/docs/rules/jsx-quotes"
|
||||
},
|
||||
|
||||
Loaded 100 of 814 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user