Skip to content

Commit

Permalink
use mypy for type hints
Browse files Browse the repository at this point in the history
  • Loading branch information
Archmonger committed Dec 6, 2022
1 parent 70210db commit 7176d35
Show file tree
Hide file tree
Showing 36 changed files with 140 additions and 91 deletions.
7 changes: 4 additions & 3 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,11 @@
"python.linting.enabled": true,
"python.linting.flake8Enabled": true,
"python.linting.pylintEnabled": true,
"python.analysis.typeCheckingMode": "basic",
"python.linting.mypyEnabled": true,
"python.analysis.typeCheckingMode": "off",
"python.languageServer": "Pylance",
"python.formatting.provider": "black",
"python.sortImports.args": [
"isort.args": [
"--src=${workspaceFolder}"
],
"python.analysis.extraPaths": [
Expand All @@ -19,7 +20,7 @@
".venv",
"docs"
],
"terminal.integrated.scrollback": 20000,
"terminal.integrated.scrollback": 10000,
"git.autofetch": true,
"prettier.tabWidth": 4,
"prettier.useTabs": true,
Expand Down
2 changes: 1 addition & 1 deletion conreq/_core/app_loader/apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ def auto_import_all(self, app_config: AppConfig):
if module_name not in self.skip_module_names:
import_module(".".join([app_config.name, module_name]))
if is_pkg:
loader.find_module(module_name).load_module(module_name)
loader.find_module(module_name).load_module(module_name) # type: ignore
except Exception as exception:
if not fail_silently:
raise exception
6 changes: 3 additions & 3 deletions conreq/_core/app_store/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ def wrap(view):
def wrapper(*args, **kwargs):
return self.admin_site.admin_view(view)(*args, **kwargs)

wrapper.model_admin = self
setattr(wrapper, "model_admin", self)
return update_wrapper(wrapper, view)

return [
Expand Down Expand Up @@ -86,8 +86,8 @@ def make_draggable(self, obj):
% (obj.pk, url)
)

make_draggable.allow_tags = True
make_draggable.short_description = ""
setattr(make_draggable, "allow_tags", True)
setattr(make_draggable, "short_description", "")


# Register your models here.
Expand Down
22 changes: 15 additions & 7 deletions conreq/_core/app_store/components/__init__.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,22 @@
import asyncio
import random
from copy import copy
from typing import Iterable
from typing import Callable, Iterable, Union, cast

from django_idom.components import django_css
from django_idom.hooks import use_query
from idom import component, hooks
from idom.html import _, div, h4, i, p
from idom.types import ComponentType

from conreq._core.app_store.components.card import card
from conreq._core.app_store.components.nav import app_store_nav
from conreq._core.app_store.models import AppPackage, SpotlightCategory, Subcategory
from conreq._core.app_store.models import (
AppPackage,
Category,
SpotlightCategory,
Subcategory,
)
from conreq.types import HomepageStateContext

# TODO: Handle situations where there are no spotlight apps or categories
Expand All @@ -19,9 +25,11 @@
@component
def app_store():
state = hooks.use_context(HomepageStateContext)
tab, set_tab = hooks.use_state(None)
tab, set_tab = hooks.use_state(cast(Union[Callable, None], None))
nav_category_query = use_query(get_nav_categories)
nav_categories, set_nav_categories = hooks.use_state({})
nav_categories, set_nav_categories = hooks.use_state(
cast(dict[Category, list[Subcategory]], {})
)
loading_needed, set_loading_needed = hooks.use_state(True)

# Display loading animation until categories are loaded
Expand Down Expand Up @@ -94,7 +102,7 @@ def spotlight(
):
opacity, set_opacity = hooks.use_state(0)
apps_query = use_query(get_spotlight_apps, apps)
card_list, set_card_list = hooks.use_state([])
card_list, set_card_list = hooks.use_state(cast(list[ComponentType], []))

@hooks.use_effect(dependencies=[])
async def fade_in_animation():
Expand Down Expand Up @@ -157,8 +165,8 @@ def get_nav_categories():
return Subcategory.objects.select_related("category").order_by("name").all()


def subcategories_to_dict(query) -> dict[str, dict[str, str]]:
new_categories = {}
def subcategories_to_dict(query) -> dict[Category, list[Subcategory]]:
new_categories: dict[Category, list[Subcategory]] = {}
for subcategory in query:
new_categories.setdefault(subcategory.category, []).append(subcategory)
return new_categories
6 changes: 3 additions & 3 deletions conreq/_core/base/management/commands/preconfig_conreq.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,9 +95,9 @@ def setup_sqlite_database(path, name, uid, gid, no_perms, verbosity):
if not no_perms and (uid != -1 or gid != -1) and sys.platform == "linux":
# pylint: disable=no-member
print("[X] Applying permissions")
new_uid = uid or os.getuid()
new_gid = gid or os.getgid()
os.chown(path, new_uid, new_gid)
new_uid = uid or os.getuid() # type: ignore
new_gid = gid or os.getgid() # type: ignore
os.chown(path, new_uid, new_gid) # type: ignore

@staticmethod
def recursive_chown(path, uid, gid, verbosity):
Expand Down
4 changes: 2 additions & 2 deletions conreq/_core/base/management/commands/run_conreq.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ def _run_webserver(self):
from conreq._core.server_settings.models import WebserverSettings

# TODO: Add in Uvicorn's reverse proxy stuff
db_conf: WebserverSettings = WebserverSettings.get_solo() # type: ignore
db_conf: WebserverSettings = WebserverSettings.get_solo()
config_kwargs = {
"ssl_certfile": self._f_path(db_conf.ssl_certificate),
"ssl_keyfile": self._f_path(db_conf.ssl_key),
Expand All @@ -116,7 +116,7 @@ def _run_webserver(self):
port=self.port,
workers=settings.WEBSERVER_WORKERS,
log_config=UVICORN_LOGGING_CONFIG if debug else {"version": 1},
debug=debug,
log_level="debug" if debug else None,
server_header=False,
**config_kwargs,
)
Expand Down
2 changes: 1 addition & 1 deletion conreq/_core/base/management/commands/start_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ class Command(TemplateCommand):
help = "Creates a Conreq app structure within a package."

# pylint: disable=arguments-differ
def handle(self, app_name: str, **options):
def handle(self, app_name: str, **options): # type: ignore
package_name = options.get("package") or input(
"Name of the package this app will belong to: "
).replace(" ", "_")
Expand Down
21 changes: 12 additions & 9 deletions conreq/_core/base/management/commands/start_package.py
Original file line number Diff line number Diff line change
@@ -1,26 +1,29 @@
from pathlib import Path
from typing import Any

from django.conf import settings
from django.core.management.templates import TemplateCommand

PACKAGES_DIR = getattr(settings, "PACKAGES_DEV_DIR")
PACKAGE_TEMPLATE = getattr(settings, "PACKAGE_TEMPLATE")
PACKAGE_SLIM_TEMPLATE = getattr(settings, "PACKAGE_SLIM_TEMPLATE")
PACKAGES_DIR: Path = getattr(settings, "PACKAGES_DEV_DIR")
PACKAGE_TEMPLATE: Path = getattr(settings, "PACKAGE_TEMPLATE")
PACKAGE_SLIM_TEMPLATE: Path = getattr(settings, "PACKAGE_SLIM_TEMPLATE")


class Command(TemplateCommand):
help = "Creates a Conreq package structure with given name."

# pylint: disable=arguments-differ
def handle(self, package_name: str, **options: dict):
def handle(self, package_name: str, **options: dict[str, Any]): # type: ignore
name = package_name
app_or_project = "app"
target = str(PACKAGES_DIR / "")
options["template"] = str(
PACKAGE_SLIM_TEMPLATE if options.get("slim") else PACKAGE_TEMPLATE
)
options["extensions"] = ["py", "txt"]
options["files"] = []
options["package_name"] = package_name
options["verbose_name"] = package_name.replace("_", " ").title()
) # type: ignore
options["extensions"] = ["py", "txt"] # type: ignore
options["files"] = [] # type: ignore
options["package_name"] = package_name # type: ignore
options["verbose_name"] = package_name.replace("_", " ").title() # type: ignore
super().handle(app_or_project, name, target, **options)

def add_arguments(self, parser):
Expand Down
6 changes: 3 additions & 3 deletions conreq/_core/components.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,9 +55,9 @@ def _set_tab_state_copy(obj):
),
ul(
{"className": "tabbed-viewport-selector list-group"},
_subtabs(top_tabs), # type: ignore
_subtabs(tabs), # type: ignore
_subtabs(bottom_tabs), # type: ignore
_subtabs(top_tabs),
_subtabs(tabs),
_subtabs(bottom_tabs),
),
),
value=tab_state,
Expand Down
4 changes: 2 additions & 2 deletions conreq/_core/email/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ class EmailBackend(smtp.EmailBackend):
"""Email backend to be used for Django reverse compatibility."""

def configure(self, email_config: EmailSettings | None = None):
config: EmailSettings = email_config or EmailSettings.get_solo() # type: ignore
config: EmailSettings = email_config or EmailSettings.get_solo()
self.host = config.server
self.port = config.port
self.username = config.username
Expand All @@ -36,7 +36,7 @@ def configure(self, email_config: EmailSettings | None = None):
self.timeout = config.timeout

def send_messages(self, email_messages: Sequence[EmailMessage]) -> int:
config: EmailSettings = EmailSettings.get_solo() # type: ignore
config: EmailSettings = EmailSettings.get_solo()
if config.enabled:
self.configure(config)
return super().send_messages(email_messages)
Expand Down
2 changes: 1 addition & 1 deletion conreq/_core/email/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@


def get_from_name(email_config: EmailSettings | None = None):
config: EmailSettings = email_config or EmailSettings.get_solo() # type: ignore
config: EmailSettings = email_config or EmailSettings.get_solo()

return (
f"{config.sender_name} <{config.username}>"
Expand Down
8 changes: 4 additions & 4 deletions conreq/_core/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,14 +85,14 @@ class EnvFormMixin:
def save(self, commit: bool = True):
super_class = super()
saved = (
super().save(commit=commit) if getattr(super_class, "save", None) else None
super().save(commit=commit) if getattr(super_class, "save", None) else None # type: ignore
)
if not commit:
return saved

for name, field in self.base_fields.items():
for name, field in self.base_fields.items(): # type: ignore
if isinstance(field, EnvFieldMixin) and self._env_changed(name, field):
set_env(field.env_name or name, self.cleaned_data.get(name))
set_env(field.env_name or name, self.cleaned_data.get(name)) # type: ignore

return saved

Expand All @@ -101,5 +101,5 @@ def _env_changed(self, name, field):
initial or stored value."""
initial_value = str(field.initial)
current_value = get_env(field.env_name, default_value=initial_value)
new_value = str(self.cleaned_data.get(name, ""))
new_value = str(self.cleaned_data.get(name, "")) # type: ignore
return current_value != new_value
4 changes: 2 additions & 2 deletions conreq/_core/home/components/navbar.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ def _update_page_title():
span(NAVBAR_TOGGLER_ICON),
),
div(NAVBAR_BRAND), # TODO: Add logo support
django_js("conreq/navbar.js"), # type: ignore
django_js("conreq/navbar.js"),
script(f"if('{page_title}'){{document.title = '{page_title}'}}"),
)

Expand All @@ -49,4 +49,4 @@ def _get_page_title(state: HomepageState):


def _default_page_title():
return GeneralSettings.get_solo().server_name # type: ignore
return GeneralSettings.get_solo().server_name
16 changes: 7 additions & 9 deletions conreq/_core/home/components/sidebar.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ async def username_on_click(_):
sidebar_group(group, key=group.name)
for group in sidebar_tabs
if group not in USER_ADMIN_DEBUG
], # type: ignore
],
[ # User tabs
sidebar_group(
group,
Expand All @@ -132,7 +132,7 @@ async def username_on_click(_):
)
for group in sidebar_tabs
if group == "User"
], # type: ignore
],
[ # Admin tabs
sidebar_group(
group,
Expand All @@ -141,14 +141,14 @@ async def username_on_click(_):
)
for group in sidebar_tabs
if group == "Admin" and websocket.scope["user"].is_staff
], # type: ignore
],
[ # Debug tabs
sidebar_group(
group, top_tabs=config._homepage.debug_sidebar_tabs, key=group.name
)
for group in sidebar_tabs
if group == "Debug" and websocket.scope["user"].is_staff and DEBUG
], # type: ignore
],
),
)

Expand Down Expand Up @@ -237,11 +237,9 @@ def sidebar_group(
div(TABS_INDICATOR),
div(
TABS, # TODO: Change these keys to be database IDs
[sidebar_tab(tab, key=tab.name) for tab in _top_tabs], # type: ignore
[sidebar_tab(tab, key=tab.name) for tab in group.tabs], # type: ignore
[
sidebar_tab(tab, key=tab.name) for tab in _bottom_tabs
], # type: ignore
[sidebar_tab(tab, key=tab.name) for tab in _top_tabs],
[sidebar_tab(tab, key=tab.name) for tab in group.tabs],
[sidebar_tab(tab, key=tab.name) for tab in _bottom_tabs],
),
),
key=group_id,
Expand Down
2 changes: 1 addition & 1 deletion conreq/_core/home/components/viewport.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ def viewport():
base_attrs = {"className": "viewport-container"}

if not this_viewport:
return div(base_attrs | HIDDEN)
return div(base_attrs | HIDDEN) # type: ignore

return div(
viewport_attrs(
Expand Down
2 changes: 1 addition & 1 deletion conreq/_core/home/components/welcome.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ async def on_click(_):

return html.div(
{"className": "welcome"},
django_css("conreq/welcome.css"), # type: ignore
django_css("conreq/welcome.css"),
html.h1("Welcome to Conreq"),
html.p("Looks like you don't have any custom tabs yet."),
html.p("Head over to the App Store and install some!"),
Expand Down
11 changes: 8 additions & 3 deletions conreq/_core/initialization/views.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from django.contrib.auth import authenticate, login
from django.core.exceptions import ValidationError
from django.shortcuts import redirect, render

from conreq._core.initialization.forms import InitializationForm
Expand Down Expand Up @@ -41,9 +42,13 @@ def _display_initialization(form, request, initialization):
username = form.cleaned_data.get("username")
password = form.cleaned_data.get("password1")
user = authenticate(username=username, password=password)
user.is_staff = True
user.is_admin = True
user.is_superuser = True

if not user:
raise ValidationError("Failed to authenticate user")

setattr(user, "is_staff", True)
setattr(user, "is_admin", True)
setattr(user, "is_superuser", True)
user.save()
login(request, user)
initialization.initialized = True
Expand Down
2 changes: 1 addition & 1 deletion conreq/_core/password_reset/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
from django.contrib.auth import get_user_model, password_validation
from django.contrib.auth.forms import PasswordResetForm as _PasswordResetForm
from django.contrib.auth.forms import SetPasswordForm as _SetPasswordForm
from django.contrib.auth.forms import _unicode_ci_compare
from django.contrib.auth.forms import _unicode_ci_compare # type: ignore
from django.db.models import Q
from django.forms import CharField, TextInput
from django.utils.translation import gettext_lazy as _
Expand Down
2 changes: 1 addition & 1 deletion conreq/_core/pwa/apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,6 @@ class PwaConfig(AppConfig):
}
]

app_splash_screen = []
app_splash_screen: list[str] = []
app_dir = "auto"
app_lang = "en-US"
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# Generated by Django 4.1.3 on 2022-12-05 16:34

import conreq._core.sign_up.models
from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
("sign_up", "0007_invitecode_locked"),
]

operations = [
migrations.AlterField(
model_name="invitecode",
name="expires_at",
field=models.DateTimeField(default=conreq._core.sign_up.models._expiration),
),
]
Loading

0 comments on commit 7176d35

Please sign in to comment.