Skip to content
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

Script for merging stubs into Django source files for testing #408

Open
wants to merge 12 commits into
base: master
Choose a base branch
from
59 changes: 59 additions & 0 deletions scripts/merge_stubs_into_django.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
from libcst import parse_module
from libcst.codemod import CodemodContext
from libcst.codemod.visitors import ApplyTypeAnnotationsVisitor

from pathlib import Path

def prRed(skk): print("\033[91m {}\033[00m" .format(skk))
def prGreen(skk): print("\033[92m {}\033[00m" .format(skk))

context = CodemodContext()
visitor = ApplyTypeAnnotationsVisitor(context)

stubs_dir = '../django-stubs'
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please, make paths not .. relative, but with Path(__file__).parent so that script could be run from other directories too.

sources_dir = '../django-sources/django'

stubs_dict = {}
sources_dict = {}

stubs_pathlist = Path(stubs_dir).rglob('*.pyi')
sources_pathlist = Path(sources_dir).rglob('*.py')

for path in stubs_pathlist:
str_path = str(path)

stubs_dict[str_path.split('/', 2)[-1].split('.')[0]] = str_path
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same thing here, use pathlib.Path everywhere for filesystem paths.


for path in sources_pathlist:
str_path = str(path)

key = str_path.split('/', 3)[-1].split('.')[0]

if key in stubs_dict:
sources_dict[key] = str_path

for key in stubs_dict:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please use enumerate(stubs_dict), you're using values of the dict too


with open(stubs_dict[key]) as file:
stub = file.read()

stub_module = parse_module(stub)
visitor.store_stub_in_context(context, stub_module)

try:
with open(sources_dict[key]) as file:
source = file.read()
except:
prRed('No corresponding file for stub: ' + stubs_dict[key])
continue

source_module = parse_module(source)
result = visitor.transform_module(source_module)

try:
file=open(sources_dict[key], 'w')
file.write(result.code)
file.close()
prGreen(sources_dict[key])
except:
prRed('Error saving file: ' + sources_dict[key])