Skip to content

Commit

Permalink
lint stuff
Browse files Browse the repository at this point in the history
  • Loading branch information
JasonGrace2282 committed May 15, 2024
1 parent 637867c commit ecbc3cd
Show file tree
Hide file tree
Showing 17 changed files with 116 additions and 132 deletions.
4 changes: 4 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ defaults:
run:
shell: bash

env:
# testing on windows
PYTHONUTF=1

jobs:
format:
runs-on: ubuntu-latest
Expand Down
18 changes: 0 additions & 18 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -65,30 +65,12 @@ select = [
"UP",
]
ignore = [
# default arguments for timezone.now()
"B008",
# null=True on CharField/TextField
"DJ001",
# No __str__ method on Model
"DJ008",
# Django order of model methods
"DJ012",
# ambiguous variable name
"E741",
# branching
"PLR09",
# avoid magic numbers
"PLR2004",
# loop variables overwritten by assignment
"PLW2901",
# Use ternary operator (x if cond else y)
"RUF005",
# mutable class attrs annotated as typing.ClassVar
"RUF012",
# implicit Optional
"RUF013",
# use format specifiers instead of percent format
"UP031",
]

[tool.ruff.format]
Expand Down
20 changes: 10 additions & 10 deletions tin/apps/assignments/forms.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from __future__ import annotations

from logging import getLogger
from typing import Dict, Iterable, Tuple
from typing import Iterable

from django import forms
from django.conf import settings
Expand Down Expand Up @@ -33,20 +33,20 @@ def __init__(self, course, *args, **kwargs):
# prevent description from getting too big
self.fields["description"].widget.attrs.update({"id": "description"})

def get_sections(self) -> Iterable[Dict[str, str | Tuple[str, ...] | bool]]:
def get_sections(self) -> Iterable[dict[str, str | tuple[str, ...] | bool]]:
for section in self.Meta.sections:
if section["name"]:
# operate on copy so errors on refresh don't happen
section = section.copy()
section["fields"] = tuple(self[field] for field in section["fields"])
yield section
new_section = section.copy()
new_section["fields"] = tuple(self[field] for field in new_section["fields"])
yield new_section

def get_main_section(self) -> Dict[str, str | Tuple[str, ...]]:
def get_main_section(self) -> dict[str, str | tuple[str, ...]]:
for section in self.Meta.sections:
if section["name"] == "":
section = section.copy()
section["fields"] = tuple(self[field] for field in section["fields"])
return section
new_section = section.copy()
new_section["fields"] = tuple(self[field] for field in new_section["fields"])
return new_section
logger.error(f"Could not find main section for assignment {self}")
return {"fields": ()}

Expand Down Expand Up @@ -127,7 +127,7 @@ class Meta:
"filename": "Clarify which file students need to upload (including the file "
"extension). For Java assignments, this also sets the name of the "
"saved submission file.",
"markdown": "This allows adding images, code blocks, or hyperlinks to the assignment description.",
"markdown": "This allows adding images, code blocks, or hyperlinks to the assignment description.", # noqa: E501
"venv": "If set, Tin will run the student's code in this virtual environment.",
"grader_has_network_access": 'If unset, this effectively disables "Give submissions '
'internet access" below. If set, it increases the amount '
Expand Down
18 changes: 9 additions & 9 deletions tin/apps/assignments/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,9 +54,9 @@ def filter_editable(self, user):
def upload_grader_file_path(assignment, _): # pylint: disable=unused-argument
assert assignment.id is not None
if assignment.language == "P":
return "assignment-{}/grader.py".format(assignment.id)
return f"assignment-{assignment.id}/grader.py"
else:
return "assignment-{}/Grader.java".format(assignment.id)
return f"assignment-{assignment.id}/Grader.java"


class Assignment(models.Model):
Expand Down Expand Up @@ -169,7 +169,7 @@ def save_grader_file(self, grader_text: str) -> None:
stdout=subprocess.DEVNULL,
stderr=subprocess.PIPE,
encoding="utf-8",
universal_newlines=True,
text=True,
check=True,
)
except FileNotFoundError as e:
Expand Down Expand Up @@ -203,7 +203,7 @@ def list_files(self) -> List[Tuple[int, str, str, int, datetime.datetime]]:
def save_file(self, file_text: str, file_name: str) -> None:
self.make_assignment_dir()

fpath = os.path.join(settings.MEDIA_ROOT, "assignment-{}".format(self.id), file_name)
fpath = os.path.join(settings.MEDIA_ROOT, f"assignment-{self.id}", file_name)

os.makedirs(os.path.dirname(fpath), exist_ok=True)

Expand All @@ -220,7 +220,7 @@ def save_file(self, file_text: str, file_name: str) -> None:
stdout=subprocess.DEVNULL,
stderr=subprocess.PIPE,
encoding="utf-8",
universal_newlines=True,
text=True,
check=True,
)
except FileNotFoundError as e:
Expand Down Expand Up @@ -449,7 +449,7 @@ class MossResult(models.Model):
user_id = models.CharField(max_length=20)

date = models.DateTimeField(auto_now_add=True)
url = models.URLField(max_length=200, null=True, blank=True)
url = models.URLField(max_length=200, blank=True)
status = models.CharField(max_length=1024, default="", null=False, blank=True)

@property
Expand All @@ -476,7 +476,7 @@ def run_action(command: List[str]) -> str:
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
encoding="utf-8",
universal_newlines=True,
text=True,
)
except FileNotFoundError as e:
logger.error("File not found: %s", e)
Expand All @@ -492,8 +492,8 @@ class FileAction(models.Model):
courses = models.ManyToManyField(Course, related_name="file_actions")
command = models.CharField(max_length=1024)

match_type = models.CharField(max_length=1, choices=MATCH_TYPES, null=True, blank=True)
match_value = models.CharField(max_length=100, null=True, blank=True)
match_type = models.CharField(max_length=1, choices=MATCH_TYPES, blank=True)
match_value = models.CharField(max_length=100, blank=True)
case_sensitive_match = models.BooleanField(default=False)

is_sandboxed = models.BooleanField(default=True)
Expand Down
113 changes: 53 additions & 60 deletions tin/apps/assignments/views.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import csv
import datetime
import json
import logging
import os
import subprocess
Expand Down Expand Up @@ -105,13 +104,12 @@ def show_view(request, assignment_id):
Period.objects.filter(course=course), id=int(period)
)
student_list = active_period.students.all().order_by("last_name")
elif period == "all":
active_period = "all"
student_list = course.students.all().order_by("last_name")
else:
if period == "all":
active_period = "all"
student_list = course.students.all().order_by("last_name")
else:
active_period = "none"
student_list = []
active_period = "none"
student_list = []

for student in student_list:
period = student.periods.filter(course=assignment.course)
Expand Down Expand Up @@ -237,13 +235,12 @@ def edit_view(request, assignment_id):
if quiz_type == "-1":
if hasattr(assignment, "quiz"):
assignment.quiz.delete()
elif hasattr(assignment, "quiz"):
assignment.quiz.action = quiz_type
assignment.save()
assignment.quiz.save()
else:
if hasattr(assignment, "quiz"):
assignment.quiz.action = quiz_type
assignment.save()
assignment.quiz.save()
else:
Quiz.objects.create(assignment=assignment, action=quiz_type)
Quiz.objects.create(assignment=assignment, action=quiz_type)

return redirect("assignments:show", assignment.id)

Expand Down Expand Up @@ -533,44 +530,24 @@ def submit_view(request, assignment_id):
file_form = FileSubmissionForm(request.POST, request.FILES)
file_errors = (
"You have made too many submissions too quickly. You will be able to "
"re-submit in {}.".format(end_delta)
f"re-submit in {end_delta}."
)
else:
text_form = TextSubmissionForm(request.POST)
text_errors = (
"You have made too many submissions too quickly. You will be able to "
"re-submit in {}.".format(end_delta)
f"re-submit in {end_delta}."
)
else:
if request.FILES.get("file"):
if request.FILES["file"].size <= settings.SUBMISSION_SIZE_LIMIT:
file_form = FileSubmissionForm(request.POST, request.FILES)
if file_form.is_valid():
try:
submission_text = request.FILES["file"].read().decode()
except UnicodeDecodeError:
file_errors = "Please don't upload binary files."
else:
submission = Submission()
submission.assignment = assignment
submission.student = student
submission.save_file(submission_text)
submission.save()

assignment.check_rate_limit(student)

submission.create_backup_copy(submission_text)

run_submission.delay(submission.id)
return redirect("assignments:show", assignment.id)
else:
file_errors = "That file's too large. Are you sure it's a Python program?"
else:
text_form = TextSubmissionForm(request.POST)
if text_form.is_valid():
submission_text = text_form.cleaned_data["text"]
if len(submission_text) <= settings.SUBMISSION_SIZE_LIMIT:
submission = text_form.save(commit=False)
elif request.FILES.get("file"):
if request.FILES["file"].size <= settings.SUBMISSION_SIZE_LIMIT:
file_form = FileSubmissionForm(request.POST, request.FILES)
if file_form.is_valid():
try:
submission_text = request.FILES["file"].read().decode()
except UnicodeDecodeError:
file_errors = "Please don't upload binary files."
else:
submission = Submission()
submission.assignment = assignment
submission.student = student
submission.save_file(submission_text)
Expand All @@ -582,8 +559,27 @@ def submit_view(request, assignment_id):

run_submission.delay(submission.id)
return redirect("assignments:show", assignment.id)
else:
text_errors = "Submission too large"
else:
file_errors = "That file's too large. Are you sure it's a Python program?"
else:
text_form = TextSubmissionForm(request.POST)
if text_form.is_valid():
submission_text = text_form.cleaned_data["text"]
if len(submission_text) <= settings.SUBMISSION_SIZE_LIMIT:
submission = text_form.save(commit=False)
submission.assignment = assignment
submission.student = student
submission.save_file(submission_text)
submission.save()

assignment.check_rate_limit(student)

submission.create_backup_copy(submission_text)

run_submission.delay(submission.id)
return redirect("assignments:show", assignment.id)
else:
text_errors = "Submission too large"

return render(
request,
Expand Down Expand Up @@ -660,8 +656,7 @@ def quiz_view(request, assignment_id):
):
text_form = TextSubmissionForm(request.POST)
text_errors = (
"You may only have a maximum of {} submission{} running at the same "
"time".format(
"You may only have a maximum of {} submission{} running at the same " "time".format(
settings.CONCURRENT_USER_SUBMISSION_LIMIT,
"" if settings.CONCURRENT_USER_SUBMISSION_LIMIT == 1 else "s",
)
Expand All @@ -676,7 +671,7 @@ def quiz_view(request, assignment_id):
text_form = TextSubmissionForm(request.POST)
text_errors = (
"You have made too many submissions too quickly. You will be able to re-submit"
"in {}.".format(end_delta)
f"in {end_delta}."
)
else:
text_form = TextSubmissionForm(request.POST)
Expand Down Expand Up @@ -776,7 +771,7 @@ def scores_csv_view(request, assignment_id):

if period == "all":
students = course.students.all()
name = "assignment_{}_all_scores.csv".format(assignment.id)
name = f"assignment_{assignment.id}_all_scores.csv"
elif course.period_set.exists():
period_obj = get_object_or_404(Period.objects.filter(course=course), id=int(period))
students = period_obj.students.all()
Expand All @@ -787,7 +782,7 @@ def scores_csv_view(request, assignment_id):
raise http.Http404

response = http.HttpResponse(content_type="text/csv")
response["Content-Disposition"] = "attachment; filename={}".format(name)
response["Content-Disposition"] = f"attachment; filename={name}"

writer = csv.writer(response)
writer.writerow(["Name", "Username", "Period", "Raw Score", "Final Score", "Formatted Grade"])
Expand Down Expand Up @@ -829,7 +824,7 @@ def download_submissions_view(request, assignment_id):

if period == "all":
students = course.students.all()
name = "assignment_{}_all_submissions.zip".format(assignment.id)
name = f"assignment_{assignment.id}_all_submissions.zip"
elif course.period_set.exists():
period_obj = get_object_or_404(Period.objects.filter(course=course), id=int(period))
students = period_obj.students.all()
Expand All @@ -853,7 +848,7 @@ def download_submissions_view(request, assignment_id):
file_with_header = published_submission.file_text_with_header
zf.writestr(f"{student.username}.{extension}", file_with_header)
resp = http.HttpResponse(s.getvalue(), content_type="application/x-zip-compressed")
resp["Content-Disposition"] = "attachment; filename={}".format(name)
resp["Content-Disposition"] = f"attachment; filename={name}"
return resp


Expand Down Expand Up @@ -930,10 +925,8 @@ def download_log_view(request, assignment_id):
try:
res = subprocess.run(
args,
stdin=subprocess.DEVNULL,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True,
capture_output=True,
text=True,
check=True,
)
except FileNotFoundError as e:
Expand All @@ -943,8 +936,8 @@ def download_log_view(request, assignment_id):
data = res.stdout

response = http.HttpResponse(data, content_type="text/plain")
response["Content-Disposition"] = 'attachment; filename="{}-grader.log"'.format(
slugify(assignment.name)
response["Content-Disposition"] = (
f'attachment; filename="{slugify(assignment.name)}-grader.log"'
)

return response
Expand Down
2 changes: 1 addition & 1 deletion tin/apps/auth/oauth.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@


def get_username(strategy, details, *args, user=None, **kwargs):
result = social_get_username(strategy, details, user=user, *args, **kwargs)
result = social_get_username(strategy, details, *args, user=user, **kwargs)
# if not hasattr(user, 'social_user'):
# user.social_user
return result
Expand Down
2 changes: 1 addition & 1 deletion tin/apps/courses/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ def get_absolute_url(self):
return reverse("courses:show", args=[self.id])

def get_teacher_str(self):
return ", ".join((t.last_name for t in self.teacher.all()))
return ", ".join(t.last_name for t in self.teacher.all())

def is_student_in_course(self, user):
return user in self.students.all()
Expand Down
Loading

0 comments on commit ecbc3cd

Please sign in to comment.