Skip to content

libcst-based script to condition code in stubs #288

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions scripts/remove_django_2_2_code.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import libcst
import libcst.matchers as m
from libcst import If, IndentedBlock, BaseSuite
from libcst.codemod import ContextAwareTransformer, CodemodContext

STUB = 'stub.pyi'
IS_3_0 = True


def is_django_3_0(if_node: If) -> bool:
return m.matches(if_node.test, m.Name(value='DJANGO_3_0'))


class DjangoVersionTransformer(ContextAwareTransformer):
def leave_IndentedBlock(
self, original_node: "IndentedBlock", updated_node: "IndentedBlock"
) -> "BaseSuite":
modified_body = []
for statement in original_node.body:
if not m.matches(statement, m.If(test=m.Name(value='DJANGO_3_0'))):
modified_body.append(statement)
continue

if_statement = libcst.ensure_type(statement, If)
if IS_3_0:
modified_body.extend(if_statement.body.body)
else:
if if_statement.orelse is not None:
modified_body.extend(if_statement.orelse.body.body)
else:
continue

return updated_node.with_changes(body=modified_body)


with open(STUB) as f:
contents = f.read()

tree = libcst.parse_module(contents)
context = CodemodContext()
transformer = DjangoVersionTransformer(context)

modified_tree = tree.visit(transformer)
print(modified_tree.code)
11 changes: 11 additions & 0 deletions scripts/stub.pyi
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
DJANGO_2_2 = 1
DJANGO_3_0 = 2

class MyClass:
if DJANGO_3_0:
def django_3_0_func(self, a: int) -> int: ...
else:
def django_2_2_func(self, a: str) -> str: ...

if DJANGO_3_0:
def only_django_3_0_func(self, a: int) -> int: ...