Skip to content

Commit

Permalink
Merge pull request #1237 from hartwork/migrate-from-yapf-to-ruff-format
Browse files Browse the repository at this point in the history
Migrate from yapf to ruff format
  • Loading branch information
hartwork authored Oct 19, 2024
2 parents 07e1656 + d086e82 commit 2f3e043
Show file tree
Hide file tree
Showing 32 changed files with 609 additions and 545 deletions.
1 change: 1 addition & 0 deletions .dockerignore
Original file line number Diff line number Diff line change
Expand Up @@ -45,5 +45,6 @@
!*.py
!*.rst
!*.sh
!*.toml
!*.txt
!*.yml
9 changes: 0 additions & 9 deletions .flake8

This file was deleted.

2 changes: 0 additions & 2 deletions .isort.cfg

This file was deleted.

26 changes: 6 additions & 20 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -1,12 +1,6 @@
exclude: '^jawanndenn/static/3rdparty/'

repos:
- repo: https://github.com/asottile/pyupgrade
rev: v3.18.0
hooks:
- id: pyupgrade
args: ['--py39-plus']

- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v5.0.0
hooks:
Expand All @@ -16,23 +10,15 @@ repos:
- id: end-of-file-fixer
- id: trailing-whitespace

- repo: https://github.com/PyCQA/flake8
rev: 7.1.1
hooks:
- id: flake8
exclude: '^jawanndenn/migrations/'

- repo: https://github.com/pycqa/isort
rev: 5.13.2
hooks:
- id: isort

- repo: https://github.com/Lucas-C/pre-commit-hooks-markup
rev: v1.0.1
hooks:
- id: rst-linter

- repo: https://github.com/google/yapf
rev: v0.40.2
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.7.0
hooks:
- id: yapf
- id: ruff
args:
- --fix
- id: ruff-format
5 changes: 0 additions & 5 deletions .style.yapf

This file was deleted.

200 changes: 107 additions & 93 deletions jawanndenn/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,99 +17,109 @@

def _require_hash_randomization():
if not sys.flags.hash_randomization:
_log.info('Hash randomization found to be disabled.')
if os.environ.get('PYTHONHASHSEED') == 'random':
_log.error('Unexpected re-execution loop detected, shutting down.')
_log.info("Hash randomization found to be disabled.")
if os.environ.get("PYTHONHASHSEED") == "random":
_log.error("Unexpected re-execution loop detected, shutting down.")
sys.exit(1)

_log.info('Re-executing with hash randomization enabled...')
_log.info("Re-executing with hash randomization enabled...")
env = os.environ.copy()
env['PYTHONHASHSEED'] = 'random'
env["PYTHONHASHSEED"] = "random"
argv = [sys.executable] + sys.argv
os.execve(argv[0], argv, env)


def _generate_random_printable_django_secret_key():
alphabet = ''.join(b for b in string.printable
if b not in string.whitespace and b not in '\'\\')
alphabet = "".join(
b for b in string.printable if b not in string.whitespace and b not in "'\\"
)
# reduce number of retries while not introducing modulo bias
alphabet = ''.join(alphabet for _ in range(256 // len(alphabet)))
alphabet = "".join(alphabet for _ in range(256 // len(alphabet)))
chars = []
while len(chars) < 50:
index = ord(os.urandom(1))
if index >= len(alphabet): # detect and avoid modulo bias
continue
chars.append(alphabet[index])
return ''.join(chars)
return "".join(chars)


def _process_django_secret_key_file(filename):
secret_key_encoding = 'utf-8'
secret_key_encoding = "utf-8"
try:
with open(filename, encoding=secret_key_encoding) as f:
secret_key = f.read()
except FileNotFoundError:
secret_key = _generate_random_printable_django_secret_key()
with open(filename, 'w', encoding=secret_key_encoding) as f:
with open(filename, "w", encoding=secret_key_encoding) as f:
f.write(secret_key)
return secret_key


def _inner_main():
parser = argparse.ArgumentParser(prog='jawanndenn')
parser.add_argument('--debug',
action='store_true',
default=False,
help='Enable debug mode (default: disabled)')
parser.add_argument('--host',
default='127.0.0.1',
metavar='HOST',
help='Hostname or IP address to listen at'
' (default: %(default)s)')
parser.add_argument('--port',
default=8080,
type=int,
metavar='PORT',
help='Port to listen at (default: %(default)s)')
parser.add_argument('--url-prefix',
default='',
metavar='PATH',
help='Path to prepend to URLs'
' (default: "%(default)s")')
parser.add_argument('--database-sqlite3',
default='~/jawanndenn.sqlite3',
metavar='FILE',
help='File to write the database to'
' (default: %(default)s)')
parser.add_argument('--django-secret-key-file',
default='~/jawanndenn.secret_key',
metavar='FILE',
help='File to use for Django secret key data'
' (default: %(default)s)')

limits = parser.add_argument_group('limit configuration')
limits.add_argument('--max-polls',
type=int,
metavar='COUNT',
default=DEFAULT_MAX_POLLS,
help='Maximum number of polls total'
' (default: %(default)s)')
limits.add_argument('--max-votes-per-poll',
type=int,
metavar='COUNT',
default=DEFAULT_MAX_VOTES_PER_POLL,
help='Maximum number of votes per poll'
' (default: %(default)s)')

export_args = parser.add_argument_group('data import/export arguments')
export_args.add_argument('--dumpdata',
action='store_true',
help='Dump a JSON export of the database to '
'standard output, then quit.')
export_args.add_argument('--loaddata',
metavar='FILE.json',
help='Load a JSON export of the database from '
'FILE.json, then quit.')
parser = argparse.ArgumentParser(prog="jawanndenn")
parser.add_argument(
"--debug", action="store_true", default=False, help="Enable debug mode (default: disabled)"
)
parser.add_argument(
"--host",
default="127.0.0.1",
metavar="HOST",
help="Hostname or IP address to listen at" " (default: %(default)s)",
)
parser.add_argument(
"--port",
default=8080,
type=int,
metavar="PORT",
help="Port to listen at (default: %(default)s)",
)
parser.add_argument(
"--url-prefix",
default="",
metavar="PATH",
help="Path to prepend to URLs" ' (default: "%(default)s")',
)
parser.add_argument(
"--database-sqlite3",
default="~/jawanndenn.sqlite3",
metavar="FILE",
help="File to write the database to" " (default: %(default)s)",
)
parser.add_argument(
"--django-secret-key-file",
default="~/jawanndenn.secret_key",
metavar="FILE",
help="File to use for Django secret key data" " (default: %(default)s)",
)

limits = parser.add_argument_group("limit configuration")
limits.add_argument(
"--max-polls",
type=int,
metavar="COUNT",
default=DEFAULT_MAX_POLLS,
help="Maximum number of polls total" " (default: %(default)s)",
)
limits.add_argument(
"--max-votes-per-poll",
type=int,
metavar="COUNT",
default=DEFAULT_MAX_VOTES_PER_POLL,
help="Maximum number of votes per poll" " (default: %(default)s)",
)

export_args = parser.add_argument_group("data import/export arguments")
export_args.add_argument(
"--dumpdata",
action="store_true",
help="Dump a JSON export of the database to " "standard output, then quit.",
)
export_args.add_argument(
"--loaddata",
metavar="FILE.json",
help="Load a JSON export of the database from " "FILE.json, then quit.",
)

options = parser.parse_args()

Expand All @@ -118,45 +128,49 @@ def _inner_main():
if not options.dumpdata and not options.loaddata:
_require_hash_randomization()

secret_key = _process_django_secret_key_file(os.path.expanduser(
options.django_secret_key_file))
secret_key = _process_django_secret_key_file(
os.path.expanduser(options.django_secret_key_file)
)

# NOTE: These are read by the the Django settings module
os.environ['JAWANNDENN_ALLOWED_HOSTS'] = ','.join(
[options.host, '127.0.0.1', '0.0.0.0', 'localhost'])
os.environ['JAWANNDENN_DEBUG'] = str(options.debug)
os.environ['JAWANNDENN_MAX_POLLS'] = str(options.max_polls)
os.environ['JAWANNDENN_MAX_VOTES_PER_POLL'] = str(options.max_votes_per_poll)
os.environ['JAWANNDENN_SECRET_KEY'] = secret_key
os.environ['JAWANNDENN_SQLITE_FILE'] = os.path.expanduser(options.database_sqlite3)
os.environ['JAWANNDENN_URL_PREFIX'] = options.url_prefix

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'jawanndenn.settings')
os.environ["JAWANNDENN_ALLOWED_HOSTS"] = ",".join(
[options.host, "127.0.0.1", "0.0.0.0", "localhost"]
)
os.environ["JAWANNDENN_DEBUG"] = str(options.debug)
os.environ["JAWANNDENN_MAX_POLLS"] = str(options.max_polls)
os.environ["JAWANNDENN_MAX_VOTES_PER_POLL"] = str(options.max_votes_per_poll)
os.environ["JAWANNDENN_SECRET_KEY"] = secret_key
os.environ["JAWANNDENN_SQLITE_FILE"] = os.path.expanduser(options.database_sqlite3)
os.environ["JAWANNDENN_URL_PREFIX"] = options.url_prefix

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "jawanndenn.settings")

# Heavy imports are down here to keep --help fast
from django.core.management import execute_from_command_line

with patch('sys.stdout', sys.stderr):
execute_from_command_line(['./manage.py', 'migrate'])
with patch("sys.stdout", sys.stderr):
execute_from_command_line(["./manage.py", "migrate"])
print()

if options.dumpdata:
execute_from_command_line(['./manage.py', 'dumpdata'])
execute_from_command_line(["./manage.py", "dumpdata"])
elif options.loaddata:
print('Importing JSON dump'
' -- this may take a few seconds...', file=sys.stderr)
execute_from_command_line(['./manage.py', 'loaddata', os.path.abspath(options.loaddata)])
print("Importing JSON dump" " -- this may take a few seconds...", file=sys.stderr)
execute_from_command_line(["./manage.py", "loaddata", os.path.abspath(options.loaddata)])
else:
sys.exit(
subprocess.call([
'gunicorn',
'--name=jawanndenn',
f'--bind={options.host}:{options.port}',
'--workers=1', # due to use of sqlite3 storage
'--access-logfile=-',
'--logger-class=gunicorn_color.Logger',
'jawanndenn.wsgi',
]))
subprocess.call(
[
"gunicorn",
"--name=jawanndenn",
f"--bind={options.host}:{options.port}",
"--workers=1", # due to use of sqlite3 storage
"--access-logfile=-",
"--logger-class=gunicorn_color.Logger",
"jawanndenn.wsgi",
]
)
)


def main():
Expand All @@ -166,5 +180,5 @@ def main():
sys.exit(128 + signal.SIGINT)


if __name__ == '__main__':
if __name__ == "__main__":
main()
2 changes: 1 addition & 1 deletion jawanndenn/asgi.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,6 @@

from django.core.asgi import get_asgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'jawanndenn.settings')
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "jawanndenn.settings")

application = get_asgi_application()
4 changes: 2 additions & 2 deletions jawanndenn/management/commands/prune_expired_polls.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@


class Command(BaseCommand):
help = 'Deletes expired polls'
help = "Deletes expired polls"

def handle(self, *args, **options):
polls_deleted, _ = Poll.objects.expired().delete()
self.stdout.write(self.style.SUCCESS(f'{polls_deleted} poll(s) deleted'))
self.stdout.write(self.style.SUCCESS(f"{polls_deleted} poll(s) deleted"))
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@


class PruneExpiredPollsTest(TestCase):

def test_deletes_expired_polls_and_those_only(self):
expired_poll = PollFactory(expires_at=now())
not_yet_expired_poll = PollFactory(expires_at=now() + timedelta(minutes=1))
Expand All @@ -28,4 +27,4 @@ def test_deletes_expired_polls_and_those_only(self):
for poll in (not_yet_expired_poll, never_expiring_poll):
poll.refresh_from_db() # would raise DoesNotExist if deleted

self.assertIn('1 poll(s) deleted', stdout.getvalue())
self.assertIn("1 poll(s) deleted", stdout.getvalue())
Loading

0 comments on commit 2f3e043

Please sign in to comment.