Skip to content

Instantly share code, notes, and snippets.

@bendem
Last active August 29, 2015 14:05
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 bendem/957b085b6fa0c1677666 to your computer and use it in GitHub Desktop.
Save bendem/957b085b6fa0c1677666 to your computer and use it in GitHub Desktop.
This was supposed to check for java imports only used once in the bukkit's files. Won't be finished because working with a sane codebase has no purpose
import os
import sys
class parser:
def __init__(self, filename):
self.imports = {}
self.filename = filename
def classfromimport(self, imp):
if not imp.startswith('import '):
return False
fully_qualified = imp[7:-1]
return fully_qualified.split('.')[-1]
def parse(self):
f = open(self.filename, 'r')
for line in f:
imp = self.classfromimport(line[0:-1])
if imp:
self.imports[imp] = 0
else:
for imp, count in self.imports.items():
if(imp in line):
self.imports[imp] += 1
f.close()
def count(self):
i = 0
for imp, count in self.imports.items():
if count < 2:
i += 1
return i
def showresults(self):
print('Results for imports in %s' % self.filename)
for imp, count in self.imports.items():
if count < 2:
print(' import "%s" used %d time' % (imp, count))
def fixresults(self):
# This is bugged and will most likely never be fixed,
# the bukkit team decided working on a sane codebase
# was useless
# Read them linez
f = open(self.filename, 'r')
lines = f.readlines()
f.close()
# Write them linez
f = open(self.filename, 'w')
for line in lines:
imp = self.classfromimport(line[0:-1])
found = False
try:
self.imports[imp]
except KeyError:
found = True
if not found or self.imports[imp] > 1:
f.write(line)
print('Removed %s from %s' % (imp, filename))
def debug(self):
if len(self.imports) == 0:
return
for imp, count in self.imports.items():
print(' %s \timports used \t%d times' % (imp, count))
if len(sys.argv) < 2:
dir = '.'
else:
dir = sys.argv[1]
total = 0
for root, dirs, files in os.walk(dir, topdown=True):
for name in files:
p = parser(os.path.join(root, name))
p.parse()
count = p.count()
total += count
if count != 0:
p.showresults()
# p.fixresults()
print(' %d imports need attention' % count)
print('total: %d' % total)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment