Skip to content

Commit

Permalink
Applied many more eslint rules
Browse files Browse the repository at this point in the history
  • Loading branch information
Gawdl3y committed Aug 3, 2016
1 parent b6e079e commit c585755
Show file tree
Hide file tree
Showing 23 changed files with 200 additions and 82 deletions.
110 changes: 107 additions & 3 deletions .eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,69 @@
},
"extends": "eslint:recommended",
"rules": {
"no-extra-parens": ["warn", "all", {
"nestedBinaryExpressions": false
}],
"valid-jsdoc": "error",

"accessor-pairs": "warn",
"array-callback-return": "error",
"complexity": "warn",
"consistent-return": "error",
"curly": ["error", "multi-line", "consistent"],
"dot-location": ["error", "property"],
"dot-notation": "error",
"eqeqeq": "error",
"no-empty-function": "error",
"no-floating-decimal": "error",
"no-implied-eval": "error",
"no-invalid-this": "error",
"no-lone-blocks": "error",
"no-multi-spaces": "error",
"no-new-func": "error",
"no-new-wrappers": "error",
"no-new": "error",
"no-octal-escape": "error",
"no-return-assign": "error",
"no-self-compare": "error",
"no-sequences": "error",
"no-throw-literal": "error",
"no-unmodified-loop-condition": "error",
"no-unused-expressions": "error",
"no-useless-call": "error",
"no-useless-concat": "error",
"no-useless-escape": "error",
"no-void": "error",
"no-warning-comments": "warn",
"wrap-iife": "error",
"yoda": "error",

"no-label-var": "error",
"no-shadow": "error",
"no-undef-init": "error",

"callback-return": "error",
"handle-callback-err": "error",
"no-mixed-requires": "error",
"no-new-require": "error",
"no-path-concat": "error",
"no-process-env": "error",

"array-bracket-spacing": "error",
"block-spacing": "error",
"brace-style": ["error", "1tbs", { "allowSingleLine": true }],
"camelcase": "error",
"comma-dangle": "error",
"comma-spacing": "error",
"comma-style": "error",
"computed-property-spacing": "error",
"consistent-this": "error",
"eol-last": "error",
"func-names": "error",
"func-style": ["error", "declaration", { "allowArrowFunctions": true }],
"id-length": ["error", { "exceptions": ["i", "j", "a", "b"] }],
"indent": ["error", "tab", { "SwitchCase": 1 }],
"semi": ["error", "always"],
"key-spacing": "error",
"keyword-spacing": ["error", {
"overrides": {
"if": { "after": false },
Expand All @@ -17,7 +78,50 @@
"switch": { "after": false }
}
}],
"no-else-return": "off",
"no-console": "off"
"max-depth": "error",
"max-nested-callbacks": ["error", { "max": 4 }],
"max-statements-per-line": ["error", { "max": 2 }],
"new-cap": "error",
"newline-per-chained-call": ["error", { "ignoreChainWithDepth": 3 }],
"no-array-constructor": "error",
"no-bitwise": "warn",
"no-inline-comments": "error",
"no-lonely-if": "error",
"no-mixed-operators": "error",
"no-multiple-empty-lines": ["error", { "max": 2, "maxEOF": 1, "maxBOF": 0 }],
"no-new-object": "error",
"no-spaced-func": "error",
"no-trailing-spaces": "error",
"no-unneeded-ternary": "error",
"no-whitespace-before-property": "error",
"object-curly-newline": "error",
"object-curly-spacing": ["error", "always"],
"operator-assignment": "error",
"operator-linebreak": ["error", "before"],
"padded-blocks": ["error", "never"],
"quote-props": ["error", "as-needed"],
"quotes": ["error", "single", { "avoidEscape": true, "allowTemplateLiterals": true }],
"semi-spacing": "error",
"semi": "error",
"space-before-blocks": "error",
"space-before-function-paren": ["error", "never"],
"space-in-parens": "error",
"space-infix-ops": "error",
"space-unary-ops": "error",
"spaced-comment": "error",
"unicode-bom": "error",

"arrow-body-style": "error",
"arrow-spacing": "error",
"no-duplicate-imports": "error",
"no-useless-computed-key": "error",
"no-useless-constructor": "error",
"prefer-arrow-callback": "error",
"prefer-rest-params": "error",
"prefer-spread": "error",
"prefer-template": "error",
"rest-spread-spacing": "error",
"template-curly-spacing": "error",
"yield-star-spacing": "error"
}
}
18 changes: 9 additions & 9 deletions src/commands/characters/list.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
'use babel';
'use strict';

import { stripIndents } from 'common-tags';
import Character from '../../database/character';
import config from '../../config';
import paginate from '../../util/pagination';
Expand All @@ -26,19 +27,18 @@ export default {
const search = args.join(' ');
let characters = await Character.findInServer(message.server, search, false);
if(characters.length > 0) {
characters.sort((a, b) => a.name < b.name ? -1 : (a.name > b.name ? 1 : 0));
characters.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
const paginated = paginate(characters, page, Math.floor(config.paginationItems));
characters = paginated.items;
message.reply(stripIndents`
Character${search ? `s ${search.length === 1 ? 'that begin with' : 'that contain'} "${search}"` : ' list'}, ${paginated.pageText}:
let messageText = search ? (search.length === 1 ? 'Characters that begin with' : 'Characters that contain') + ' "' + search + '"' : 'Character list';
messageText += ', ' + paginated.pageText + ' (Use ';
if(paginated.maxPage > 1) messageText += usage.short('characters' + (search ? ' ' + search : '') + ' <page>') + ' to view a specific page, or ';
messageText += usage.short('character <name>') + ' to view information about a character):';
messageText += '\n\n' + characters.map(element => element.name).join('\n');
message.reply(messageText);
${characters.map(char => char.name).join('\n')}
${paginated.maxPage > 1 ? `\nUse ${usage.long(`characters ${search ? `${search} ` : ''}<page>`, message.server)} to view a specific page.` : ''}
Use ${usage.long('character <name>', message.server)} to view information about a character.
`);
} else {
const messageText = 'There are no characters ' + (search ? (search.length === 1 ? 'that begin with' : 'that contain') + ' "' + search + '".' : 'in the database.');
message.reply(messageText);
message.reply(`There are no characters ${search ? `${search.length === 1 ? 'that begin with' : 'that contain'} "${search}"` : 'in the database'}.`);
}
}
};
2 changes: 1 addition & 1 deletion src/commands/characters/view.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export default {
const characters = await Character.findInServer(message.server, args[0]);
if(characters.length === 1) {
const owner = message.client.users.get('id', characters[0].owner);
const ownerName = owner ? owner.name + '#' + owner.discriminator : 'Unknown';
const ownerName = owner ? `${owner.name}#${owner.discriminator}` : 'Unknown';
message.reply(`Character **${characters[0].name}** (created by ${ownerName}):\n${characters[0].info}`);
} else if(characters.length > 1) {
message.reply(disambiguation(characters, 'characters'));
Expand Down
4 changes: 2 additions & 2 deletions src/commands/dice/max.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@ export default {
try {
const maxRoll = new DiceExpression(args[0]).max();
message.reply(`The maximum possible roll is **${maxRoll}**.`);
} catch(e) {
logger.error(e);
} catch(err) {
logger.error(err);
message.reply('Invalid dice expression specified.');
return;
}
Expand Down
4 changes: 2 additions & 2 deletions src/commands/dice/min.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@ export default {
try {
const minRoll = new DiceExpression(args[0]).min();
message.reply(`The minimum possible roll is **${minRoll}**.`);
} catch(e) {
logger.error(e);
} catch(err) {
logger.error(err);
message.reply('Invalid dice expression specified.');
return;
}
Expand Down
8 changes: 4 additions & 4 deletions src/commands/dice/roll.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ export default {
const dice = new DiceExpression(matches[1]);

// Restrict the maximum dice count
const totalDice = dice.dice.reduce((prev, d) => prev + d.diceCount, 0);
const totalDice = dice.dice.reduce((prev, die) => prev + die.diceCount, 0);
if(totalDice > 1000) {
message.client.sendMessage(message, `${message.author} might hurt themselves by rolling that many dice at once!`);
return;
Expand All @@ -46,7 +46,7 @@ export default {
// Build the list of dice
let diceList = '';
if(totalDice <= 100 && (rollResult.diceRaw.length > 1 || (rollResult.diceRaw.length > 0 && rollResult.diceRaw[0].length > 1))) {
diceList = rollResult.diceRaw.map((r, i) => nbsp(r.length > 1 ? r.join(' + ') + ' = ' + rollResult.diceSums[i] : r[0])).join(', ');
diceList = rollResult.diceRaw.map((res, i) => nbsp(res.length > 1 ? `${res.join(' + ')} = ${rollResult.diceSums[i]}` : res[0])).join(', ');
}

if(matches[2]) {
Expand All @@ -68,8 +68,8 @@ export default {
const diceInfo = diceList ? ` (${diceList})` : '';
message.client.sendMessage(message, `${message.author} rolled **${rollResult.roll}**.${diceInfo}`);
}
} catch(e) {
logger.error(e);
} catch(err) {
logger.error(err);
message.client.sendMessage(message, `${message.author} specified an invalid dice expression.`);
return;
}
Expand Down
6 changes: 3 additions & 3 deletions src/commands/general/about.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,17 +18,17 @@ export default {
async run(message) {
const owner = message.client.users.get('id', config.owner);
const servers = message.client.servers.length.toLocaleString(), users = message.client.users.length.toLocaleString();
const serversLabel = servers != 1 ? 'servers' : 'server', usersLabel = users != 1 ? 'users' : 'user';
const serversLabel = servers !== 1 ? 'servers' : 'server', usersLabel = users !== 1 ? 'users' : 'user';
const uptime = process.uptime();
const days = Math.floor(uptime / 60 / 60 / 24), hours = Math.floor(uptime / 60 / 60 % 24), minutes = Math.floor(uptime / 60 % 60);
const daysLabel = days != 1 ? 'days' : 'day', hoursLabel = hours != 1 ? 'hours' : 'hour', minutesLabel = minutes != 1 ? 'minutes' : 'minute';
const daysLabel = days !== 1 ? 'days' : 'day', hoursLabel = hours !== 1 ? 'hours' : 'hour', minutesLabel = minutes !== 1 ? 'minutes' : 'minute';
const daysStr = `${days.toLocaleString()} ${daysLabel}`, hoursStr = `${hours.toLocaleString()} ${hoursLabel}`, minutesStr = `${minutes.toLocaleString()} ${minutesLabel}`;
message.client.sendMessage(message.author, stripIndents`
**RPBot** v${version} created by Schuyler Cebulskie (Gawdl3y).
Source code and information: https://github.com/Gawdl3y/discord-rpbot
This bot ${owner ? `is owned by ${owner.name}#${owner.discriminator}, and ` : ''}is serving ${users} ${usersLabel} across ${servers} ${serversLabel}.
It has been running without interruption for ${days > 0 ? `${daysStr} ` : '' }${hours > 0 ? `${hoursStr} ` : '' }${minutesStr}.
It has been running without interruption for ${days > 0 ? `${daysStr} ` : ''}${hours > 0 ? `${hoursStr} ` : ''}${minutesStr}.
${config.invite ? `For bot feedback/help, use this invite: ${config.invite}` : ''}
`);
if(message.server) message.reply('Sent a DM to you with information.');
Expand Down
6 changes: 3 additions & 3 deletions src/commands/general/eval.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,9 +45,9 @@ export default {
async run(msg, args) {
if(!args[0]) throw new CommandFormatError(this, msg.server);
try {
msg.reply(`Result: \`${util.inspect(eval(args[0]), {depth: 0})}\``);
} catch(e) {
msg.reply(`Error while evaluating: ${e}`);
msg.reply(`Result: \`${util.inspect(eval(args[0]), { depth: 0 })}\``);
} catch(err) {
msg.reply(`Error while evaluating: ${err}`);
}
}
};
6 changes: 3 additions & 3 deletions src/commands/general/help.js
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,9 @@ export default {
**Available commands in ${message.server ? `${message.server}` : 'this DM'} (use ${usage.short('help <command>')} for more info):**
${groups.filter(g => g.commands.some(c => c.isRunnable(message))).map(g => stripIndents`
__${g.name}__
${g.commands.filter(c => c.isRunnable(message)).map(c => `**${c.name}:** ${c.description}`).join('\n')}
${groups.filter(grp => grp.commands.some(cmd => cmd.isRunnable(message))).map(grp => stripIndents`
__${grp.name}__
${grp.commands.filter(cmd => cmd.isRunnable(message)).map(cmd => `**${cmd.name}:** ${cmd.description}`).join('\n')}
`).join('\n\n')}
`);
if(message.server) message.reply('Sent a DM to you with information.');
Expand Down
7 changes: 5 additions & 2 deletions src/commands/general/list-roles.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
'use babel';
'use strict';

import { stripIndents } from 'common-tags';
import * as permissions from '../../util/permissions';

export default {
Expand All @@ -16,7 +17,9 @@ export default {
},

async run(message) {
const roleList = message.server.roles.map(element => `${element.name} (ID: ${element.id})`).join('\n');
message.reply(`__**Server roles:**__\n${roleList}`);
message.reply(stripIndents`
__**Server roles:**__
${message.server.roles.map(element => `${element.name} (ID: ${element.id})`).join('\n')}
`);
}
};
18 changes: 9 additions & 9 deletions src/commands/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,24 +43,24 @@ export const commands = [
export default commands;

export const groups = [
{id: 'general', name: 'General', commands: []},
{id: 'dice', name: 'Dice', commands: []},
{id: 'characters', name: 'Characters', commands: []},
{id: 'mod-roles', name: 'Mod roles', commands: []}
{ id: 'general', name: 'General', commands: [] },
{ id: 'dice', name: 'Dice', commands: [] },
{ id: 'characters', name: 'Characters', commands: [] },
{ id: 'mod-roles', name: 'Mod roles', commands: [] }
];
for(const command of commands) groups.find(g => g.id === command.group).commands.push(command);
for(const command of commands) groups.find(grp => grp.id === command.group).commands.push(command);

export function findCommands(searchString = null, message = null) {
if(!searchString) return message ? commands.filter(c => c.isRunnable(message)) : commands;
if(!searchString) return message ? commands.filter(cmd => cmd.isRunnable(message)) : commands;

// Find all matches
const lowercaseSearch = searchString.toLowerCase();
const matchedCommands = commands.filter(c => c.name.includes(lowercaseSearch) || (c.aliases && c.aliases.some(a => a.includes(lowercaseSearch))));
const matchedCommands = commands.filter(cmd => cmd.name.includes(lowercaseSearch) || (cmd.aliases && cmd.aliases.some(ali => ali.includes(lowercaseSearch))));

// See if there's an exact match
for(const command of matchedCommands) {
if(command.name === lowercaseSearch || (command.aliases && command.aliases.some(a => a === lowercaseSearch))) return [command];
if(command.name === lowercaseSearch || (command.aliases && command.aliases.some(ali => ali === lowercaseSearch))) return [command];
}

return message ? matchedCommands.filter(c => c.isRunnable(message)) : matchedCommands;
return message ? matchedCommands.filter(cmd => cmd.isRunnable(message)) : matchedCommands;
}
6 changes: 5 additions & 1 deletion src/commands/mod-roles/list.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
'use babel';
'use strict';

import { stripIndents } from 'common-tags';
import ModRole from '../../database/mod-role';
import * as permissions from '../../util/permissions';

Expand All @@ -19,7 +20,10 @@ export default {
async run(message) {
const roles = ModRole.findInServer(message.server);
if(roles.length > 0) {
message.reply('__**Moderator roles:**__\n' + roles.map(role => `${role.name} (ID: ${role.id})`).join('\n'));
message.reply(stripIndents`
__**Moderator roles:**__
${roles.map(role => `${role.name} (ID: ${role.id})`).join('\n')}
`);
} else {
message.reply('There are no moderator roles.');
}
Expand Down
7 changes: 4 additions & 3 deletions src/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -162,12 +162,13 @@ const config = yargs
group: 'Special:',
normalize: true,
config: true,
configParser: (configFile) => {
configParser: configFile => {
const extension = path.extname(configFile).toLowerCase();
if(extension === '.json')
if(extension === '.json') {
return JSON.parse(fs.readFileSync(configFile));
else if(extension === '.yml' || extension === '.yaml')
} else if(extension === '.yml' || extension === '.yaml') {
return YAML.safeLoad(fs.readFileSync(configFile));
}
throw new Error('Unknown config file type.');
}
})
Expand Down
2 changes: 1 addition & 1 deletion src/database/character.js
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ export default class Character {
if(!server) throw new Error('A server must be specified.');
server = server.id ? server.id : server;
const findStmt = await db.prepare(searchString ? sqlFindByServerAndNameLike : sqlFindByServer);
const characters = await findStmt.all(server, searchString ? (searchString.length > 1 ? `%${searchString}%` : `${searchString}%`) : undefined);
const characters = await findStmt.all(server, searchString ? searchString.length > 1 ? `%${searchString}%` : `${searchString}%` : undefined);
findStmt.finalize();
for(const [index, character] of characters.entries()) characters[index] = new Character(character.server_id, character.user_id, character.name, character.info);
return searchExact ? search(characters, searchString, { searchInexact: false }) : characters;
Expand Down
3 changes: 2 additions & 1 deletion src/database/index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
'use babel';
'use strict';

import { join as pathJoin } from 'path';
import sqlite from 'sqlite';
import Character from './character';
import config from '../config';
Expand All @@ -12,7 +13,7 @@ export default db;
export async function init() {
logger.info('Initializing database...', { file: config.database, verbose: config.databaseVerbose });
await db.open(config.database, { verbose: config.databaseVerbose });
await db.migrate({ migrationsPath: __dirname + '/../../migrations' });
await db.migrate({ migrationsPath: pathJoin(__dirname, '../../migrations') });
await Promise.all([
Character.convertStorage()
]);
Expand Down
2 changes: 1 addition & 1 deletion src/database/mod-role.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ export default class ModRole {
if(!this.serversMap[server.id]) return [];

// Find all of the server's roles that match, and filter them to ones that are mod roles
const roles = search(server.roles, searchString, { searchExact: false }).filter(r => this.serversMap[server.id].includes(r.id));
const roles = search(server.roles, searchString, { searchExact: false }).filter(role => this.serversMap[server.id].includes(role.id));
return search(roles, searchString, { searchInexact: false });
}

Expand Down
Loading

0 comments on commit c585755

Please sign in to comment.