Created
July 17, 2019 15:05
-
-
Save romuald/85483f6e23c0025c82f2d82090f4c1d1 to your computer and use it in GitHub Desktop.
Search python files for division operators, helping spot issues with python3 migrations
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
""" | |
This script will search python files inside directories and list use of | |
the division operator. | |
It is meant to help spot possible issues with python3 migrations | |
""" | |
import io | |
import os | |
import ast | |
import sys | |
import itertools | |
def search_file(filename): | |
data = io.open(filename, mode='rb').read() | |
try: | |
parsed = ast.parse(data, filename) | |
except SyntaxError as err: | |
print('ERROR', filename, err) | |
return | |
lines = data.decode().splitlines() | |
prev = None | |
for node in ast.walk(parsed): | |
if isinstance(node, ast.Div): | |
yield filename, node, prev, lines[prev.lineno - 1] | |
prev = node | |
def gather(dirs): | |
for directory in dirs: | |
for root, _, files in os.walk(directory): | |
for file in files: | |
if file.endswith('.py'): | |
yield os.path.join(root, file) | |
def main(): | |
dirs = sys.argv[1:] | |
print('Searching for division operator in %s' % (', '.join(dirs))) | |
files = gather(dirs) | |
res = itertools.chain(*map(search_file, files)) | |
for filename, node, prev, line in res: | |
print('%s:%d %s' % (filename, prev.lineno, line.strip())) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment