From b7bcc3dee08fadc90afdc9490828569e7ec06786 Mon Sep 17 00:00:00 2001 From: Bruno Alla Date: Tue, 19 Jan 2021 19:04:53 +0000 Subject: [PATCH] fix: bug when `url()` route uses the `regex` kwarg --- django_codemod/visitors/urls.py | 10 ++++++++++ tests/visitors/test_urls.py | 22 ++++++++++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/django_codemod/visitors/urls.py b/django_codemod/visitors/urls.py index 2b700162..0b4a591e 100644 --- a/django_codemod/visitors/urls.py +++ b/django_codemod/visitors/urls.py @@ -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 @@ -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) diff --git a/tests/visitors/test_urls.py b/tests/visitors/test_urls.py index a9715574..8f5f8f72 100644 --- a/tests/visitors/test_urls.py +++ b/tests/visitors/test_urls.py @@ -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[0-9]+)/$', view=views.page, name='page'), + url(regex=r'^hex/(?P[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//', view=views.page, name='page'), + re_path(r'^hex/(?P[a-f1-9]+)/$', view=views.hex, name='hex'), + ] + """ + self.assertCodemod(before, after)