-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathadd-imports.py
88 lines (68 loc) · 2.33 KB
/
add-imports.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#!/usr/bin
# Add missing imports to NMS after MCP package class rename
# XXX: This is obsolete - used in the older 1.4.5 rename. 1.4.6+ in rangeapply.py
import os, re
import packagify
srcdir = "../CraftBukkit/src/main/java/net/minecraft"
def getJavaSource(srcdir):
paths = []
for root, dirs, files in os.walk(srcdir):
for fn in files:
if not fn.endswith(".java"): continue
path = os.path.join(root, fn)
paths.append(path)
for d in dirs:
paths.extend(getJavaSource(os.path.join(root, d)))
return paths
# Get (heurstically estimated) classes referenced by another class
def getClassUsage(data, clslist):
foundClasses = []
for cls in clslist:
if re.search(r"\b" + re.escape(cls) + r"\b", data):
foundClasses.append(cls)
return foundClasses
def addImports(data, newImports):
lines = data.split("\n")
lastNativeImport = None
existingImports = []
for i, line in enumerate(lines):
if line.startswith("import net.minecraft"):
lastNativeImport = i
existingImports.append(line)
if lastNativeImport is None:
insertionPoint = 3
else:
insertionPoint = lastNativeImport
importsToAdd = []
for imp in newImports:
if imp in existingImports: continue
importsToAdd.append(imp)
splice = lines[0:insertionPoint] + importsToAdd + lines[insertionPoint:]
return "\n".join(splice)
def getThisPackage(data):
match = re.match(r"package ([^;]+);", data)
if not match:
print data
print "!!! Unable to parse package in file"
raise SystemExit
return match.group(1)
cls2pkg = packagify.getPackages()
for filename in getJavaSource(srcdir):
data = file(filename, "r").read()
if "COPIED MCP SOURCE" in data: continue
usedClasses = getClassUsage(data, cls2pkg.keys())
thisPackage = getThisPackage(data)
newImports = []
for cls in usedClasses:
pkg = cls2pkg[cls].replace("/",".")
if pkg == thisPackage: continue # unnecessary import
newImports.append("import %s.%s;" % (pkg, cls))
newImports.sort()
print filename
#print "BEFORE"
#print data
data = addImports(data, newImports)
#print "AFTER"
#print data
print len(newImports)
file(filename, "w").write(data)