Skip to content

Commit

Permalink
chore: fix common linting problems
Browse files Browse the repository at this point in the history
This also replaces f"{$1}" with str($1) to make
the Alan formatting CI happy
  • Loading branch information
JasonGrace2282 authored and alanzhu0 committed Jun 17, 2024
1 parent 3fd1236 commit 1d1ff53
Show file tree
Hide file tree
Showing 115 changed files with 480 additions and 512 deletions.
2 changes: 1 addition & 1 deletion Ion.egg-info/PKG-INFO
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ Intranet 3

*Version 3.0.0*

Intranet3 (Ion) is the next-generation Intranet platform for `TJHSST
Intranet3 (Ion) is the next-generation Intranet platform for `TJHSST
<https://tjhsst.fcps.edu/>`_. Using Python, Django, Redis, Postgres, and many other technologies, Ion was developed from the ground up to be simple, well-documented, and extensible.

Documentation (in RestructuredText format) is available inside the "docs" folder or at https://tjcsl.github.io/ion publicly on the web.
Expand Down
4 changes: 2 additions & 2 deletions Ion.egg-info/SOURCES.txt
Original file line number Diff line number Diff line change
Expand Up @@ -1024,7 +1024,7 @@ intranet/static/img/logos/touch/touch-icon76.png
intranet/static/img/patterns/brushed.png
intranet/static/img/patterns/brushed_@2X.png
intranet/static/img/patterns/concrete_seamless.png
intranet/static/img/patterns/confectionary.png
intranet/static/img/patterns/confectionery.png
intranet/static/img/patterns/contemporary_china.png
intranet/static/img/patterns/contemporary_china_2.png
intranet/static/img/patterns/cream_pixels.png
Expand All @@ -1051,7 +1051,7 @@ intranet/static/img/patterns/squared_metal_@2X.png
intranet/static/img/patterns/dark/brushed.png
intranet/static/img/patterns/dark/brushed_@2X.png
intranet/static/img/patterns/dark/concrete_seamless.png
intranet/static/img/patterns/dark/confectionary.png
intranet/static/img/patterns/dark/confectionery.png
intranet/static/img/patterns/dark/contemporary_china.png
intranet/static/img/patterns/dark/contemporary_china_2.png
intranet/static/img/patterns/dark/cream_pixels.png
Expand Down
2 changes: 1 addition & 1 deletion README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ Intranet 3

*Version 3.0.0*

Intranet3 (Ion) is the next-generation Intranet platform for `TJHSST
Intranet3 (Ion) is the next-generation Intranet platform for `TJHSST
<https://tjhsst.fcps.edu/>`_. Using Python, Django, Redis, Postgres, and many other technologies, Ion was developed from the ground up to be simple, well-documented, and extensible.

Documentation (in RestructuredText format) is available inside the "docs" folder or at https://tjcsl.github.io/ion publicly on the web.
Expand Down
12 changes: 6 additions & 6 deletions SETUP.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ The Git repository on the host computer is synced with ``~/intranet`` on the vir
## Set Up

1. Create your own fork of the [``tjcsl/ion`` repository](https://github.com/tjcsl/ion.git).
2. Clone the Ion repositiory from your Ion fork by running ``git clone git@github.com:<YOUR_GITHUB_USERNAME>/ion.git intranet``. Note: if your host machine is running Windows, please run ``git config core.autocrlf input`` before cloning to prevent line ending issues.
2. Clone the Ion repository from your Ion fork by running ``git clone git@github.com:<YOUR_GITHUB_USERNAME>/ion.git intranet``. Note: if your host machine is running Windows, please run ``git config core.autocrlf input`` before cloning to prevent line ending issues.
3. Run ``cd config/docker``
4. Run `docker compose build ` (or use `docker-compose build` if this doesn't work)
5. Run ``docker compose up``
Expand All @@ -35,7 +35,7 @@ Navigate to http://localhost:8080 in the web browser of your choice. You might h

### Interacting with the application:

If you need to run a Django command like ``makemigrations``, ``collectstatic`` or ``shell_plus``, run ``docker exec -it intranet bash`` in your terminal. That wlll give you a shell into the application container. You can also use this to run scripts like ``build_sources.sh``. If you need to view the output from or restart ``runserver``, run ``docker attach application``.
If you need to run a Django command like ``makemigrations``, ``collectstatic`` or ``shell_plus``, run ``docker exec -it intranet bash`` in your terminal. That will give you a shell into the application container. You can also use this to run scripts like ``build_sources.sh``. If you need to view the output from or restart ``runserver``, run ``docker attach application``.

### Attaching to logs

Expand All @@ -45,14 +45,14 @@ To view logs of a container, run `docker logs [CONTAINER NAME] -f`. For example,

## Prerequisites

- [Virtualbox](https://www.virtualbox.org/) is a virtualization service that allows the creation of virtual machines. Installation is OS-specific and instructions can be found [here](https://www.virtualbox.org/wiki/Downloads).
- [Virtualbox](https://www.virtualbox.org/) is a virtualization service that allows the creation of virtual machines. Installation is OS-specific and instructions can be found [here](https://www.virtualbox.org/wiki/Downloads).
- [Vagrant](https://www.vagrantup.com/) is a command line utility for managing and setting up virtual machines and environments. Installation is OS-specific and instructions can be found [here](https://developer.hashicorp.com/vagrant/downloads).
- [GitHub](https://github.com) is the version control system used by the CSL. Make sure that you have an account and an SSH key tied to that account that will allow you to push and pull code. Ensure you have an SSH key set up with GitHub by running ``ssh -T git@github.com``. You should be greeted by your username. If not, set up an SSH key with GitHub by following [these instructions](https://help.github.com/articles/generating-an-ssh-key/).

## Set Up

1. Create your own fork of the [``tjcsl/ion`` repository](https://github.com/tjcsl/ion.git).
2. Clone the Ion repositiory from your Ion fork by running ``git clone git@github.com:<YOUR_GITHUB_USERNAME>/ion.git intranet``. Note: if your host machine is running Windows, please run ``git config core.autocrlf input`` before cloning to prevent line ending issues.
2. Clone the Ion repository from your Ion fork by running ``git clone git@github.com:<YOUR_GITHUB_USERNAME>/ion.git intranet``. Note: if your host machine is running Windows, please run ``git config core.autocrlf input`` before cloning to prevent line ending issues.
3. In the ``config/vagrant`` directory, copy the file ``devconfig.json.sample`` to ``devconfig.json`` and edit the properties in ``devconfig.json`` as appropriate. Ensure ``ssh_key`` is set to the same SSH key registered with GitHub (e.g. ``id_rsa``).
4. Run ``vagrant plugin install vagrant-vbguest``. If you are on Windows, also run ``vagrant plugin install vagrant-winnfsd``.
5. Run ``vagrant up && vagrant reload`` and wait while the development environment is set up. If you are asked to select a network interface for bridging, enter the number corresponding to one that is active. To automatically select this interface in the future, set the "network_interface" key in ``devconfig.json`` to the name of the interface you selected (e.g. ``"en0: Wi-Fi (AirPort)"``). There may be repeated warnings similar to "``Remote connection disconnect`` and ``Warning: Connection aborted. Retrying...`` on the second ``vagrant up``. After several minutes they will stop.
Expand Down Expand Up @@ -100,11 +100,11 @@ When you want to close the VM environment, make sure you have exited out of the

## Changing Master Password

The master password for vagrant development enviornment is ``swordfish``.
The master password for vagrant development environment is ``swordfish``.

In non-Vagrant environments, you should set a master password different from the default. Ideally, this password should have many bits of entropy and should be randomly generated.

We use the secure Argon2 hashing algorithim to secure our master password. To set the master password, set ``MASTER_PASSWORD`` to the string output of the below script (after changing values as appropriate) in ``secret.py``. After changing this value, restart Ion.
We use the secure Argon2 hashing algorithm to secure our master password. To set the master password, set ``MASTER_PASSWORD`` to the string output of the below script (after changing values as appropriate) in ``secret.py``. After changing this value, restart Ion.

Currently, Ion requires that you use Argon2id to create the hash. You also must prepend ``argon2`` to the hash before putting it into ``secret.py``.

Expand Down
4 changes: 2 additions & 2 deletions config/docker/entrypoint.sh
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
#!/bin/sh

if [ ! -f "config/docker/first-run.log" ]; then
if [ ! -f "config/docker/first-run.log" ]; then
echo "# Log of first run, to run initial setup again, delete this file" > config/docker/first-run.log
/bin/sh config/docker/initial_setup.sh 2>&1 | tee -a config/docker/first-run.log
fi
Expand All @@ -11,7 +11,7 @@ export PYTHONUNBUFFERED=1 # Don't buffer Django output

# Wrap the run command in a loop so that it restarts if it crashes, e.g. due to a syntax error
while true
do
do
python3 manage.py run 0.0.0.0:8080 # Custom run command that skips system checks for performance
sleep 1
done
6 changes: 3 additions & 3 deletions config/docker/initial_setup.sh
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,10 @@ echo -e "${BLUE}${BOLD}Copying over secret.py...${CLEAR}"
cp -u config/docker/secret.py intranet/settings

echo -e "${BLUE}${BOLD}Collecting static...${CLEAR}"
python3 manage.py collectstatic --noinput
python3 manage.py collectstatic --noinput

echo -e "${BLUE}${BOLD}Running migrations...${CLEAR}"
python3 manage.py migrate
python3 manage.py migrate

echo -e "${BLUE}${BOLD}Copying over scripts...${CLEAR}"
cp config/scripts/*.py .
Expand All @@ -22,7 +22,7 @@ for year in "freshman" "sophomore" "junior" "senior"; do
python3 create_users.py -t student -nw -y $year -n student student1 student2 student3 student4 student5
python3 create_users.py -t admin -nw -y $year -n admin admin1 admin2 admin3 admin4 admin5
done
python3 create_users.py -nw -ny -t admin -n admin
python3 create_users.py -nw -ny -t admin -n admin
python3 create_users.py -t admin -c 10
python3 create_users.py -t student -c 100
python3 create_users.py -t teacher -c 20
Expand Down
2 changes: 1 addition & 1 deletion config/scripts/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ A set of scripts to generate somewhat realistic student data for the Ion develop
- To run manually and/or change data:

- Delete `config/docker/first-run.log`

- Then, either:
- Restart the container to load new data
- Or manually run `config/docker/initial_setup.sh`
Expand Down
6 changes: 3 additions & 3 deletions config/scripts/create_activities.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,9 @@ def generate_activities(args: argparse.Namespace) -> None:
if restriction == "senior":
activity.seniors_allowed = True

sponser = EighthSponsor.objects.get_or_create(user=random.choice(teachers))[0]
sponser.save()
activity.sponsors.set((sponser,))
sponsor = EighthSponsor.objects.get_or_create(user=random.choice(teachers))[0]
sponsor.save()
activity.sponsors.set((sponsor,))

room = EighthRoom.objects.get_or_create(name=f"Room {random.randint(1, 100)}")[0]
room.save()
Expand Down
2 changes: 1 addition & 1 deletion config/scripts/create_users.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ def generate_names(args: argparse.Namespace) -> "list[tuple[str]]":
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument(
"-n", "--names", nargs="+", default=[], help="Provide in format first_last, or as a username, ignores count if supplied, seperate with '_'"
"-n", "--names", nargs="+", default=[], help="Provide in format first_last, or as a username, ignores count if supplied, separate with '_'"
)
parser.add_argument("-c", "--count", type=int, default=10, help="Number of users to make, defaults to 10")
parser.add_argument("-t", "--type", type=str, required=True, choices=["student", "teacher", "admin"], help="type of user to make")
Expand Down
2 changes: 1 addition & 1 deletion docs/developing/eighth-models.rst
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ What follows is a brief list of the eighth models with a description of each. Mo
The ``add_user()`` method of this class is where all of the logic to sign a user up for an activity is. Be *very* careful when modifying it.

- ``EighthSignup``: Represents that a user is signed up for a particular ``EighthScheduledActivity`` during the block for which it is scheduled. Has ``ForeignKey``\s to the ``EighthScheduledActivity`` and the ``User`` objects. Also stores some information such as whether the user signed up after the deadline (assumed to be a pass), whether the user signed themselves up or was signed up by an eighth admin, the name and sponsor list of the activity they were signed up for previously (if applicable), whether they were absent, etc.

**Note**: Since Ion's launch, it has been plagued by duplicate ``EighthSignup``\s (``EighthSignup``\s for the same user during the same block) being created. There are multiple checks before the object is saved to make sure it is unique, and uniqueness is enforced on a per-user, per- ``EighthScheduledActivity`` basis at the model level, but the problem has continued. As of summer 2019, measures have been enacted that will hopefully minimize the occurrences of this issue in the future, as well as allow better diagnosing of the problem if it occurs again.

- ``EighthWaitlist``: Ion has all of the backend logic to implement waitlists for each activity, but it is not enabled in production (``settings.ENABLE_WAITLIST`` is ``False``). When the waitlist is enabled, an ``EighthWaitlist`` object represents that a user signed up for the waitlist for a particular ``EighthScheduledActivity`` at a particular time. The user's position in the waitlist is calculated dynamically by finding the number of users who signed up for the waitlist before them.
Expand Down
12 changes: 6 additions & 6 deletions docs/developing/requirements.rst
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ autobahn
-----------------
https://github.com/crossbario/autobahn-python

This package provides `WebSocket <http://tools.ietf.org/html/rfc6455>_` & `Web Appplication Messaging Protocol (WAMP) <http://wamp-proto.org/>_` support.
This package provides `WebSocket <http://tools.ietf.org/html/rfc6455>_` & `Web Application Messaging Protocol (WAMP) <http://wamp-proto.org/>_` support.

It provides WebSocket support for Ion.

Expand Down Expand Up @@ -141,7 +141,7 @@ django
------------------
https://github.com/django/django

Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design.
Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design.

It is used as our web framework.

Expand All @@ -153,7 +153,7 @@ https://github.com/Suor/django-cacheops

This package is a Django app that supports automatic or manual queryset caching into a Redis ORM cache.

It is used for queryset caching into a Redis databse.
It is used for queryset caching into a Redis database.

LICENSE: 3-clause BSD

Expand Down Expand Up @@ -259,7 +259,7 @@ django-redis-cache
---------------------
https://github.com/sebleier/django-redis-cache

This package provides the redis backend cache.
This package provides the redis backend cache.

FIXME: Needs more specific info

Expand Down Expand Up @@ -323,7 +323,7 @@ docutils
---------
https://sourceforge.net/p/docutils/code/HEAD/tree/trunk/docutils/

This package provides a modular system for processing documentation into useful formats, such as HTML, XML, and LaTeX.
This package provides a modular system for processing documentation into useful formats, such as HTML, XML, and LaTeX.

It is an optional dependency for admindocs and setuptools.

Expand All @@ -333,7 +333,7 @@ https://github.com/mathiasertl/fabric/

This package provides a basic suite of operations for executing local or remote shell commands (normally or via sudo) and uploading/downloading files, as well as auxiliary functionality such as prompting the running user for input, or aborting execution.

It is used to manage the Ion application in both developement and production (see ``fabfile.py``)
It is used to manage the Ion application in both development and production (see ``fabfile.py``)

NEEDSRELEASE

Expand Down
2 changes: 1 addition & 1 deletion intranet/apps/announcements/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ class AnnouncementUserMap(models.Model):
users_seen = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name="announcements_seen")

def __str__(self):
return "UserMap: {}".format(self.announcement.title)
return f"UserMap: {self.announcement.title}"


class Announcement(models.Model):
Expand Down
18 changes: 9 additions & 9 deletions intranet/apps/announcements/notifications.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ def request_announcement_email(request, form, obj):
teacher_ids = [teacher_ids]
teachers = get_user_model().objects.filter(id__in=teacher_ids)

subject = "News Post Confirmation Request from {}".format(request.user.full_name)
subject = f"News Post Confirmation Request from {request.user.full_name}"
emails = []
for teacher in teachers:
emails.append(teacher.tj_email)
Expand All @@ -56,7 +56,7 @@ def admin_request_announcement_email(request, form, obj):
"""

subject = "News Post Approval Needed ({})".format(obj.title)
subject = f"News Post Approval Needed ({obj.title})"
emails = [settings.APPROVAL_EMAIL]
base_url = request.build_absolute_uri(reverse("index"))
data = {
Expand All @@ -80,7 +80,7 @@ def announcement_approved_email(request, obj, req):
if not settings.PRODUCTION:
logger.debug("Not in production. Ignoring email for approved announcement.")
return
subject = "Announcement Approved: {}".format(obj.title)
subject = f"Announcement Approved: {obj.title}"
""" Email to teachers who approved. """
teachers = req.teachers_approved.all()

Expand All @@ -94,7 +94,7 @@ def announcement_approved_email(request, obj, req):
email_send_task.delay(
"announcements/emails/announcement_approved.txt", "announcements/emails/announcement_approved.html", data, subject, teacher_emails
)
messages.success(request, "Sent teacher approved email to {} users".format(len(teacher_emails)))
messages.success(request, f"Sent teacher approved email to {len(teacher_emails)} users")
""" Email to submitter. """
submitter = req.user
data = {"announcement": obj, "request": req, "info_link": url, "base_url": base_url, "role": "submitted"}
Expand All @@ -112,7 +112,7 @@ def announcement_posted_email(request, obj, send_all=False):
"""

if settings.EMAIL_ANNOUNCEMENTS:
subject = "Announcement: {}".format(obj.title)
subject = f"Announcement: {obj.title}"
if send_all:
users = (
get_user_model()
Expand Down Expand Up @@ -145,7 +145,7 @@ def announcement_posted_email(request, obj, send_all=False):
email_send_task.delay(
"announcements/emails/announcement_posted.txt", "announcements/emails/announcement_posted.html", data, subject, emails, bcc=True
)
messages.success(request, "Sent email to {} users".format(len(users_send)))
messages.success(request, f"Sent email to {len(users_send)} users")
else:
logger.info("Emailing announcements disabled")

Expand All @@ -159,9 +159,9 @@ def announcement_posted_twitter(request, obj):
content = re.sub("<[^>]*>", "", obj.content)
content = content.replace("&nbsp;", " ")
content_len = 139 - (len(title) + 2 + 3 + 3 + 22)
text = "{}: {}... - {}".format(title, content[:content_len], url)
text = f"{title}: {content[:content_len]}... - {url}"
else:
text = "{}... - {}".format(title[:110], url)
text = f"{title[:110]}... - {url}"
logger.info("Posting tweet: %s", text)

try:
Expand All @@ -174,7 +174,7 @@ def announcement_posted_twitter(request, obj):
capture_exception(e)
else:
if respobj and "id" in respobj:
messages.success(request, "Posted tweet: {}".format(text))
messages.success(request, f"Posted tweet: {text}")
messages.success(request, "https://twitter.com/tjintranet/status/{}".format(respobj["id"]))
else:
messages.error(request, resp)
Expand Down
4 changes: 2 additions & 2 deletions intranet/apps/announcements/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ def announcement_posted_hook(request, obj):
announcement_posted_email(request, obj)
except Exception as e:
logger.error("Exception when emailing announcement: %s", e)
messages.error(request, "Exception when emailing announcement: {}".format(e))
messages.error(request, f"Exception when emailing announcement: {e}")
raise e
else:
logger.debug("Announcement notify off")
Expand Down Expand Up @@ -308,7 +308,7 @@ def modify_announcement_view(request, announcement_id=None):
form = AnnouncementEditForm(request.POST, instance=announcement)
if form.is_valid():
obj = form.save()
if "update_added_date" in form.cleaned_data and form.cleaned_data["update_added_date"]:
if form.cleaned_data.get("update_added_date"):
obj.added = timezone.now()
if form.cleaned_data.get("notify_post_resend") or form.cleaned_data.get("notify_email_all_resend"):
obj.notify_post = form.cleaned_data["notify_post_resend"]
Expand Down
Loading

0 comments on commit 1d1ff53

Please sign in to comment.