Skip to content

Commit

Permalink
Format project to adhere to PEP8 standards and best practices (Pycord…
Browse files Browse the repository at this point in the history
…-Development#896)

* initial re-pass of Black, Flynt, isort after rebase

* run Black, Flynt, isort again on latest `master`

* re-pep8 master

* apply code efficiency and readability improvements

i.e. most (but not all) of these: https://github.com/sourcery-ai/sourcery/wiki/Current-Refactorings

* pep88888

* pep8

* pep8
  • Loading branch information
krittick authored Feb 11, 2022
1 parent 5db5e16 commit 6c578c2
Show file tree
Hide file tree
Showing 128 changed files with 9,975 additions and 6,523 deletions.
20 changes: 11 additions & 9 deletions discord/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,18 +9,18 @@
"""

__title__ = 'discord'
__author__ = 'Pycord Development'
__license__ = 'MIT'
__copyright__ = 'Copyright 2015-2021 Rapptz & Copyright 2021-present Pycord Development'
__version__ = '2.0.0b4'
__title__ = "discord"
__author__ = "Pycord Development"
__license__ = "MIT"
__copyright__ = "Copyright 2015-2021 Rapptz & Copyright 2021-present Pycord Development"
__version__ = "2.0.0b4"

__path__ = __import__('pkgutil').extend_path(__path__, __name__)
__path__ = __import__("pkgutil").extend_path(__path__, __name__)

import logging
from typing import NamedTuple, Literal
from typing import Literal, NamedTuple

from . import utils, opus, abc, ui, sinks
from . import abc, opus, sinks, ui, utils
from .activity import *
from .appinfo import *
from .asset import *
Expand Down Expand Up @@ -74,6 +74,8 @@ class VersionInfo(NamedTuple):
serial: int


version_info: VersionInfo = VersionInfo(major=2, minor=0, micro=0, releaselevel='beta', serial=4)
version_info: VersionInfo = VersionInfo(
major=2, minor=0, micro=0, releaselevel="beta", serial=4
)

logging.getLogger(__name__).addHandler(logging.NullHandler())
207 changes: 140 additions & 67 deletions discord/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,36 +24,44 @@
"""

import argparse
import platform
import sys
from pathlib import Path

from typing import Tuple

import discord
import pkg_resources
import aiohttp
import platform
import pkg_resources

import discord


def show_version() -> None:
entries = []
entries = [
"- Python v{0.major}.{0.minor}.{0.micro}-{0.releaselevel}".format(
sys.version_info
)
]

entries.append('- Python v{0.major}.{0.minor}.{0.micro}-{0.releaselevel}'.format(sys.version_info))
version_info = discord.version_info
entries.append('- py-cord v{0.major}.{0.minor}.{0.micro}-{0.releaselevel}'.format(version_info))
if version_info.releaselevel != 'final':
pkg = pkg_resources.get_distribution('py-cord')
entries.append(
"- py-cord v{0.major}.{0.minor}.{0.micro}-{0.releaselevel}".format(version_info)
)
if version_info.releaselevel != "final":
pkg = pkg_resources.get_distribution("py-cord")
if pkg:
entries.append(f' - py-cord pkg_resources: v{pkg.version}')
entries.append(f" - py-cord pkg_resources: v{pkg.version}")

entries.append(f'- aiohttp v{aiohttp.__version__}')
entries.append(f"- aiohttp v{aiohttp.__version__}")
uname = platform.uname()
entries.append('- system info: {0.system} {0.release} {0.version}'.format(uname))
print('\n'.join(entries))
entries.append("- system info: {0.system} {0.release} {0.version}".format(uname))
print("\n".join(entries))


def core(parser, args) -> None:
if args.version:
show_version()


_bot_template = """#!/usr/bin/env python3
from discord.ext import commands
Expand Down Expand Up @@ -123,7 +131,7 @@ def setup(bot):
bot.add_cog({name}(bot))
'''

_cog_extras = '''
_cog_extras = """
def cog_unload(self):
# clean up logic goes here
pass
Expand Down Expand Up @@ -152,44 +160,68 @@ async def cog_after_invoke(self, ctx):
# called after a command is called here
pass
'''
"""


# certain file names and directory names are forbidden
# see: https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247%28v=vs.85%29.aspx
# although some of this doesn't apply to Linux, we might as well be consistent
_base_table = {
'<': '-',
'>': '-',
':': '-',
'"': '-',
"<": "-",
">": "-",
":": "-",
'"': "-",
# '/': '-', these are fine
# '\\': '-',
'|': '-',
'?': '-',
'*': '-',
"|": "-",
"?": "-",
"*": "-",
}

# NUL (0) and 1-31 are disallowed
_base_table.update((chr(i), None) for i in range(32))

_translation_table = str.maketrans(_base_table)


def to_path(parser, name, *, replace_spaces=False) -> Path:
if isinstance(name, Path):
return name

if sys.platform == 'win32':
forbidden = ('CON', 'PRN', 'AUX', 'NUL', 'COM1', 'COM2', 'COM3', 'COM4', 'COM5', 'COM6', 'COM7', \
'COM8', 'COM9', 'LPT1', 'LPT2', 'LPT3', 'LPT4', 'LPT5', 'LPT6', 'LPT7', 'LPT8', 'LPT9')
if sys.platform == "win32":
forbidden = (
"CON",
"PRN",
"AUX",
"NUL",
"COM1",
"COM2",
"COM3",
"COM4",
"COM5",
"COM6",
"COM7",
"COM8",
"COM9",
"LPT1",
"LPT2",
"LPT3",
"LPT4",
"LPT5",
"LPT6",
"LPT7",
"LPT8",
"LPT9",
)
if len(name) <= 4 and name.upper() in forbidden:
parser.error('invalid directory name given, use a different one')
parser.error("invalid directory name given, use a different one")

name = name.translate(_translation_table)
if replace_spaces:
name = name.replace(' ', '-')
name = name.replace(" ", "-")
return Path(name)


def newbot(parser, args) -> None:
new_directory = to_path(parser, args.directory) / to_path(parser, args.name)

Expand All @@ -198,106 +230,147 @@ def newbot(parser, args) -> None:
try:
new_directory.mkdir(exist_ok=True, parents=True)
except OSError as exc:
parser.error(f'could not create our bot directory ({exc})')
parser.error(f"could not create our bot directory ({exc})")

cogs = new_directory / 'cogs'
cogs = new_directory / "cogs"

try:
cogs.mkdir(exist_ok=True)
init = cogs / '__init__.py'
init = cogs / "__init__.py"
init.touch()
except OSError as exc:
print(f'warning: could not create cogs directory ({exc})')
print(f"warning: could not create cogs directory ({exc})")

try:
with open(str(new_directory / 'config.py'), 'w', encoding='utf-8') as fp:
with open(str(new_directory / "config.py"), "w", encoding="utf-8") as fp:
fp.write('token = "place your token here"\ncogs = []\n')
except OSError as exc:
parser.error(f'could not create config file ({exc})')
parser.error(f"could not create config file ({exc})")

try:
with open(str(new_directory / 'bot.py'), 'w', encoding='utf-8') as fp:
base = 'Bot' if not args.sharded else 'AutoShardedBot'
with open(str(new_directory / "bot.py"), "w", encoding="utf-8") as fp:
base = "Bot" if not args.sharded else "AutoShardedBot"
fp.write(_bot_template.format(base=base, prefix=args.prefix))
except OSError as exc:
parser.error(f'could not create bot file ({exc})')
parser.error(f"could not create bot file ({exc})")

if not args.no_git:
try:
with open(str(new_directory / '.gitignore'), 'w', encoding='utf-8') as fp:
with open(str(new_directory / ".gitignore"), "w", encoding="utf-8") as fp:
fp.write(_gitignore_template)
except OSError as exc:
print(f'warning: could not create .gitignore file ({exc})')
print(f"warning: could not create .gitignore file ({exc})")

print("successfully made bot at", new_directory)

print('successfully made bot at', new_directory)

def newcog(parser, args) -> None:
cog_dir = to_path(parser, args.directory)
try:
cog_dir.mkdir(exist_ok=True)
except OSError as exc:
print(f'warning: could not create cogs directory ({exc})')
print(f"warning: could not create cogs directory ({exc})")

directory = cog_dir / to_path(parser, args.name)
directory = directory.with_suffix('.py')
directory = directory.with_suffix(".py")
try:
with open(str(directory), 'w', encoding='utf-8') as fp:
attrs = ''
extra = _cog_extras if args.full else ''
with open(str(directory), "w", encoding="utf-8") as fp:
attrs = ""
extra = _cog_extras if args.full else ""
if args.class_name:
name = args.class_name
else:
name = str(directory.stem)
if '-' in name or '_' in name:
translation = str.maketrans('-_', ' ')
name = name.translate(translation).title().replace(' ', '')
if "-" in name or "_" in name:
translation = str.maketrans("-_", " ")
name = name.translate(translation).title().replace(" ", "")
else:
name = name.title()

if args.display_name:
attrs += f', name="{args.display_name}"'
if args.hide_commands:
attrs += ', command_attrs=dict(hidden=True)'
attrs += ", command_attrs=dict(hidden=True)"
fp.write(_cog_template.format(name=name, extra=extra, attrs=attrs))
except OSError as exc:
parser.error(f'could not create cog file ({exc})')
parser.error(f"could not create cog file ({exc})")
else:
print('successfully made cog at', directory)
print("successfully made cog at", directory)


def add_newbot_args(subparser: argparse._SubParsersAction) -> None:
parser = subparser.add_parser('newbot', help='creates a command bot project quickly')
parser = subparser.add_parser(
"newbot", help="creates a command bot project quickly"
)
parser.set_defaults(func=newbot)

parser.add_argument('name', help='the bot project name')
parser.add_argument('directory', help='the directory to place it in (default: .)', nargs='?', default=Path.cwd())
parser.add_argument('--prefix', help='the bot prefix (default: $)', default='$', metavar='<prefix>')
parser.add_argument('--sharded', help='whether to use AutoShardedBot', action='store_true')
parser.add_argument('--no-git', help='do not create a .gitignore file', action='store_true', dest='no_git')
parser.add_argument("name", help="the bot project name")
parser.add_argument(
"directory",
help="the directory to place it in (default: .)",
nargs="?",
default=Path.cwd(),
)
parser.add_argument(
"--prefix", help="the bot prefix (default: $)", default="$", metavar="<prefix>"
)
parser.add_argument(
"--sharded", help="whether to use AutoShardedBot", action="store_true"
)
parser.add_argument(
"--no-git",
help="do not create a .gitignore file",
action="store_true",
dest="no_git",
)


def add_newcog_args(subparser: argparse._SubParsersAction) -> None:
parser = subparser.add_parser('newcog', help='creates a new cog template quickly')
parser = subparser.add_parser("newcog", help="creates a new cog template quickly")
parser.set_defaults(func=newcog)

parser.add_argument('name', help='the cog name')
parser.add_argument('directory', help='the directory to place it in (default: cogs)', nargs='?', default=Path('cogs'))
parser.add_argument('--class-name', help='the class name of the cog (default: <name>)', dest='class_name')
parser.add_argument('--display-name', help='the cog name (default: <name>)')
parser.add_argument('--hide-commands', help='whether to hide all commands in the cog', action='store_true')
parser.add_argument('--full', help='add all special methods as well', action='store_true')
parser.add_argument("name", help="the cog name")
parser.add_argument(
"directory",
help="the directory to place it in (default: cogs)",
nargs="?",
default=Path("cogs"),
)
parser.add_argument(
"--class-name",
help="the class name of the cog (default: <name>)",
dest="class_name",
)
parser.add_argument("--display-name", help="the cog name (default: <name>)")
parser.add_argument(
"--hide-commands",
help="whether to hide all commands in the cog",
action="store_true",
)
parser.add_argument(
"--full", help="add all special methods as well", action="store_true"
)


def parse_args() -> Tuple[argparse.ArgumentParser, argparse.Namespace]:
parser = argparse.ArgumentParser(prog='discord', description='Tools for helping with Pycord')
parser.add_argument('-v', '--version', action='store_true', help='shows the library version')
parser = argparse.ArgumentParser(
prog="discord", description="Tools for helping with Pycord"
)
parser.add_argument(
"-v", "--version", action="store_true", help="shows the library version"
)
parser.set_defaults(func=core)

subparser = parser.add_subparsers(dest='subcommand', title='subcommands')
subparser = parser.add_subparsers(dest="subcommand", title="subcommands")
add_newbot_args(subparser)
add_newcog_args(subparser)
return parser, parser.parse_args()


def main() -> None:
parser, args = parse_args()
args.func(parser, args)

if __name__ == '__main__':

if __name__ == "__main__":
main()
Loading

0 comments on commit 6c578c2

Please sign in to comment.