Skip to content

Commit

Permalink
fix: bug when url() route uses the regex kwarg
Browse files Browse the repository at this point in the history
  • Loading branch information
browniebroke committed Jan 19, 2021
1 parent 1b785b7 commit b7bcc3d
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
10 changes: 10 additions & 0 deletions django_codemod/visitors/urls.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from typing import Sequence

from libcst import Arg, BaseExpression, Call, Name, SimpleString
from libcst import matchers as m
from libcst.codemod.visitors import AddImportsVisitor
Expand Down Expand Up @@ -97,3 +99,11 @@ def check_route(self, route):
"""Check that route doesn't contain anymore regex."""
if set(route) & REGEX_SPECIALS_SANS_DASH:
raise PatternNotSupported(f"Route {route} contains regex")

def update_call_args(self, node: Call) -> Sequence[Arg]:
"""Remove keyword argument from first argument of `re_path`."""
first_arg, *other_args = node.args
if m.matches(first_arg, m.Arg(keyword=m.Name("regex"))):
first_arg = Arg(value=first_arg.value)
return (first_arg, *other_args)
return super().update_call_args(node)
22 changes: 22 additions & 0 deletions tests/visitors/test_urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -168,3 +168,25 @@ def test_non_captured_group(self) -> None:
]
"""
self.assertCodemod(before, after)

def test_route_with_kwargs(self) -> None:
"""Check when `url()` call uses keyword argument `regex`."""
before = """
from django.conf.urls import url
urlpatterns = [
url(regex=r'^/$', view=views.home, name='home'),
url(regex=r'^p/(?P<page>[0-9]+)/$', view=views.page, name='page'),
url(regex=r'^hex/(?P<code>[a-f1-9]+)/$', view=views.hex, name='hex'),
]
"""
after = """
from django.urls import path, re_path
urlpatterns = [
path('/', view=views.home, name='home'),
path('p/<int:page>/', view=views.page, name='page'),
re_path(r'^hex/(?P<code>[a-f1-9]+)/$', view=views.hex, name='hex'),
]
"""
self.assertCodemod(before, after)

0 comments on commit b7bcc3d

Please sign in to comment.