Bug 1344027 - Move eslint-plugin-mozilla's .eslintrc.js file so that all of the plugin is linted, and fix the resulting issues. r=mossop

MozReview-Commit-ID: POYhxkeOaw

--HG--
rename : tools/lint/eslint/eslint-plugin-mozilla/lib/rules/.eslintrc.js => tools/lint/eslint/eslint-plugin-mozilla/.eslintrc.js
extra : rebase_source : efd9a97796e72e94c436df6f4223a12d6daa036a
This commit is contained in:
Mark Banner 2017-03-03 10:17:54 +00:00
Родитель 8796160b00
Коммит 7d5e6f23c5
16 изменённых файлов: 135 добавлений и 90 удалений

Просмотреть файл

@ -34,18 +34,21 @@ const EXTRA_SCRIPTS = [
// Via editMenuOverlay.xul
"toolkit/content/editMenuOverlay.js",
// Via baseMenuOverlay.xul
"browser/base/content/utilityOverlay.js",
"browser/base/content/utilityOverlay.js"
];
// Some files in global-scripts.inc need mapping to specific locations.
const MAPPINGS = {
"printUtils.js": "toolkit/components/printing/content/printUtils.js",
"browserPlacesViews.js": "browser/components/places/content/browserPlacesViews.js",
"browserPlacesViews.js":
"browser/components/places/content/browserPlacesViews.js",
"panelUI.js": "browser/components/customizableui/content/panelUI.js",
"viewSourceUtils.js": "toolkit/components/viewsource/content/viewSourceUtils.js",
"viewSourceUtils.js":
"toolkit/components/viewsource/content/viewSourceUtils.js"
};
const globalScriptsRegExp = /<script type=\"application\/javascript\" src=\"(.*)\"\/>/;
const globalScriptsRegExp =
/<script type=\"application\/javascript\" src=\"(.*)\"\/>/;
function getGlobalScriptsIncludes() {
let globalScriptsPath = path.join(rootDir, "browser", "base", "content",
@ -59,8 +62,9 @@ function getGlobalScriptsIncludes() {
for (let line of fileData) {
let match = line.match(globalScriptsRegExp);
if (match) {
let sourceFile = match[1].replace("chrome://browser/content/", "browser/base/content/")
.replace("chrome://global/content/", "toolkit/content/");
let sourceFile =
match[1].replace("chrome://browser/content/", "browser/base/content/")
.replace("chrome://global/content/", "toolkit/content/");
for (let mapping of Object.getOwnPropertyNames(MAPPINGS)) {
if (sourceFile.includes(mapping)) {
@ -84,8 +88,9 @@ function getScriptGlobals() {
fileGlobals = fileGlobals.concat(globals.getGlobalsForFile(fileName));
} catch (e) {
console.error(`Could not load globals from file ${fileName}: ${e}`);
console.error(`You may need to update the mappings in ${module.filename}`);
throw new Error(`Could not load globals from file ${fileName}: ${e}`)
console.error(
`You may need to update the mappings in ${module.filename}`);
throw new Error(`Could not load globals from file ${fileName}: ${e}`);
}
}

Просмотреть файл

@ -17,13 +17,14 @@ var path = require("path");
var helpers = require("../helpers");
var globals = require("../globals");
var root = helpers.getRootDir(module.filename);
var modules = require(path.join(root, "tools", "lint", "eslint", "modules.json"));
var modules = require(path.join(root,
"tools", "lint", "eslint", "modules.json"));
const placesOverlayFiles = [
"toolkit/content/globalOverlay.js",
"browser/base/content/utilityOverlay.js",
"browser/components/places/content/controller.js",
"browser/components/places/content/treeView.js",
"browser/components/places/content/treeView.js"
];
const extraPlacesDefinitions = [
@ -32,26 +33,26 @@ const extraPlacesDefinitions = [
{name: "Ci", writable: false},
{name: "Cr", writable: false},
{name: "Cu", writable: false},
// Via Components.utils / XPCOMUtils.defineLazyModuleGetter (and map to single)
// variable.
// Via Components.utils / XPCOMUtils.defineLazyModuleGetter (and map to
// single) variable.
{name: "XPCOMUtils", writable: false},
{name: "Task", writable: false},
{name: "PlacesUIUtils", writable: false},
{name: "PlacesTransactions", writable: false},
]
{name: "PlacesTransactions", writable: false}
];
const placesOverlayModules = [
"PlacesUtils.jsm",
]
"PlacesUtils.jsm"
];
function getScriptGlobals() {
let fileGlobals = [];
for (let file of placesOverlayFiles) {
let fileName = path.join(root, file)
let fileName = path.join(root, file);
try {
fileGlobals = fileGlobals.concat(globals.getGlobalsForFile(fileName));
} catch (e) {
throw new Error(`Could not load globals from file ${fileName}: ${e}`)
throw new Error(`Could not load globals from file ${fileName}: ${e}`);
}
}

Просмотреть файл

@ -29,11 +29,11 @@ function getScriptGlobals() {
let fileGlobals = [];
let root = helpers.getRootDir(module.filename);
for (let file of simpleTestFiles) {
let fileName = path.join(root, simpleTestPath, file)
let fileName = path.join(root, simpleTestPath, file);
try {
fileGlobals = fileGlobals.concat(globals.getGlobalsForFile(fileName));
} catch (e) {
throw new Error(`Could not load globals from file ${fileName}: ${e}`)
throw new Error(`Could not load globals from file ${fileName}: ${e}`);
}
}

Просмотреть файл

@ -15,8 +15,8 @@ const escope = require("escope");
const estraverse = require("estraverse");
/**
* Parses a list of "name:boolean_value" or/and "name" options divided by comma or
* whitespace.
* Parses a list of "name:boolean_value" or/and "name" options divided by comma
* or whitespace.
*
* This function was copied from eslint.js
*
@ -38,7 +38,7 @@ function parseBooleanConfig(string, comment) {
}
let pos = name.indexOf(":");
let value = undefined;
let value;
if (pos !== -1) {
value = name.substring(pos + 1, name.length);
name = name.substring(0, pos);
@ -77,7 +77,7 @@ var globalDiscoveryInProgressForFiles = new Set();
*/
function GlobalsForNode(filePath) {
this.path = filePath;
this.dirname = path.dirname(this.path)
this.dirname = path.dirname(this.path);
this.root = helpers.getRootDir(this.path);
}
@ -102,7 +102,9 @@ GlobalsForNode.prototype = {
let isGlobal = helpers.getIsGlobalScope(parents);
let globals = helpers.convertExpressionToGlobals(node, isGlobal, this.root);
// Map these globals now, as getGlobalsForFile is pre-mapped.
globals = globals.map(name => { return { name, writable: true }});
globals = globals.map(name => {
return { name, writable: true };
});
// Here we assume that if importScripts is set in the global scope, then
// this is a worker. It would be nice if eslint gave us a way of getting
@ -114,7 +116,7 @@ GlobalsForNode.prototype = {
}
return globals;
},
}
};
module.exports = {
@ -156,7 +158,7 @@ module.exports = {
let globals = Object.keys(globalScope.variables).map(v => ({
name: globalScope.variables[v].name,
writable: true,
writable: true
}));
// Walk over the AST to find any of our custom globals
@ -175,7 +177,7 @@ module.exports = {
globals.push({
name,
writable: values[name].value
})
});
}
}
}
@ -218,7 +220,7 @@ module.exports = {
}
let globals = handler[type](node, context.getAncestors(), globalScope);
helpers.addGlobals(globals, globalScope);
}
};
}
return parser;

Просмотреть файл

@ -35,7 +35,7 @@ var definitions = [
];
var imports = [
/^(?:Cu|Components\.utils)\.import\(".*\/((.*?)\.jsm?)"(?:, this)?\)/,
/^(?:Cu|Components\.utils)\.import\(".*\/((.*?)\.jsm?)"(?:, this)?\)/
];
var workerImportFilenameMatch = /(.*\/)*(.*?\.jsm?)/;
@ -71,9 +71,11 @@ module.exports = {
getASTSource: function(node) {
switch (node.type) {
case "MemberExpression":
if (node.computed)
if (node.computed) {
throw new Error("getASTSource unsupported computed MemberExpression");
return this.getASTSource(node.object) + "." + this.getASTSource(node.property);
}
return this.getASTSource(node.object) + "." +
this.getASTSource(node.property);
case "ThisExpression":
return "this";
case "Identifier":
@ -92,7 +94,8 @@ module.exports = {
case "ArrowFunctionExpression":
return "() => {}";
case "AssignmentExpression":
return this.getASTSource(node.left) + " = " + this.getASTSource(node.right);
return this.getASTSource(node.left) + " = " +
this.getASTSource(node.right);
default:
throw new Error("getASTSource unsupported node type: " + node.type);
}
@ -176,11 +179,13 @@ module.exports = {
* - {Boolean} writable
* If the global is writeable or not.
*/
convertWorkerExpressionToGlobals: function(node, isGlobal, repository, dirname) {
convertWorkerExpressionToGlobals: function(node, isGlobal, repository,
dirname) {
var getGlobalsForFile = require("./globals").getGlobalsForFile;
if (!modules) {
modules = require(path.join(repository, "tools", "lint", "eslint", "modules.json"));
modules = require(path.join(repository,
"tools", "lint", "eslint", "modules.json"));
}
let results = [];
@ -213,13 +218,13 @@ module.exports = {
convertExpressionToGlobals: function(node, isGlobal, repository) {
if (!modules) {
modules = require(path.join(repository, "tools", "lint", "eslint", "modules.json"));
modules = require(path.join(repository,
"tools", "lint", "eslint", "modules.json"));
}
try {
var source = this.getASTSource(node);
}
catch (e) {
} catch (e) {
return [];
}
@ -320,7 +325,7 @@ module.exports = {
sourceType: "script",
ecmaFeatures: {
experimentalObjectRestSpread: true,
globalReturn: true,
globalReturn: true
}
};
},
@ -378,9 +383,10 @@ module.exports = {
let filepath = this.cleanUpPath(scope.getFilename());
let dir = path.dirname(filepath);
let names = fs.readdirSync(dir)
.filter(name => name.startsWith("head") && name.endsWith(".js"))
.map(name => path.join(dir, name));
let names =
fs.readdirSync(dir)
.filter(name => name.startsWith("head") && name.endsWith(".js"))
.map(name => path.join(dir, name));
return names;
},
@ -412,7 +418,7 @@ module.exports = {
manifests.push({
file: path.join(dir, name),
manifest
})
});
} catch (e) {
}
}

Просмотреть файл

@ -17,11 +17,11 @@ module.exports = {
"chrome-worker": require("../lib/environments/chrome-worker.js"),
"frame-script": require("../lib/environments/frame-script.js"),
"places-overlay": require("../lib/environments/places-overlay.js"),
"simpletest": require("../lib/environments/simpletest.js"),
"simpletest": require("../lib/environments/simpletest.js")
},
processors: {
".xml": require("../lib/processors/xbl-bindings"),
".js": require("../lib/processors/self-hosted"),
".js": require("../lib/processors/self-hosted")
},
rules: {
"avoid-removeChild": require("../lib/rules/avoid-removeChild"),
@ -32,10 +32,13 @@ module.exports = {
"no-aArgs": require("../lib/rules/no-aArgs"),
"no-cpows-in-tests": require("../lib/rules/no-cpows-in-tests"),
"no-single-arg-cu-import": require("../lib/rules/no-single-arg-cu-import"),
"no-import-into-var-and-global": require("../lib/rules/no-import-into-var-and-global.js"),
"no-import-into-var-and-global":
require("../lib/rules/no-import-into-var-and-global.js"),
"no-useless-parameters": require("../lib/rules/no-useless-parameters"),
"no-useless-removeEventListener": require("../lib/rules/no-useless-removeEventListener"),
"reject-importGlobalProperties": require("../lib/rules/reject-importGlobalProperties"),
"no-useless-removeEventListener":
require("../lib/rules/no-useless-removeEventListener"),
"reject-importGlobalProperties":
require("../lib/rules/reject-importGlobalProperties"),
"reject-some-requires": require("../lib/rules/reject-some-requires"),
"use-ownerGlobal": require("../lib/rules/use-ownerGlobal"),
"var-only-at-top-level": require("../lib/rules/var-only-at-top-level")

Просмотреть файл

@ -41,4 +41,4 @@ module.exports = {
postprocess: function(messages, filename) {
return Array.prototype.concat.apply([], messages);
}
}
};

Просмотреть файл

@ -14,18 +14,19 @@ const NS_XBL = "http://www.mozilla.org/xbl";
let sax = require("sax");
// Converts sax's error message to something that eslint will understand
let errorRegex = /(.*)\nLine: (\d+)\nColumn: (\d+)\nChar: (.*)/
let errorRegex = /(.*)\nLine: (\d+)\nColumn: (\d+)\nChar: (.*)/;
function parseError(err) {
let matches = err.message.match(errorRegex);
if (!matches)
if (!matches) {
return null;
}
return {
fatal: true,
message: matches[1],
line: parseInt(matches[2]) + 1,
column: parseInt(matches[3])
}
};
}
let entityRegex = /&[\w][\w-\.]*;/g;
@ -44,8 +45,8 @@ function XMLParser(parser) {
local: "#document",
uri: null,
children: [],
comments: [],
}
comments: []
};
this._currentNode = this.document;
}
@ -64,7 +65,7 @@ XMLParser.prototype = {
textLine: this.parser.line,
textColumn: this.parser.column,
textEndLine: this.parser.line
}
};
for (let attr of Object.keys(tag.attributes)) {
if (tag.attributes[attr].uri == "") {
@ -102,7 +103,7 @@ XMLParser.prototype = {
onComment: function(text) {
this._currentNode.comments.push(text);
}
}
};
// -----------------------------------------------------------------------------
// Processor Definition
@ -129,7 +130,8 @@ function addSyntheticLine(line, linePos, addDisableLine) {
}
/**
* Adds generated lines from an XBL node to the script to be passed back to eslint.
* Adds generated lines from an XBL node to the script to be passed back to
* eslint.
*/
function addNodeLines(node, reindent) {
let lines = node.textContent.split("\n");
@ -158,12 +160,16 @@ function addNodeLines(node, reindent) {
let firstLine = lines.shift();
firstLine = " ".repeat(reindent * INDENT_LEVEL) + firstLine;
// ESLint counts columns starting at 1 rather than 0
lineMap[scriptLines.length] = { line: startLine, offset: reindent * INDENT_LEVEL - (startColumn - 1) };
lineMap[scriptLines.length] = {
line: startLine,
offset: reindent * INDENT_LEVEL - (startColumn - 1)
};
scriptLines.push(firstLine);
startLine++;
}
// Find the preceeding whitespace for all lines that aren't entirely whitespace
// Find the preceeding whitespace for all lines that aren't entirely
// whitespace.
let indents = lines.filter(s => s.trim().length > 0)
.map(s => s.length - s.trimLeft().length);
// Find the smallest indent level in use
@ -176,7 +182,10 @@ function addNodeLines(node, reindent) {
lineMap[scriptLines.length] = { line: startLine, offset: 0 };
} else {
line = " ".repeat(reindent * INDENT_LEVEL) + line.substring(minIndent);
lineMap[scriptLines.length] = { line: startLine, offset: reindent * INDENT_LEVEL - (minIndent - 1) };
lineMap[scriptLines.length] = {
line: startLine,
offset: reindent * INDENT_LEVEL - (minIndent - 1)
};
}
scriptLines.push(line);
@ -195,12 +204,12 @@ module.exports = {
// Unfortunately it also throws away the case of tagnames and attributes
let parser = sax.parser(false, {
lowercase: true,
xmlns: true,
xmlns: true
});
parser.onerror = function(err) {
xmlParseError = parseError(err);
}
};
let xp = new XMLParser(parser);
parser.write(text);
@ -231,7 +240,8 @@ module.exports = {
continue;
}
addSyntheticLine(indent(1) + `"${binding.attributes.id}": {`, binding.textLine);
addSyntheticLine(indent(1) +
`"${binding.attributes.id}": {`, binding.textLine);
for (let part of binding.children) {
if (part.namespace != NS_XBL) {
@ -260,8 +270,10 @@ module.exports = {
continue;
}
addSyntheticLine(indent(3) + `get ${item.attributes.name}() {`, item.textLine);
addSyntheticLine(indent(4) + `return (`, item.textLine);
addSyntheticLine(indent(3) +
`get ${item.attributes.name}() {`, item.textLine);
addSyntheticLine(indent(4) +
`return (`, item.textLine);
// Remove trailing semicolons, as we are adding our own
item.textContent = item.textContent.replace(/;(?=\s*$)/, "");
@ -280,14 +292,20 @@ module.exports = {
break;
}
case "method": {
// Methods become function declarations with the appropriate params
// Methods become function declarations with the appropriate
// params.
let params = item.children.filter(n => n.local == "parameter" && n.namespace == NS_XBL)
let params = item.children.filter(n => {
return n.local == "parameter" && n.namespace == NS_XBL;
})
.map(n => n.attributes.name)
.join(", ");
let body = item.children.filter(n => n.local == "body" && n.namespace == NS_XBL)[0];
let body = item.children.filter(n => {
return n.local == "body" && n.namespace == NS_XBL;
})[0];
addSyntheticLine(indent(3) + `${item.attributes.name}(${params}) {`, item.textLine);
addSyntheticLine(indent(3) +
`${item.attributes.name}(${params}) {`, item.textLine);
addNodeLines(body, 4);
addSyntheticLine(indent(3) + `},`, item.textEndLine);
break;
@ -300,9 +318,11 @@ module.exports = {
}
if (propdef.local == "setter") {
addSyntheticLine(indent(3) + `set ${item.attributes.name}(val) {`, propdef.textLine);
addSyntheticLine(indent(3) +
`set ${item.attributes.name}(val) {`, propdef.textLine);
} else if (propdef.local == "getter") {
addSyntheticLine(indent(3) + `get ${item.attributes.name}() {`, propdef.textLine);
addSyntheticLine(indent(3) +
`get ${item.attributes.name}() {`, propdef.textLine);
} else {
continue;
}
@ -312,7 +332,8 @@ module.exports = {
break;
}
case "handler": {
// Handlers become a function declaration with an `event` parameter
// Handlers become a function declaration with an `event`
// parameter.
addSyntheticLine(indent(3) + `function(event) {`, item.textLine);
addNodeLines(item, 4);
addSyntheticLine(indent(3) + `},`, item.textEndLine);
@ -323,7 +344,8 @@ module.exports = {
}
}
addSyntheticLine(indent(2) + (part.local == "implementation" ? `},` : `],`), part.textEndLine);
addSyntheticLine(indent(2) +
(part.local == "implementation" ? `},` : `],`), part.textEndLine);
}
addSyntheticLine(indent(1) + `},`, binding.textEndLine);
}

Просмотреть файл

@ -31,7 +31,7 @@ exports.runTest = function(ruleTester) {
invalidCode("elt.parentNode.removeChild(elt);"),
invalidCode("elt.parentNode.parentNode.removeChild(elt.parentNode);"),
invalidCode("$(e).parentNode.removeChild($(e));"),
invalidCode("$('e').parentNode.removeChild($('e'));"),
invalidCode("$('e').parentNode.removeChild($('e'));")
]
});
};

Просмотреть файл

@ -14,8 +14,10 @@ var rule = require("../lib/rules/balanced-listeners");
//------------------------------------------------------------------------------
function error(code, message) {
return {code: code,
errors: [{message: message, type: "Identifier"}]};
return {
code: code,
errors: [{message: message, type: "Identifier"}]
};
}
exports.runTest = function(ruleTester) {

Просмотреть файл

@ -33,7 +33,7 @@ exports.runTest = function(ruleTester) {
"elt.removeEventListener('click', handler);",
"elt.removeEventListener('click', handler, true);",
"window.getComputedStyle(elt);",
"window.getComputedStyle(elt, ':before');",
"window.getComputedStyle(elt, ':before');"
],
invalid: [
{
@ -82,11 +82,14 @@ exports.runTest = function(ruleTester) {
},
{
code: "elt.addEventListener('click', handler, false);",
errors: callError("addEventListener's third parameter can be omitted when it's false.")
errors: callError(
"addEventListener's third parameter can be omitted when it's false.")
},
{
code: "elt.removeEventListener('click', handler, false);",
errors: callError("removeEventListener's third parameter can be omitted when it's false.")
errors: callError(
"removeEventListener's third parameter can be omitted when it's" +
" false.")
},
{
code: "window.getComputedStyle(elt, null);",

Просмотреть файл

@ -55,7 +55,7 @@ exports.runTest = function(ruleTester) {
// Should not reject when there's 2 different variables
"elt.addEventListener(event1, function listener() {" +
" elt.removeEventListener(event2, listener);" +
"});",
"});"
],
invalid: [
invalidCode("elt.addEventListener('click', function listener() {" +
@ -76,7 +76,7 @@ exports.runTest = function(ruleTester) {
"});"),
invalidCode("elt.addEventListener(eventName, function listener() {" +
" elt.removeEventListener(eventName, listener);" +
"});"),
"});")
]
});
};

Просмотреть файл

@ -1,7 +1,7 @@
/* Any copyright is dedicated to the Public Domain.
* http://creativecommons.org/publicdomain/zero/1.0/ */
"use strict";
"use strict";
//------------------------------------------------------------------------------
// Requirements
@ -16,13 +16,13 @@ var rule = require("../lib/rules/no-import-into-var-and-global");
const ExpectedError = {
message: "Cu.import imports into variables and into global scope.",
type: "CallExpression"
}
};
exports.runTest = function(ruleTester) {
ruleTester.run("no-import-into-var-and-global", rule, {
valid: [
"var foo = Cu.import('fake', {});",
"var foo = Components.utils.import('fake', {});",
"var foo = Components.utils.import('fake', {});"
],
invalid: [{
code: "var foo = Cu.import('fake', this);",
@ -32,4 +32,4 @@ exports.runTest = function(ruleTester) {
errors: [ExpectedError]
}]
});
}
};

Просмотреть файл

@ -16,12 +16,12 @@ var rule = require("../lib/rules/no-single-arg-cu-import");
const ExpectedError = {
message: "Single argument Cu.import exposes new globals to all modules",
type: "CallExpression"
}
};
exports.runTest = function(ruleTester) {
ruleTester.run("no-single-arg-cu-import", rule, {
valid: [
"Cu.import('fake', {});",
"Cu.import('fake', {});"
],
invalid: [{
code: "Cu.import('fake');",

Просмотреть файл

@ -23,12 +23,13 @@ exports.runTest = function(ruleTester) {
valid: [
"aEvent.target.ownerGlobal;",
"this.DOMPointNode.ownerGlobal.getSelection();",
"windowToMessageManager(node.ownerGlobal);",
"windowToMessageManager(node.ownerGlobal);"
],
invalid: [
invalidCode("aEvent.target.ownerDocument.defaultView;"),
invalidCode("this.DOMPointNode.ownerDocument.defaultView.getSelection();"),
invalidCode("windowToMessageManager(node.ownerDocument.defaultView);"),
invalidCode(
"this.DOMPointNode.ownerDocument.defaultView.getSelection();"),
invalidCode("windowToMessageManager(node.ownerDocument.defaultView);")
]
});
};