Remove variable shadowing

Refactor to remove all no-shadow warnings.
This commit is contained in:
Hornwitser committed 2020-10-23 21:22:45 +02:00
1 parent e5e82ba2fb
commit 00a1f6aea7
14 files changed
+87 -86

No files matched your search

+1 -1
View File
@@ -192,7 +192,7 @@ module.exports = {
"no-script-url": "error", "no-script-url": "error",
"no-self-compare": "error", "no-self-compare": "error",
"no-sequences": "error", "no-sequences": "error",
"no-shadow": "warn", "no-shadow": ["error", { "allow": ["yargs"] }],
"no-spaced-func": "error", "no-spaced-func": "error",
"no-sync": "error", "no-sync": "error",
"no-tabs": ["error", { "allowIndentationTabs": true }], "no-tabs": ["error", { "allowIndentationTabs": true }],
+1 -6
View File
@@ -443,12 +443,7 @@ class ConfigGroup {
} }
let prev = this._fields.get(name); let prev = this._fields.get(name);
let updated = {}; let updated = {...prev || {}};
if (prev !== null) {
for (let [key, value] of Object.entries(prev)) {
updated[key] = value;
}
}
updated[prop] = value; updated[prop] = value;
this._fields.set(name, updated); this._fields.set(name, updated);
+6 -6
View File
@@ -130,19 +130,19 @@ async function exportItems(server, modVersions, items) {
let pos = 0; let pos = 0;
let iconCache = new Map(); let iconCache = new Map();
async function loadIcon(path, iconSize, iconMipmaps) { async function loadIcon(iconPath, iconSize, iconMipmaps) {
let icon = iconCache.get(path); let icon = iconCache.get(iconPath);
if (icon === undefined) { if (icon === undefined) {
let fileContent = await loadFile(server, modVersions, path); let fileContent = await loadFile(server, modVersions, iconPath);
if (fileContent) { if (fileContent) {
icon = await Jimp.read(fileContent); icon = await Jimp.read(fileContent);
icon.crop(0, 0, iconSize, iconSize); icon.crop(0, 0, iconSize, iconSize);
iconCache.set(path, icon); iconCache.set(iconPath, icon);
} else { } else {
icon = null; icon = null;
console.log(`Warning: ${path} not found`); console.log(`Warning: ${iconPath} not found`);
} }
iconCache.set(path, icon); iconCache.set(iconPath, icon);
} }
return icon; return icon;
} }
+2 -2
View File
@@ -169,8 +169,8 @@ function reorderDependencies(modules) {
// the module depends on a module that satisfy any of these conditions. // the module depends on a module that satisfy any of these conditions.
let remaining = new Map(); let remaining = new Map();
for (let modules of hold.values()) { for (let heldModules of hold.values()) {
for (let module of modules) { for (let module of heldModules) {
remaining.set(module.name, module); remaining.set(module.name, module);
} }
} }
+4 -4
View File
@@ -371,8 +371,8 @@ class WebSocketClientConnector extends WebSocketBaseConnector {
this._sessionToken = data.session_token; this._sessionToken = data.session_token;
this._heartbeatInterval = data.heartbeat_interval; this._heartbeatInterval = data.heartbeat_interval;
this.startHeartbeat(); this.startHeartbeat();
for (let message of this._sendBuffer) { for (let bufferedMessage of this._sendBuffer) {
this._socket.send(JSON.stringify(message)); this._socket.send(JSON.stringify(bufferedMessage));
} }
this._startedReconnect = null; this._startedReconnect = null;
this._connected = true; this._connected = true;
@@ -384,8 +384,8 @@ class WebSocketClientConnector extends WebSocketBaseConnector {
this._heartbeatInterval = data.heartbeat_interval; this._heartbeatInterval = data.heartbeat_interval;
this.startHeartbeat(); this.startHeartbeat();
this._dropSendBufferSeq(data.last_seq); this._dropSendBufferSeq(data.last_seq);
for (let message of this._sendBuffer) { for (let bufferedMessage of this._sendBuffer) {
this._socket.send(JSON.stringify(message)); this._socket.send(JSON.stringify(bufferedMessage));
} }
this._startedReconnect = null; this._startedReconnect = null;
this._connected = true; this._connected = true;
+23 -23
View File
@@ -13,9 +13,9 @@ class Metric {
throw new Error(`Invalid name '${name}'`); throw new Error(`Invalid name '${name}'`);
} }
for (let name of labels) { for (let label of labels) {
if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(name)) { if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(label)) {
throw new Error(`Invalid label '${name}'`); throw new Error(`Invalid label '${label}'`);
} }
} }
@@ -106,16 +106,28 @@ function keyToLabels(key) {
return labels; return labels;
} }
function removeMatchingLabels(mapping, labels) {
for (let key of mapping.keys()) {
let candidate = keyToLabels(key);
let hasLabels = Object.entries(labels).every(([name, value]) => (
candidate.get(name) === value
));
if (hasLabels) {
mapping.delete(key);
}
}
}
class ValueCollector extends Collector { class ValueCollector extends Collector {
constructor(type, name, help, options, childClass) { constructor(type, name, help, options, childClass) {
let labels = []; let labels = [];
let register = true; let register = true;
let callback = null; let callback = null;
for (let [name, value] of Object.entries(options)) { for (let [key, value] of Object.entries(options)) {
if (name === "labels") { labels = value; } if (key === "labels") { labels = value; }
else if (name === "register") { register = value; } else if (key === "register") { register = value; }
else if (name === "callback") { callback = value; } else if (key === "callback") { callback = value; }
else { throw new Error(`Unrecognized option '${name}'`); } else { throw new Error(`Unrecognized option '${key}'`); }
} }
// Make sure we don't register to the default registry if metric throws. // Make sure we don't register to the default registry if metric throws.
@@ -164,18 +176,6 @@ class ValueCollector extends Collector {
throw new Error("labels cannot be empty"); throw new Error("labels cannot be empty");
} }
function removeMatchingLabels(mapping, labels) {
for (let key of mapping.keys()) {
let candidate = keyToLabels(key);
let hasLabels = Object.entries(labels).every(([name, value]) => (
candidate.get(name) === value
));
if (hasLabels) {
mapping.delete(key);
}
}
}
removeMatchingLabels(this._values, labels); removeMatchingLabels(this._values, labels);
removeMatchingLabels(this._children, labels); removeMatchingLabels(this._children, labels);
} }
@@ -341,11 +341,11 @@ async function* expositionLines(resultsIterator) {
} }
async function exposition(resultsIterator = defaultRegistry.collect()) { async function exposition(resultsIterator = defaultRegistry.collect()) {
let exposition = ""; let lines = "";
for await (let line of expositionLines(resultsIterator)) { for await (let line of expositionLines(resultsIterator)) {
exposition += line; lines += line;
} }
return exposition; return lines;
} }
// HTTP Content-Type for the exposition format that's implemented // HTTP Content-Type for the exposition format that's implemented
+5 -5
View File
@@ -64,11 +64,11 @@ function definePermission({ name, title, description, grantByDefault=false }) {
* @static * @static
*/ */
class Role { class Role {
constructor({ id, name, description, permissions }) { constructor(serializedRole) {
this.id = id; this.id = serializedRole.id;
this.name = name; this.name = serializedRole.name;
this.description = description; this.description = serializedRole.description;
this.permissions = new Set(permissions); this.permissions = new Set(serializedRole.permissions);
} }
serialize() { serialize() {
+7 -7
View File
@@ -38,7 +38,7 @@ let masterPlugins = new Map();
let pluginInfos = new Map(); let pluginInfos = new Map();
let stopAcceptingNewSessions = false; let stopAcceptingNewSessions = false;
let debugEvents = new events.EventEmitter(); let debugEvents = new events.EventEmitter();
let pluginList = {}; let loadedPlugins = {};
let devMiddleware; let devMiddleware;
// homebrew modules // homebrew modules
@@ -1290,7 +1290,7 @@ wss.on("connection", function (socket, req) {
// Start connection handshake. // Start connection handshake.
socket.send(JSON.stringify({ seq: null, type: "hello", data: { socket.send(JSON.stringify({ seq: null, type: "hello", data: {
version, version,
plugins: pluginList, plugins: loadedPlugins,
}})); }}));
function attachHandler() { function attachHandler() {
@@ -1444,20 +1444,20 @@ async function handleHandshake(message, socket, req, attachHandler) {
} }
// handle plugins on the master // handle plugins on the master
async function pluginManagement(pluginInfos) { async function pluginManagement() {
let startPluginLoad = Date.now(); let startPluginLoad = Date.now();
masterPlugins = await loadPlugins(pluginInfos); masterPlugins = await loadPlugins();
console.log("All plugins loaded in "+(Date.now() - startPluginLoad)+"ms"); console.log("All plugins loaded in "+(Date.now() - startPluginLoad)+"ms");
} }
async function loadPlugins(pluginInfos) { async function loadPlugins() {
let plugins = new Map(); let plugins = new Map();
for (let pluginInfo of pluginInfos) { for (let pluginInfo of pluginInfos) {
if (!masterConfig.group(pluginInfo.name).get("enabled")) { if (!masterConfig.group(pluginInfo.name).get("enabled")) {
continue; continue;
} }
pluginList[pluginInfo.name] = pluginInfo.version; loadedPlugins[pluginInfo.name] = pluginInfo.version;
let pluginLoadStarted = Date.now(); let pluginLoadStarted = Date.now();
let MasterPlugin = libPlugin.BaseMasterPlugin; let MasterPlugin = libPlugin.BaseMasterPlugin;
@@ -1747,7 +1747,7 @@ async function startServer() {
} }
// Load plugins // Load plugins
await pluginManagement(pluginInfos); await pluginManagement();
// Only start listening for connections after all plugins have loaded // Only start listening for connections after all plugins have loaded
if (httpPort) { if (httpPort) {
@@ -200,8 +200,10 @@ export class InstanceView extends Component {
this.getData(); this.getData();
}} }}
> >
{this.state.slaves.map(slave => <Option defaultValue={instance.assigned_slave} value={slave.id} key={slave.id}> {this.state.slaves.map(newSlave => <Option
{slave.name} defaultValue={instance.assigned_slave} value={newSlave.id} key={newSlave.id}
>
{newSlave.name}
</Option>)} </Option>)}
</Select> </Select>
} }
+14 -12
View File
@@ -900,12 +900,13 @@ class Slave extends libLink.Link {
this.updateInstances().catch((err) => { this.updateInstances().catch((err) => {
console.error("ERROR: Unexpected error updating instances"); console.error("ERROR: Unexpected error updating instances");
console.error(err); console.error(err);
this.shutdown().catch((err) => { return this.shutdown();
setBlocking(true);
console.error("ERROR: Unexpected error during shutdown"); }).catch((err) => {
console.error(err); setBlocking(true);
process.exit(1); console.error("ERROR: Unexpected error during shutdown");
}); console.error(err);
process.exit(1);
}); });
}); });
@@ -919,12 +920,13 @@ class Slave extends libLink.Link {
this.connector.connect().catch((err) => { this.connector.connect().catch((err) => {
console.error("ERROR: Unexpected error reconnecting to master"); console.error("ERROR: Unexpected error reconnecting to master");
console.error(err); console.error(err);
this.shutdown().catch((err) => { return this.shutdown();
setBlocking(true);
console.error("ERROR: Unexpected error during shutdown"); }).catch((err) => {
console.error(err); setBlocking(true);
process.exit(1); console.error("ERROR: Unexpected error during shutdown");
}); console.error(err);
process.exit(1);
}); });
} else { } else {
+15 -12
View File
@@ -249,8 +249,11 @@ describe("Integration of Clusterio", function() {
let args = "--description \"A temp role\" --permissions core.control.connect"; let args = "--description \"A temp role\" --permissions core.control.connect";
await execCtl(`role create temp ${args}`); await execCtl(`role create temp ${args}`);
let result = await libLink.messages.listRoles.send(getControl()); let result = await libLink.messages.listRoles.send(getControl());
let role = result.list.find(role => role.name === "temp"); let tempRole = result.list.find(role => role.name === "temp");
assert.deepEqual(role, { id: 5, name: "temp", description: "A temp role", permissions: ["core.control.connect"] }); assert.deepEqual(
tempRole,
{ id: 5, name: "temp", description: "A temp role", permissions: ["core.control.connect"] }
);
}); });
}); });
@@ -259,8 +262,8 @@ describe("Integration of Clusterio", function() {
let args = "--name new --description \"A new role\" --permissions"; let args = "--name new --description \"A new role\" --permissions";
await execCtl(`role edit temp ${args}`); await execCtl(`role edit temp ${args}`);
let result = await libLink.messages.listRoles.send(getControl()); let result = await libLink.messages.listRoles.send(getControl());
let role = result.list.find(role => role.name === "new"); let newRole = result.list.find(role => role.name === "new");
assert.deepEqual(role, { id: 5, name: "new", description: "A new role", permissions: [] }); assert.deepEqual(newRole, { id: 5, name: "new", description: "A new role", permissions: [] });
}); });
}); });
@@ -268,8 +271,8 @@ describe("Integration of Clusterio", function() {
it("should modify the given role", async function() { it("should modify the given role", async function() {
await execCtl("role delete new"); await execCtl("role delete new");
let result = await libLink.messages.listRoles.send(getControl()); let result = await libLink.messages.listRoles.send(getControl());
let role = result.list.find(role => role.name === "new"); let newRole = result.list.find(role => role.name === "new");
assert(!role, "Role was not deleted"); assert(!newRole, "Role was not deleted");
}); });
}); });
@@ -283,8 +286,8 @@ describe("Integration of Clusterio", function() {
it("should create the given user", async function() { it("should create the given user", async function() {
await execCtl("user create temp"); await execCtl("user create temp");
let result = await libLink.messages.listUsers.send(getControl()); let result = await libLink.messages.listUsers.send(getControl());
let user = result.list.find(user => user.name === "temp"); let tempUser = result.list.find(user => user.name === "temp");
assert(user, "user was not created"); assert(tempUser, "user was not created");
}); });
}); });
@@ -292,8 +295,8 @@ describe("Integration of Clusterio", function() {
it("should set the roles on the user", async function() { it("should set the roles on the user", async function() {
await execCtl("user set-roles temp Admin"); await execCtl("user set-roles temp Admin");
let result = await libLink.messages.listUsers.send(getControl()); let result = await libLink.messages.listUsers.send(getControl());
let user = result.list.find(user => user.name === "temp"); let tempUser = result.list.find(user => user.name === "temp");
assert.deepEqual(user.roles, [0]); assert.deepEqual(tempUser.roles, [0]);
}); });
}); });
@@ -301,8 +304,8 @@ describe("Integration of Clusterio", function() {
it("should delete the user", async function() { it("should delete the user", async function() {
await execCtl("user delete temp"); await execCtl("user delete temp");
let result = await libLink.messages.listUsers.send(getControl()); let result = await libLink.messages.listUsers.send(getControl());
let user = result.list.find(user => user.name === "temp"); let tempUser = result.list.find(user => user.name === "temp");
assert(!user, "user was note deleted"); assert(!tempUser, "user was note deleted");
}); });
}); });
}); });
+2 -2
View File
@@ -44,10 +44,10 @@ function slowTest(test) {
test.timeout(20000); test.timeout(20000);
} }
async function get(path) { async function get(urlPath) {
let res = await phin({ let res = await phin({
method: "GET", method: "GET",
url: `https://localhost:4443${path}`, url: `https://localhost:4443${urlPath}`,
core: { rejectUnauthorized: false }, core: { rejectUnauthorized: false },
}); });
if (res.statusCode !== 200) { if (res.statusCode !== 200) {
+3 -3
View File
@@ -415,14 +415,14 @@ describe("lib/config/classes", function() {
describe(".registerGroup()", function() { describe(".registerGroup()", function() {
it("should throw if the class is finalized", function() { it("should throw if the class is finalized", function() {
class TestConfig extends classes.Config { } class FinalizedConfig extends classes.Config { }
TestConfig.finalize(); FinalizedConfig.finalize();
class TestGroup extends classes.ConfigGroup { } class TestGroup extends classes.ConfigGroup { }
TestGroup.groupName = "test"; TestGroup.groupName = "test";
TestGroup.finalize(); TestGroup.finalize();
assert.throws( assert.throws(
() => TestConfig.registerGroup(TestGroup), () => FinalizedConfig.registerGroup(TestGroup),
new Error("Cannot register group on finalized config") new Error("Cannot register group on finalized config")
); );
}); });
-1
View File
@@ -2,7 +2,6 @@
const assert = require("assert").strict; const assert = require("assert").strict;
const fs = require("fs"); const fs = require("fs");
const path = require("path"); const path = require("path");
const stream = require("stream");
const libHash = require("@clusterio/lib/hash"); const libHash = require("@clusterio/lib/hash");