Skip to content

Commit

Permalink
work on typing and linting errors
Browse files Browse the repository at this point in the history
  • Loading branch information
bckohan committed Jan 27, 2024
1 parent 06af219 commit 38dcaed
Show file tree
Hide file tree
Showing 5 changed files with 41 additions and 39 deletions.
6 changes: 3 additions & 3 deletions django_typer/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
from django.core.management.base import BaseCommand
from django.core.management.color import no_style
from django.utils.functional import lazy
from django.utils.translation import gettext_lazy as _
from django.utils.translation import gettext as _
from typer import Typer
from typer.core import TyperCommand as CoreTyperCommand
from typer.core import TyperGroup as CoreTyperGroup
Expand Down Expand Up @@ -87,7 +87,7 @@
# pass


def traceback_config():
def traceback_config() -> t.Union[bool, t.Dict[str, t.Any]]:
"""
Fetch the rich traceback installation parameters from our settings. By default
rich tracebacks are on with show_locals = True. If the config is set to False
Expand All @@ -99,7 +99,7 @@ def traceback_config():
cfg = getattr(settings, "DT_RICH_TRACEBACK_CONFIG", {"show_locals": True})
if cfg:
return {"show_locals": True, **cfg}
return cfg
return bool(cfg)


def get_command(
Expand Down
18 changes: 12 additions & 6 deletions django_typer/apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,25 @@
installation logic.
"""
import inspect
import typing as t
from types import ModuleType

from django.apps import AppConfig
from django.conf import settings
from django.core.checks import Warning, register
from django.utils.translation import gettext_lazy as _
from django.core.checks import CheckMessage
from django.core.checks import Warning as CheckWarning
from django.core.checks import register
from django.utils.translation import gettext as _

from django_typer import traceback_config

rich: t.Union[ModuleType, None] = None

try:
import rich

tb_config = traceback_config()
if isinstance(tb_config, dict) and not tb_config.get("no_install", False):
if rich and isinstance(tb_config, dict) and not tb_config.get("no_install", False):
# install rich tracebacks if we've been configured to do so (default)
rich.traceback.install(
**{
Expand All @@ -26,11 +32,11 @@
}
)
except ImportError:
rich = None
pass


@register("settings")
def check_traceback_config(app_configs, **kwargs):
def check_traceback_config(app_configs, **kwargs) -> t.List[CheckMessage]:
"""
A system check that validates that the traceback config is valid and
contains only the expected parameters.
Expand All @@ -47,7 +53,7 @@ def check_traceback_config(app_configs, **kwargs):
unexpected = set(tb_cfg.keys()) - expected
if unexpected:
warnings.append(
Warning(
CheckWarning(
"DT_RICH_TRACEBACK_CONFIG",
hint=_("Unexpected parameters encountered: {keys}.").format(
keys=", ".join(unexpected)
Expand Down
24 changes: 8 additions & 16 deletions django_typer/completers.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ class ModelObjectCompleter:
model_cls: t.Type[Model]
lookup_field: str = "id"
help_field: t.Optional[str] = None
query: QueryBuilder
query: MethodType
limit: t.Optional[int] = 50
case_insensitive: bool = True
distinct: bool = True
Expand All @@ -87,9 +87,9 @@ def default_query(
:raises TypeError: If there is a problem using the incomplete string as a
lookup given the field class.
"""
field = self.model_cls._meta.get_field(
field = self.model_cls._meta.get_field( # pylint: disable=protected-access
self.lookup_field
) # pylint: disable=protected-access
)
if issubclass(field.__class__, IntegerField):
return self.int_query(context, parameter, incomplete)
if issubclass(field.__class__, (CharField, TextField)):
Expand All @@ -100,9 +100,7 @@ def default_query(
return self.float_query(context, parameter, incomplete)
raise ValueError(f"Unsupported lookup field class: {field.__class__.__name__}")

def int_query( # pylint: disable=unused-argument
self, context: Context, parameter: Parameter, incomplete: str
) -> Q:
def int_query(self, context: Context, parameter: Parameter, incomplete: str) -> Q:
"""
The default completion query builder for integer fields. This method will
return a Q object that will match any value that starts with the incomplete
Expand All @@ -127,9 +125,7 @@ def int_query( # pylint: disable=unused-argument
)
return qry

def float_query( # pylint: disable=unused-argument
self, context: Context, parameter: Parameter, incomplete: str
) -> Q:
def float_query(self, context: Context, parameter: Parameter, incomplete: str) -> Q:
"""
The default completion query builder for float fields. This method will
return a Q object that will match any value that starts with the incomplete
Expand All @@ -152,9 +148,7 @@ def float_query( # pylint: disable=unused-argument
**{f"{self.lookup_field}__lt": upper}
)

def text_query( # pylint: disable=unused-argument
self, context: Context, parameter: Parameter, incomplete: str
) -> Q:
def text_query(self, context: Context, parameter: Parameter, incomplete: str) -> Q:
"""
The default completion query builder for text-based fields. This method will
return a Q object that will match any value that starts with the incomplete
Expand All @@ -169,9 +163,7 @@ def text_query( # pylint: disable=unused-argument
return Q(**{f"{self.lookup_field}__istartswith": incomplete})
return Q(**{f"{self.lookup_field}__startswith": incomplete})

def uuid_query( # pylint: disable=unused-argument
self, context: Context, parameter: Parameter, incomplete: str
) -> Q:
def uuid_query(self, context: Context, parameter: Parameter, incomplete: str) -> Q:
"""
The default completion query builder for UUID fields. This method will
return a Q object that will match any value that starts with the incomplete
Expand Down Expand Up @@ -265,7 +257,7 @@ def complete_app_label(ctx: Context, param: Parameter, incomplete: str):
:return: A list of matching app labels. Labels already present for the parameter
on the command line will be filtered out.
"""
present = [app.label for app in (ctx.params.get(param.name) or [])]
present = [app.label for app in (ctx.params.get(param.name or "") or [])]
return [
app.label
for app in apps.get_app_configs()
Expand Down
25 changes: 11 additions & 14 deletions django_typer/parsers.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from django.core.exceptions import ObjectDoesNotExist
from django.core.management import CommandError
from django.db.models import Model
from django.utils.translation import gettext_lazy as _
from django.utils.translation import gettext as _


class ModelObjectParser:
Expand Down Expand Up @@ -61,15 +61,12 @@ def __call__(self, value: t.Union[str, Model]) -> Model:
return self.model_cls.objects.get(**{self.lookup_field: value})
except self.model_cls.DoesNotExist as err:
if self.on_error:
self.on_error(self.model_cls, value, err)
else:
raise CommandError(
_(
'{model} "{value}" does not exist!'.format(
model=self.model_cls.__name__, value=value
)
)
return self.on_error(self.model_cls, value, err)
raise CommandError(
_('{model} "{value}" does not exist!').format(
model=self.model_cls.__name__, value=value
)
) from err


def parse_app_label(label: t.Union[str, AppConfig]):
Expand All @@ -85,14 +82,14 @@ def parse_app_label(label: t.Union[str, AppConfig]):
return label
try:
return apps.get_app_config(label)
except LookupError:
except LookupError as err:
label = label.lower()
for cfg in apps.get_app_configs():
if cfg.label.lower() == label:
return cfg
elif cfg.name.lower() == label:
if cfg.name.lower() == label:
return cfg

raise CommandError(
_("{label} does not match any installed app label.".format(label=label))
)
raise CommandError(
_("{label} does not match any installed app label.").format(label=label)
) from err
7 changes: 7 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,7 @@ DJANGO_SETTINGS_MODULE = "django_typer.tests.settings"
python_files = "tests.py"
norecursedirs = "*.egg .eggs dist build docs .tox .git __pycache__"


addopts = [
"--strict-markers",
"--cov=django_typer",
Expand Down Expand Up @@ -140,3 +141,9 @@ max-args=30

[tool.pylint.'MASTER']
ignore="tests"

[tool.pylint.'MESSAGES CONTROL']
disable = [
'R0903', # to few public methods - seriously?
'W0613', # unused argument - unavoidable in generic base interfaces
]

0 comments on commit 38dcaed

Please sign in to comment.