Skip to content

Commit

Permalink
Reformat to 90 columns per line.
Browse files Browse the repository at this point in the history
Current devices can easily print 100 columns in half the screen.
  • Loading branch information
Manuel Vázquez Acosta committed Jun 20, 2024
1 parent 397c4d2 commit ba0f3f5
Show file tree
Hide file tree
Showing 8 changed files with 45 additions and 107 deletions.
11 changes: 7 additions & 4 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ dev-dependencies = [
"djlint~=1.34.1",
"ipython~=8.22.1",
"basedpyright==1.12.2",
"ruff==0.4.5",
"ruff==0.4.9",
"whitenoise~=6.6.0",
"isort~=5.13.2",
"ipdb~=0.13.13",
Expand All @@ -60,11 +60,14 @@ dev-dependencies = [


[tool.ruff]
line-length = 80
line-length = 90
target-version = "py311"

[tool.ruff.format]
preview = true

[too.isort]
line-length = 80
line-length = 90
profile ="django"


Expand All @@ -79,7 +82,7 @@ exclude = [

[tool.isort]
profile = "black"
line_length = 80
line_length = 90

[tool.djlint]
# Here we ignore
Expand Down
59 changes: 16 additions & 43 deletions src/djhtmx/component.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,9 +131,7 @@ def __init__(
):
self.request = request
self.component_by_id: dict[str, PydanticComponent] = {}
self.component_by_name: dict[str, list[PydanticComponent]] = (
defaultdict(list)
)
self.component_by_name: dict[str, list[PydanticComponent]] = defaultdict(list)
self.states_by_id = states_by_id or {}
self.subscriptions_by_id = subscriptions_by_id or {}

Expand Down Expand Up @@ -180,9 +178,7 @@ def _listen_to_post_save(
**kwargs,
):
action = "created" if created else "updated"
self.signals.update(
get_model_subscriptions(instance, actions=(action,))
)
self.signals.update(get_model_subscriptions(instance, actions=(action,)))
self._listen_to_related(sender, instance, action=action)

def _listen_to_pre_delete(
Expand All @@ -191,9 +187,7 @@ def _listen_to_pre_delete(
instance: models.Model,
**kwargs,
):
self.signals.update(
get_model_subscriptions(instance, actions=("deleted",))
)
self.signals.update(get_model_subscriptions(instance, actions=("deleted",)))
self._listen_to_related(sender, instance, action="deleted")

def _listen_to_related(
Expand Down Expand Up @@ -221,12 +215,9 @@ def dispatch_signals(self, main_component_id: str):
for component_id, subscriptions in self.subscriptions_by_id.items():
if (
current_signals.intersection(subscriptions)
and (component := self.get_component_by_id(component_id))
is not None
and (component := self.get_component_by_id(component_id)) is not None
):
logger.debug(
" > MATCHED: %s (%s)", component.hx_name, subscriptions
)
logger.debug(" > MATCHED: %s (%s)", component.hx_name, subscriptions)
components_to_update.add(component.id)

current_events = events_queue.pop()
Expand Down Expand Up @@ -329,9 +320,7 @@ def render_html(
) -> SafeString:
is_oob = oob not in ("true", None)
html = [
format_html('<div hx-swap-oob="{oob}">', oob=oob)
if is_oob
else None,
format_html('<div hx-swap-oob="{oob}">', oob=oob) if is_oob else None,
component.controller.render_html(
component._get_template(template),
component._get_context()
Expand All @@ -347,9 +336,7 @@ def _patch_state_with_query_string(self, component_name, state):
if patchers := QS_MAP.get(component_name):
for patcher in patchers:
if patcher.shared:
state = state | patcher.get_shared_state_updates(
self.params
)
state = state | patcher.get_shared_state_updates(self.params)
elif ns := state.get(patcher.ns_attr_name, ""):
state = state | patcher.get_private_state_updates(
self.params,
Expand Down Expand Up @@ -384,22 +371,16 @@ def destroy(self):
self._destroyed = True

def append(self, target: str, component: type[PydanticComponent], **state):
self._oob.append(
(f"beforeend:{target}", self.build(component, **state))
)
self._oob.append((f"beforeend:{target}", self.build(component, **state)))

def prepend(self, target: str, component: type[PydanticComponent], **state):
self._oob.append(
(f"afterbegin:{target}", self.build(component, **state))
)
self._oob.append((f"afterbegin:{target}", self.build(component, **state)))

def after(self, target: str, component: type["PydanticComponent"], **state):
self._oob.append((f"afterend:{target}", self.build(component, **state)))

def before(self, target: str, component: type[PydanticComponent], **state):
self._oob.append(
(f"beforebegin:{target}", self.build(component, **state))
)
self._oob.append((f"beforebegin:{target}", self.build(component, **state)))

def update(self, component: type[PydanticComponent], **state):
self._oob.append(("true", self.build(component, **state)))
Expand Down Expand Up @@ -564,9 +545,7 @@ def __init_subclass__(cls, public=True):
setattr(
cls,
attr_name,
validate_call(config={"arbitrary_types_allowed": True})(
attr
),
validate_call(config={"arbitrary_types_allowed": True})(attr),
)

if public and (event_handler := getattr(cls, "_handle_event", None)):
Expand Down Expand Up @@ -623,9 +602,7 @@ def any_user(self) -> TUser | AnonymousUser:
else:
return user

def _get_template(
self, template: str | None = None
) -> t.Callable[..., SafeString]:
def _get_template(self, template: str | None = None) -> t.Callable[..., SafeString]:
return get_template(template or self._template_name)

def _get_context(self):
Expand Down Expand Up @@ -700,11 +677,9 @@ class Component:
_name = ...
_fields: tuple[str, ...]

_pydantic_config = ConfigDict(
{
"arbitrary_types_allowed": True,
}
)
_pydantic_config = ConfigDict({
"arbitrary_types_allowed": True,
})

def __init_subclass__(cls, name=None, public=True):
if public:
Expand All @@ -717,9 +692,7 @@ def __init_subclass__(cls, name=None, public=True):
for attr_name in dict(vars(cls)):
attr = getattr(cls, attr_name)
if attr_name == "__init__" or (
not attr_name.startswith("_")
and attr_name.islower()
and callable(attr)
not attr_name.startswith("_") and attr_name.islower() and callable(attr)
):
setattr(
cls,
Expand Down
14 changes: 5 additions & 9 deletions src/djhtmx/executor.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,7 @@ def __call__(self):
template = None
with ExitStack() as stack:
for patcher in component._get_query_patchers():
stack.enter_context(
patcher.tracking_query_string(repo, component)
)
stack.enter_context(patcher.tracking_query_string(repo, component))
template = handler(**handler_kwargs)

if isinstance(template, tuple):
Expand Down Expand Up @@ -62,12 +60,10 @@ def __call__(self):

if isinstance(template, str):
# if there was a partial response, send the state for update
response["HX-State"] = json.dumps(
{
"component_id": component.id,
"state": signer.sign(component.model_dump_json()),
}
)
response["HX-State"] = json.dumps({
"component_id": component.id,
"state": signer.sign(component.model_dump_json()),
})
if isinstance(target, str):
response["HX-Retarget"] = target

Expand Down
18 changes: 4 additions & 14 deletions src/djhtmx/introspection.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,20 +21,14 @@ class ModelRelatedField:
related_model_name: str


MODEL_RELATED_FIELDS: dict[
t.Type[models.Model], tuple[ModelRelatedField, ...]
] = {}
MODEL_RELATED_FIELDS: dict[t.Type[models.Model], tuple[ModelRelatedField, ...]] = {}


def Model(model: t.Type[models.Model]):
return t.Annotated[
model,
BeforeValidator(
lambda v: (
v
if isinstance(v, model)
else model.objects.filter(pk=v).first()
)
lambda v: (v if isinstance(v, model) else model.objects.filter(pk=v).first())
),
PlainSerializer(
func=lambda v: v.pk,
Expand Down Expand Up @@ -161,17 +155,13 @@ def _parse_obj(
field_name = fragment[: fragment.index("[")]
index = int(fragment[fragment.index("[") + 1 : -1])
arrays[field_name][index] = (
_parse_obj([(tail, value)], arrays[field_name][index])
if tail
else value
_parse_obj([(tail, value)], arrays[field_name][index]) if tail else value
)
else:
output[fragment] = _parse_obj([(tail, value)]) if tail else value

for field, items in arrays.items():
output[field] = [
v for _, v in sorted(items.items(), key=lambda kv: kv[0])
]
output[field] = [v for _, v in sorted(items.items(), key=lambda kv: kv[0])]
return output


Expand Down
16 changes: 4 additions & 12 deletions src/djhtmx/management/commands/htmx.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,13 +74,9 @@ def check_pydantic_components_shadowing():
for name, shadows in clashes.items():
shadows = delete_duplicates(shadows)
if shadows:
click.echo(
f"Pydantic Component {bold(name)} might be shadowed by:"
)
click.echo(f"Pydantic Component {bold(name)} might be shadowed by:")
for shadow in shadows:
click.echo(
f" - {bold(shadow.__module__)}.{bold(shadow.__name__)}"
)
click.echo(f" - {bold(shadow.__module__)}.{bold(shadow.__name__)}")

return bool(clashes)

Expand All @@ -101,12 +97,8 @@ def check_old_components_shadowing():
for name, shadows in clashes.items():
shadows = delete_duplicates(shadows)
if shadows:
click.echo(
f"Old-style component {bold(name)} might be shadowed by:"
)
click.echo(f"Old-style component {bold(name)} might be shadowed by:")
for shadow in shadows:
click.echo(
f" - {bold(shadow.__module__)}.{bold(shadow.__name__)}"
)
click.echo(f" - {bold(shadow.__module__)}.{bold(shadow.__name__)}")

return bool(clashes)
17 changes: 4 additions & 13 deletions src/djhtmx/query.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,9 +99,7 @@ def tracking_query_string(self, repository, component):
if previous != after:
if self.shared:
self._set_shared_value(repository.params, after)
elif ns := getattr(
component, self.ns_attr_name, component.hx_name_scrambled
):
elif ns := getattr(component, self.ns_attr_name, component.hx_name_scrambled):
self._set_private_value(repository.params, after, ns)
repository.signals.add(self.subscription_channel)

Expand All @@ -126,9 +124,7 @@ def _from_field_info(
def _maybe_extract_optional(ann):
# Possibly extract t.Optional[sequence_type]
if t.get_origin(ann) is types.UnionType:
args = [
arg for arg in t.get_args(ann) if ann is not types.NoneType
]
args = [arg for arg in t.get_args(ann) if ann is not types.NoneType]
if len(args) == 1:
return args[0]
return ann
Expand Down Expand Up @@ -167,9 +163,7 @@ def _get_value_extractor(ann):
elif _is_seq_of_simple_types(ann):
getter = QueryDict.getlist
else:
raise TypeError(
f"Invalid type annotation {ann} for a query string"
)
raise TypeError(f"Invalid type annotation {ann} for a query string")

def result(qd, suffix):
if suffix:
Expand Down Expand Up @@ -249,10 +243,7 @@ def _set_value(qdict: QueryDict, value, suffix: str = ""):
@classmethod
def for_component(cls, component_cls):
def _field_has_default(f: FieldInfo):
return (
f.default is not PydanticUndefined
or f.default_factory is not None
)
return f.default is not PydanticUndefined or f.default_factory is not None

def _get_querystring_args(name, f: FieldInfo):
done = False
Expand Down
12 changes: 4 additions & 8 deletions src/djhtmx/templatetags/htmx.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,11 +109,9 @@ def hx_tag(context, swap: str = "outerHTML"):
" ".join(html),
id=context["id"],
url=event_url(component, "render"),
headers=json.dumps(
{
"X-Component-State": signer.sign(component._state_json),
}
),
headers=json.dumps({
"X-Component-State": signer.sign(component._state_json),
}),
)


Expand Down Expand Up @@ -169,9 +167,7 @@ def on(
"hx-post": event_url(component, _event_handler),
"hx-trigger": _trigger,
"hx-target": f"#{component.id}" if hx_target is unset else hx_target,
"hx-include": (
f"#{component.id} [name]" if hx_include is unset else hx_include
),
"hx-include": (f"#{component.id} [name]" if hx_include is unset else hx_include),
"hx-vals": json.dumps(kwargs) if kwargs else None,
}
return format_html_attrs(attrs)
Expand Down
5 changes: 1 addition & 4 deletions src/djhtmx/tracing.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
import contextlib

try:
from sentry_sdk import ( # pyright: ignore[reportMissingImports]
Hub,
configure_scope,
)
from sentry_sdk import Hub, configure_scope # pyright: ignore[reportMissingImports]

@contextlib.contextmanager
def sentry_transaction_name(transaction_name):
Expand Down

0 comments on commit ba0f3f5

Please sign in to comment.