Skip to content

Commit

Permalink
Use ruff for formatting and linting
Browse files Browse the repository at this point in the history
  • Loading branch information
tyilo committed Nov 20, 2023
1 parent db5c90a commit 5b2238c
Show file tree
Hide file tree
Showing 20 changed files with 59 additions and 89 deletions.
29 changes: 10 additions & 19 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -2,37 +2,28 @@
# See https://pre-commit.com/hooks.html for more hooks
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.4.0
rev: v4.5.0
hooks:
- id: mixed-line-ending
- id: trailing-whitespace
- id: end-of-file-fixer
- id: check-added-large-files

- repo: https://github.com/hadialqattan/pycln
rev: v2.2.1
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.1.6
hooks:
- id: pycln
args: [--config=pyproject.toml]

- repo: https://github.com/psf/black
rev: 23.7.0
hooks:
- id: black

- repo: https://github.com/PyCQA/isort
rev: 5.12.0
hooks:
- id: isort
- id: ruff
args: [--fix]
- id: ruff-format

- repo: https://github.com/pre-commit/mirrors-prettier
rev: v3.0.1
rev: v3.1.0
hooks:
- id: prettier
additional_dependencies:
- prettier@3.0.1
- prettier-plugin-svelte@3.0.3
- svelte@4.1.2
- prettier@3.1.0
- prettier-plugin-svelte@3.1.0
- svelte@4.2.7

- repo: https://github.com/Tyilo/pre-commit-django-migrations
rev: d3a23e91aeb76b3c6b0f934d734c0dca237840ae
Expand Down
7 changes: 3 additions & 4 deletions academy/asgi.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,14 @@
import os

import django

django.setup()

from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
from django.core.asgi import get_asgi_application

import chat.routing

django.setup()


os.environ.setdefault("DJANGO_SETTINGS_MODULE", "academy.settings.development")

application = ProtocolTypeRouter(
Expand Down
3 changes: 2 additions & 1 deletion academy/settings/development.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@

from django.db.backends.signals import connection_created

from .base import *
from .base import * # noqa: F403
from .base import TESTING, MIDDLEWARE

ALLOWED_HOSTS = ["*"]
DEBUG = True
Expand Down
2 changes: 1 addition & 1 deletion academy/settings/development_postgres.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from .development import *
from .development import * # noqa: F403

DATABASES = {
"default": {
Expand Down
3 changes: 2 additions & 1 deletion academy/settings/production.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from .base import *
from .base import * # noqa: F403
import os

DEBUG = False
ALLOWED_HOSTS = ["academy.beer"]
Expand Down
4 changes: 3 additions & 1 deletion games/achievements.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,9 @@ def has_achieved(user):

class StudyHardAchievement(Achievement):
name = "Study Hard"
description = f"Spend at least the amount of time corresponding to 2.5 ECTS in game (56 hours)"
description = (
"Spend at least the amount of time corresponding to 2.5 ECTS in game (56 hours)"
)
icon = "diploma"

def has_achieved(user):
Expand Down
6 changes: 3 additions & 3 deletions games/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,10 @@ def clean(self):
super().clean()
user1 = self.cleaned_data.get("user1")
user2 = self.cleaned_data.get("user2")
if user1 != None and user1 == user2:
if user1 is not None and user1 == user2:
raise forms.ValidationError("Please pick two different users.")

if user1 != None and user2 != None:
if user1 is not None and user2 is not None:
same_games = user1.games.filter(id__in=user2.games.all())
if same_games.exists():
raise forms.ValidationError(
Expand Down Expand Up @@ -130,7 +130,7 @@ def clean(self):
log = self.cleaned_data["game_log"]
try:
data = json.loads(log)
except:
except Exception:
raise forms.ValidationError("Invalid JSON")

try:
Expand Down
2 changes: 1 addition & 1 deletion games/management/commands/import_dump.py
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ def import_cards(self):
drawn_datetime = None
else:
if game.id not in card_delta:
assert game.start_datetime != None
assert game.start_datetime is not None
diff_start = drawn_datetime - game.start_datetime
seconds = diff_start.total_seconds()
hours = seconds / (60 * 60)
Expand Down
26 changes: 13 additions & 13 deletions games/management/commands/import_old_game.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,30 +65,30 @@ def handle(self, *args, **options):

first_parts = lines[0].split()
if len(first_parts) < 2:
raise CommandError(f"First line has fewer than 2 words")
raise CommandError("First line has fewer than 2 words")

name, start_timestamp, *ids = first_parts
if name != "startime":
raise CommandError(f"First line doesn't start with 'startime'")
raise CommandError("First line doesn't start with 'startime'")

if not (2 <= len(ids) <= 6):
raise CommandError(f"Not between 2 and 6 players")
raise CommandError("Not between 2 and 6 players")

if options["ignore_ids"]:
ids = ["0"] * len(ids)

try:
ids = [int(x) for x in ids]
except ValueError:
raise CommandError(f"Ids are not numeric")
raise CommandError("Ids are not numeric")

last_parts = lines[-1].split()
if len(last_parts) != 2:
raise CommandError(f"Not 2 words on last line")
raise CommandError("Not 2 words on last line")

name, end_timestamp = last_parts
if name != "endtime":
raise CommandError(f"Last line doesn't start with 'endtime'")
raise CommandError("Last line doesn't start with 'endtime'")

player_count = len(ids)
find_ids = options["ignore_ids"] or ids[0] == "0"
Expand All @@ -103,8 +103,8 @@ def handle(self, *args, **options):
i = 0
while len(ids) < player_count:
i += 1
l = lines[i]
parts = l.split()
line = lines[i]
parts = line.split()
if len(parts) == 6:
continue
elif len(parts) == 4:
Expand All @@ -116,7 +116,7 @@ def handle(self, *args, **options):
f"Couldn't find user with username {username}"
)
else:
raise CommandError(f"Unknown line with {len(parts)} words: {l}")
raise CommandError(f"Unknown line with {len(parts)} words: {line}")

users = []
for user_id in ids:
Expand All @@ -137,11 +137,11 @@ def handle(self, *args, **options):

last_card = None
card_index = 0
for l in lines[1:-1]:
parts = l.split()
for line in lines[1:-1]:
parts = line.split()
if len(parts) == 6:
if last_card is None or last_card.value != 14:
raise CommandError(f"Chuck without an ace before")
raise CommandError("Chuck without an ace before")

duration_ms = self.parse_duration(parts[4])
Chug.objects.create(card=last_card, duration_ms=duration_ms)
Expand All @@ -159,7 +159,7 @@ def handle(self, *args, **options):
)
card_index += 1
else:
raise CommandError(f"Unknown line with {len(parts)} words: {l}")
raise CommandError(f"Unknown line with {len(parts)} words: {line}")

expected_cards = player_count * 13
if game.cards.count() != expected_cards:
Expand Down
4 changes: 2 additions & 2 deletions games/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ def filter_season(qs, season, key=None, should_include_live=False):


def filter_player_count(qs, player_count, key=None):
if player_count == None:
if player_count is None:
return qs

if key:
Expand Down Expand Up @@ -611,7 +611,7 @@ def duration_str(self):
return "?"

duration = self.get_duration()
if duration == None:
if duration is None:
duration = timezone.now() - self.start_datetime

return datetime.timedelta(seconds=round(duration.total_seconds()))
Expand Down
8 changes: 4 additions & 4 deletions games/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -238,7 +238,7 @@ def check_field(field, default=None, new_value=DEFAULT):
ended = data["has_ended"]
dnf = data["dnf"]
completed = ended and not dnf
if not completed and data.get("description") != None:
if not completed and data.get("description") is not None:
raise serializers.ValidationError(
{"description": "Can't set description before game has ended"}
)
Expand Down Expand Up @@ -412,14 +412,14 @@ class Meta(GameSerializer.Meta):
player_stats = serializers.SerializerMethodField()

def get_player_stats(self, obj):
l = []
res = []
for stats in obj.get_player_stats():
for k, v in stats.items():
if isinstance(v, datetime.timedelta):
stats[k] = v.total_seconds() * 1000
l.append(stats)
res.append(stats)

return l
return res


class PlayerStatSerializer(serializers.ModelSerializer):
Expand Down
6 changes: 3 additions & 3 deletions games/shuffle_indices.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,10 @@ def generate_shuffle_indices_for_players(player_count, random_seed=None):
return generate_shuffle_indices(player_count * 13, random_seed)


def shuffle_with_indices(l, shuffle_indices):
n = len(l)
def shuffle_with_indices(lst, shuffle_indices):
n = len(lst)
assert len(shuffle_indices) + 1 == n

for i in range(n - 1, 0, -1):
j = shuffle_indices[n - 1 - i]
l[i], l[j] = l[j], l[i]
lst[i], lst[j] = lst[j], lst[i]
2 changes: 1 addition & 1 deletion games/tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,5 +85,5 @@ def send_webpush_notification(game_id):
payload=payload,
ttl=24 * 60 * 60,
)
except:
except Exception:
pass
2 changes: 1 addition & 1 deletion games/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ def format_float_sips_html(value, places):
def format_chug_duration(ms):
td = datetime.timedelta(milliseconds=ms)
s = str(td)
if not "." in s:
if "." not in s:
s += "."

a, b = s.split(".")
Expand Down
28 changes: 2 additions & 26 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,26 +1,2 @@
[tool.black]
target-version = ['py311']
exclude = '''
(
/(
\.eggs # exclude a few common directories in the
| \.git # root of the project
| \.hg
| \.mypy_cache
| \.tox
| \.venv
| _build
| buck-out
| build
| dist
| db_data
)/
)
'''

[tool.pycln]
all = true

[tool.isort]
profile = 'black'
[tool.ruff]
target-version = "py311"
4 changes: 2 additions & 2 deletions web/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,14 +57,14 @@ def clean_new_image_data_url(self):

try:
data = base64.b64decode(parts[1])
except:
except Exception:
raise forms.ValidationError("Invalid base64 data")

bytes_io = BytesIO(data)
try:
image = Image.open(bytes_io)
image.verify()
except:
except Exception:
raise forms.ValidationError("Invalid image")

bytes_io.seek(0)
Expand Down
4 changes: 2 additions & 2 deletions web/templatetags/base14.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,10 @@

@register.filter
def base14(value, places=None):
if value == None:
if value is None:
return None

if places != None:
if places is not None:
return format_float_sips_html(value, places)
else:
return format_sips_html(value)
2 changes: 1 addition & 1 deletion web/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ def setUp(self):
create_game(self)

def assert_can_render_pages(self):
r = self.client.get(f"/games/")
r = self.client.get("/games/")
self.assertEqual(r.status_code, 200)
r = self.client.get(f"/games/{self.game.id}/")
self.assertEqual(r.status_code, 200)
Expand Down
4 changes: 2 additions & 2 deletions web/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,13 +125,13 @@ def from_str(self, s):
return None

def to_str(self, value):
if value == None:
if value is None:
return "All games"

return f"{value} player games"

def to_query_str(self, value):
if value == None:
if value is None:
return None

return value
Expand Down
2 changes: 1 addition & 1 deletion web/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ def get_ranking_url(ranking, user, season):
return None

page = (rank - 1) // RANKING_PAGE_LIMIT + 1
return f"/ranking/?" + urlencode(
return "/ranking/?" + urlencode(
{"season": season.number, "type": ranking.key, "page": page}
)

Expand Down

0 comments on commit 5b2238c

Please sign in to comment.