Created
June 22, 2016 07:00
-
-
Save justinmoon/d1001cf39ce67c8b94f31f7aa841b7b9 to your computer and use it in GitHub Desktop.
First-order hack at finding dead python code (unimported python files)
This file contains 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
import os | |
import re | |
from pprint import pprint | |
def import_from_path(path): | |
try: | |
path, file_extension = path.split('.') | |
_, karmic_path = path.split(os.getcwd()) | |
return re.sub('/', '.', karmic_path) | |
except Exception as e: | |
print(path) | |
def is_python_file(path): | |
split = path.split('.') | |
return len(split) == 2 and split[1] == 'py' | |
def collect_imports(): | |
imports = [] | |
for (dirpath, dirnames, filenames) in os.walk(os.getcwd()): | |
_imports = [import_from_path(dirpath + '/' + filename) | |
for filename in filenames | |
if is_python_file(filename)] | |
imports.extend(_imports) | |
return imports | |
def collect_files(): | |
files = [] | |
for (dirpath, dirnames, filenames) in os.walk(os.getcwd()): | |
_imports = [dirpath + '/' + filename | |
for filename in filenames | |
if is_python_file(filename)] | |
files.extend(_imports) | |
return files | |
def read_lines_in_project(): | |
lines = [] | |
for (dirpath, dirnames, filenames) in os.walk(os.getcwd()): | |
for filename in filenames: | |
if is_python_file(filename): | |
with open(dirpath + '/' + filename, 'r') as f: | |
lines.extend(f.readlines()) | |
return lines | |
def unused_imports(imports, lines): | |
imports = set(i for i in imports if type(i) == str) | |
lines = set(l for l in lines if type(l) == str) | |
unused_imports = imports.copy() | |
for line in lines: | |
for import_ in imports: | |
if import_ in line: | |
if import_ in unused_imports: | |
unused_imports.remove(import_) | |
return unused_imports | |
def main(): | |
return unused_imports(collect_imports(), collect_files()) | |
if __name__ == '__main__': | |
pprint(sorted(main())) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment