Skip to content

Commit

Permalink
Chore: enable prefer-arrow-callback on ESLint codebase (fixes #6407) (
Browse files Browse the repository at this point in the history
#7503)

* Chore: enable `prefer-arrow-callback` on ESLint codebase (fixes #6407)

* Move some complex expressions onto multiple lines

* Use `.returns(value)` instead of `() => value` with sinon
  • Loading branch information
not-an-aardvark authored and ilyavolodin committed Nov 1, 2016
1 parent 4f1fa67 commit 183def6
Show file tree
Hide file tree
Showing 143 changed files with 2,652 additions and 2,907 deletions.
82 changes: 30 additions & 52 deletions Makefile.js
Expand Up @@ -90,9 +90,7 @@ function getTestFilePatterns() {
testTemplatesPath = "tests/templates/",
testBinPath = "tests/bin/";

return ls(testLibPath).filter(function(pathToCheck) {
return test("-d", testLibPath + pathToCheck);
}).reduce(function(initialValue, currentValues) {
return ls(testLibPath).filter(pathToCheck => test("-d", testLibPath + pathToCheck)).reduce((initialValue, currentValues) => {
if (currentValues !== "rules") {
initialValue.push(`"${testLibPath + currentValues}/**/*.js"`);
}
Expand Down Expand Up @@ -135,7 +133,7 @@ function generateRulesIndex(basedir) {

output += " var rules = Object.create(null);\n";

find(`${basedir}rules/`).filter(fileType("js")).forEach(function(filename) {
find(`${basedir}rules/`).filter(fileType("js")).forEach(filename => {
const basename = path.basename(filename, ".js");

output += ` rules["${basename}"] = require("./rules/${basename}");\n`;
Expand Down Expand Up @@ -204,7 +202,7 @@ function generateRuleIndexPage(basedir) {
categoryList = "conf/category-list.json",
categoriesData = JSON.parse(cat(path.resolve(categoryList)));

find(path.join(basedir, "/lib/rules/")).filter(fileType("js")).forEach(function(filename) {
find(path.join(basedir, "/lib/rules/")).filter(fileType("js")).forEach(filename => {
const rule = require(filename);
const basename = path.basename(filename, ".js");

Expand Down Expand Up @@ -324,7 +322,7 @@ function getTagOfFirstOccurrence(filePath) {
let tags = execSilent(`git tag --contains ${firstCommit}`);

tags = splitCommandResultToLines(tags);
return tags.reduce(function(list, version) {
return tags.reduce((list, version) => {
version = semver.valid(version.trim());
if (version) {
list.push(version);
Expand Down Expand Up @@ -363,12 +361,8 @@ function getFirstVersionOfDeletion(filePath) {
tags = execSilent(`git tag --contains ${deletionCommit}`);

return splitCommandResultToLines(tags)
.map(function(version) {
return semver.valid(version.trim());
})
.filter(function(version) {
return version;
})
.map(version => semver.valid(version.trim()))
.filter(version => version)
.sort(semver.compare)[0];
}

Expand Down Expand Up @@ -476,7 +470,7 @@ function getFormatterResults() {
].join("\n"),
rawMessages = cli.executeOnText(codeString, "fullOfProblems.js", true);

return formatterFiles.reduce(function(data, filename) {
return formatterFiles.reduce((data, filename) => {
const fileExt = path.extname(filename),
name = path.basename(filename, fileExt);

Expand Down Expand Up @@ -594,9 +588,7 @@ target.gensite = function(prereleaseVersion) {

// append version
if (prereleaseVersion) {
docFiles = docFiles.map(function(docFile) {
return `/${prereleaseVersion}${docFile}`;
});
docFiles = docFiles.map(docFile => `/${prereleaseVersion}${docFile}`);
}

// 1. create temp and build directory
Expand All @@ -605,7 +597,7 @@ target.gensite = function(prereleaseVersion) {
}

// 2. remove old files from the site
docFiles.forEach(function(filePath) {
docFiles.forEach(filePath => {
const fullPath = path.join(DOCS_DIR, filePath),
htmlFullPath = fullPath.replace(".md", ".html");

Expand All @@ -632,7 +624,7 @@ target.gensite = function(prereleaseVersion) {
}

// 4. Loop through all files in temporary directory
find(TEMP_DIR).forEach(function(filename) {
find(TEMP_DIR).forEach(filename => {
if (test("-f", filename) && path.extname(filename) === ".md") {

const rulesUrl = "https://github.com/eslint/eslint/tree/master/lib/rules/",
Expand Down Expand Up @@ -763,7 +755,7 @@ target.checkRuleFiles = function() {
const ruleFiles = find("lib/rules/").filter(fileType("js"));
let errors = 0;

ruleFiles.forEach(function(filename) {
ruleFiles.forEach(filename => {
const basename = path.basename(filename, ".js");
const docFilename = `docs/rules/${basename}.md`;

Expand Down Expand Up @@ -838,35 +830,27 @@ target.checkLicenses = function() {
const licenses = dependency.licenses;

if (Array.isArray(licenses)) {
return licenses.some(function(license) {
return isPermissible({
name: dependency.name,
licenses: license
});
});
return licenses.some(license => isPermissible({
name: dependency.name,
licenses: license
}));
}

return OPEN_SOURCE_LICENSES.some(function(license) {
return license.test(licenses);
});
return OPEN_SOURCE_LICENSES.some(license => license.test(licenses));
}

echo("Validating licenses");

checker.init({
start: __dirname
}, function(deps) {
const impermissible = Object.keys(deps).map(function(dependency) {
return {
name: dependency,
licenses: deps[dependency].licenses
};
}).filter(function(dependency) {
return !isPermissible(dependency);
});
}, deps => {
const impermissible = Object.keys(deps).map(dependency => ({
name: dependency,
licenses: deps[dependency].licenses
})).filter(dependency => !isPermissible(dependency));

if (impermissible.length) {
impermissible.forEach(function(dependency) {
impermissible.forEach(dependency => {
console.error("%s license for %s is impermissible.",
dependency.licenses,
dependency.name
Expand Down Expand Up @@ -960,9 +944,7 @@ function createConfigForPerformanceTest() {

content.push.apply(
content,
ls("lib/rules").map(function(fileName) {
return ` ${path.basename(fileName, ".js")}: 1`;
})
ls("lib/rules").map(fileName => ` ${path.basename(fileName, ".js")}: 1`)
);

content.join("\n").to(PERF_ESLINTRC);
Expand All @@ -981,7 +963,7 @@ function createConfigForPerformanceTest() {
function time(cmd, runs, runNumber, results, cb) {
const start = process.hrtime();

exec(cmd, { silent: true }, function(code, stdout, stderr) {
exec(cmd, { silent: true }, (code, stdout, stderr) => {
const diff = process.hrtime(start),
actual = (diff[0] * 1e3 + diff[1] / 1e6); // ms

Expand Down Expand Up @@ -1026,14 +1008,12 @@ function runPerformanceTest(title, targets, multiplier, cb) {
echo(title);
echo(" CPU Speed is %d with multiplier %d", cpuSpeed, multiplier);

time(cmd, 5, 1, [], function(results) {
time(cmd, 5, 1, [], results => {
if (!results || results.length === 0) { // No results? Something is wrong.
throw new Error("Performance test failed.");
}

results.sort(function(a, b) {
return a - b;
});
results.sort((a, b) => a - b);

const median = results[~~(results.length / 2)];

Expand Down Expand Up @@ -1068,9 +1048,7 @@ function loadPerformance() {
results.push(loadPerfData.loadTime);
}

results.sort(function(a, b) {
return a - b;
});
results.sort((a, b) => a - b);
const median = results[~~(results.length / 2)];

echo("");
Expand All @@ -1079,7 +1057,7 @@ function loadPerformance() {
}

target.perf = function() {
downloadMultifilesTestTarget(function() {
downloadMultifilesTestTarget(() => {
createConfigForPerformanceTest();

loadPerformance();
Expand All @@ -1088,7 +1066,7 @@ target.perf = function() {
"Single File:",
"tests/performance/jshint.js",
PERF_MULTIPLIER,
function() {
() => {

// Count test target files.
const count = glob.sync(
Expand All @@ -1101,7 +1079,7 @@ target.perf = function() {
`Multi Files (${count} files):`,
PERF_MULTIFILES_TARGETS,
3 * PERF_MULTIPLIER,
function() {}
() => {}
);
}
);
Expand Down
6 changes: 3 additions & 3 deletions bin/eslint.js
Expand Up @@ -36,7 +36,7 @@ const concat = require("concat-stream"),
// Execution
//------------------------------------------------------------------------------

process.on("uncaughtException", function(err) {
process.on("uncaughtException", err => {

// lazy load
const lodash = require("lodash");
Expand All @@ -55,13 +55,13 @@ process.on("uncaughtException", function(err) {
});

if (useStdIn) {
process.stdin.pipe(concat({ encoding: "string" }, function(text) {
process.stdin.pipe(concat({ encoding: "string" }, text => {
process.exitCode = cli.execute(process.argv, text);
}));
} else if (init) {
const configInit = require("../lib/config/config-initializer");

configInit.initializeConfig(function(err) {
configInit.initializeConfig(err => {
if (err) {
process.exitCode = 1;
console.error(err.message);
Expand Down
4 changes: 1 addition & 3 deletions lib/ast-utils.js
Expand Up @@ -176,9 +176,7 @@ function hasJSDocThisTag(node, sourceCode) {
// because callbacks don't have its JSDoc comment.
// e.g.
// sinon.test(/* @this sinon.Sandbox */function() { this.spy(); });
return sourceCode.getComments(node).leading.some(function(comment) {
return thisTagPattern.test(comment.value);
});
return sourceCode.getComments(node).leading.some(comment => thisTagPattern.test(comment.value));
}

/**
Expand Down
20 changes: 9 additions & 11 deletions lib/cli-engine.js
Expand Up @@ -90,7 +90,7 @@ const debug = require("debug")("eslint:cli-engine");
* @private
*/
function calculateStatsPerFile(messages) {
return messages.reduce(function(stat, message) {
return messages.reduce((stat, message) => {
if (message.fatal || message.severity === 2) {
stat.errorCount++;
} else {
Expand All @@ -110,7 +110,7 @@ function calculateStatsPerFile(messages) {
* @private
*/
function calculateStatsPerRun(results) {
return results.reduce(function(stat, result) {
return results.reduce((stat, result) => {
stat.errorCount += result.errorCount;
stat.warningCount += result.warningCount;
return stat;
Expand Down Expand Up @@ -241,7 +241,7 @@ function processText(text, configHelper, filename, fix, allowInlineConfig) {
const parsedBlocks = processor.preprocess(text, filename);
const unprocessedMessages = [];

parsedBlocks.forEach(function(block) {
parsedBlocks.forEach(block => {
unprocessedMessages.push(eslint.verify(block, config, {
filename,
allowInlineConfig
Expand Down Expand Up @@ -466,15 +466,15 @@ function CLIEngine(options) {
if (this.options.rulePaths) {
const cwd = this.options.cwd;

this.options.rulePaths.forEach(function(rulesdir) {
this.options.rulePaths.forEach(rulesdir => {
debug(`Loading rules from ${rulesdir}`);
rules.load(rulesdir, cwd);
});
}

Object.keys(this.options.rules || {}).forEach(function(name) {
Object.keys(this.options.rules || {}).forEach(name => {
validator.validateRuleOptions(name, this.options.rules[name], "CLI");
}.bind(this));
});
}

/**
Expand Down Expand Up @@ -526,7 +526,7 @@ CLIEngine.getFormatter = function(format) {
CLIEngine.getErrorResults = function(results) {
const filtered = [];

results.forEach(function(result) {
results.forEach(result => {
const filteredMessages = result.messages.filter(isErrorMessage);

if (filteredMessages.length > 0) {
Expand All @@ -549,9 +549,7 @@ CLIEngine.getErrorResults = function(results) {
* @returns {void}
*/
CLIEngine.outputFixes = function(report) {
report.results.filter(function(result) {
return result.hasOwnProperty("output");
}).forEach(function(result) {
report.results.filter(result => result.hasOwnProperty("output")).forEach(result => {
fs.writeFileSync(result.filePath, result.output);
});
};
Expand Down Expand Up @@ -708,7 +706,7 @@ CLIEngine.prototype = {
patterns = this.resolveFileGlobPatterns(patterns);
const fileList = globUtil.listFilesToProcess(patterns, options);

fileList.forEach(function(fileInfo) {
fileList.forEach(fileInfo => {
executeOnFile(fileInfo.filename, fileInfo.ignored);
});

Expand Down
8 changes: 4 additions & 4 deletions lib/code-path-analysis/debug-helpers.js
Expand Up @@ -108,15 +108,15 @@ module.exports = {
}

if (segment.internal.nodes.length > 0) {
text += segment.internal.nodes.map(function(node) {
text += segment.internal.nodes.map(node => {
switch (node.type) {
case "Identifier": return `${node.type} (${node.name})`;
case "Literal": return `${node.type} (${node.value})`;
default: return node.type;
}
}).join("\\n");
} else if (segment.internal.exitNodes.length > 0) {
text += segment.internal.exitNodes.map(function(node) {
text += segment.internal.exitNodes.map(node => {
switch (node.type) {
case "Identifier": return `${node.type}:exit (${node.name})`;
case "Literal": return `${node.type}:exit (${node.value})`;
Expand Down Expand Up @@ -176,7 +176,7 @@ module.exports = {
stack.push([nextSegment, 0]);
}

codePath.returnedSegments.forEach(function(finalSegment) {
codePath.returnedSegments.forEach(finalSegment => {
if (lastId === finalSegment.id) {
text += "->final";
} else {
Expand All @@ -185,7 +185,7 @@ module.exports = {
lastId = null;
});

codePath.thrownSegments.forEach(function(finalSegment) {
codePath.thrownSegments.forEach(finalSegment => {
if (lastId === finalSegment.id) {
text += "->thrown";
} else {
Expand Down
4 changes: 2 additions & 2 deletions lib/config.js
Expand Up @@ -197,7 +197,7 @@ function Config(options) {

this.useEslintrc = (options.useEslintrc !== false);

this.env = (options.envs || []).reduce(function(envs, name) {
this.env = (options.envs || []).reduce((envs, name) => {
envs[name] = true;
return envs;
}, {});
Expand All @@ -208,7 +208,7 @@ function Config(options) {
* whether global is writable.
* If user declares "foo", convert to "foo:false".
*/
this.globals = (options.globals || []).reduce(function(globals, def) {
this.globals = (options.globals || []).reduce((globals, def) => {
const parts = def.split(":");

globals[parts[0]] = (parts.length > 1 && parts[1] === "true");
Expand Down

0 comments on commit 183def6

Please sign in to comment.