Skip to content

Instantly share code, notes, and snippets.

@novocaine
Last active August 29, 2015 14:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save novocaine/d06d82259f107266b2e3 to your computer and use it in GitHub Desktop.
Save novocaine/d06d82259f107266b2e3 to your computer and use it in GitHub Desktop.
Using redbaron to find all open()s in text mode so we can review them for python 3
from redbaron import RedBaron
import os
import sys
import io
def is_bad_open(node):
# must be function invocation (not method invocation)
if node.parent.type != 'atomtrailers':
return False
if node.index_on_parent != 0:
return False
# must be called()
if node.next is None or node.next.type != 'call':
return False
call = node.next
arglist = call.value
# if it only has one argument, its text
if len(arglist) <= 1:
return True
def is_binary_mode(node):
return node.value.type == 'string' and "b" in str(node.value)
# second argument is not a kvarg, must be mode
if arglist[1].target is None:
# we can ignore it if its a string literal containing 'b'
return not is_binary_mode(arglist[1])
# second argument is a kvarg, so try to find mode in
# any remaining args
for arg in arglist[1:]:
if arg.target.value == "mode":
return not is_binary_mode(arg)
return True
def process(src):
"""
>>> process('open(x)')
'1:open(x)\\n'
>>> process('open(x, "wb")')
''
>>> process('open(x, "w")')
'1:open(x, "w")\\n'
>>> process('open(x, something=blah)')
'1:open(x, something=blah)\\n'
>>> process('open(x, something=blah, mode="r")')
'1:open(x, something=blah, mode="r")\\n'
"""
output = io.BytesIO()
for sort in RedBaron(src).find_all('name', value='open'):
if is_bad_open(sort):
output.write("%d:%s\n" %
(sort.absolute_bounding_box.top_left.line, sort.parent))
return output.getvalue()
if __name__ == "__main__":
if len(sys.argv) > 1:
for f in sys.argv[1:]:
s = process(open(f).read())
if s:
print f
print s
else:
import doctest
doctest.testmod()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment