google / pasta

Library to refactor python code through AST manipulation.
Apache License 2.0
341 stars 40 forks source link

Comment at the end of the file is being removed after executing pasta.dump #26

Closed williamjamir closed 6 years ago

williamjamir commented 6 years ago

Hi again =)

I found this issue while running the following script "script.py "on file "rename.py" Script.py

import os
import pasta
from pasta.augment import rename

path = r'rename.py'
with open(path, mode='r') as file:
    tree = pasta.parse(file.read())
    for moved_classes in list_of_classes_to_move:
        rename.rename_external(tree, 'a.b.c', 'a.b.d')
    source_code = pasta.dump(tree)

with open(path, mode='w') as file:
    print(source_code)
    file.write(source_code)

File before the pasta.dump:

from a.b import c 

c

#Testing
#Test1

File after the pasta.dump:

from a.b import d 

d

I've noticed that this issue just occurs when the commentary is at the end of the file, without any more code after it.

So in this example, the pasta.dump works just fine:

from a.b import c 

c

#Testing
#Test1

print('Hi')

After dump:

from a.b import d 

d

#Testing
#Test1

print('Hi')

cc @nicoddemus

williamjamir commented 6 years ago

Just to add that when the comment is at the end of the file, but "inside" a function, the dump occurs just fine.

Before the dump:

from a.b import c

c

#Testing
#Test1

def a():
    print('Hi')
    # Last line of function

After the dump:

from a.b import d

d

#Testing
#Test1

def a():
    print('Hi')
    # Last line of function
soupytwist commented 6 years ago

Thanks! :) There needs to be a test for this. The last statement should probably get the suffix.

soupytwist commented 6 years ago

I put the suffix on the Module node itself, I think that makes sense.