-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMethodsCounter.py
More file actions
265 lines (249 loc) · 11.1 KB
/
MethodsCounter.py
File metadata and controls
265 lines (249 loc) · 11.1 KB
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import ConfigParser
import xml.dom.minidom
import codecs
import re
from exceptions import RuntimeError
import time
# Get a config parse
def getConfigParser():
configFile = os.path.join(os.path.dirname(__file__), 'config.ini')
if os.path.exists(configFile):
parser = ConfigParser.ConfigParser()
parser.read(configFile)
return parser
# Check whether the project is an Eclipse project
def isEclipseProject(projectDir):
manifestFile = os.path.join(projectDir, 'AndroidManifest.xml')
return os.path.exists(manifestFile)
# Check whether the project is an Android Studio project
def isAndroidStudioProject(projectDir):
manifestFile = os.path.join(projectDir, 'AndroidManifest.xml')
gradleFile = os.path.join(projectDir, 'build.gradle')
if os.path.exists(manifestFile):
return False
else:
return os.path.exists(gradleFile)
# Get the source code folder path
def getSrcPathList(isEclipse, projectDir):
srcPath = []
if isEclipse:
cfgFile = os.path.join(projectDir, '.classpath')
if os.path.exists(cfgFile):
dom = xml.dom.minidom.parse(cfgFile)
root = dom.documentElement
items = root.getElementsByTagName('classpathentry')
for item in items:
itemKind = item.getAttribute('kind')
if itemKind == 'src':
itemPath = item.getAttribute('path')
if itemPath != 'gen':
srcPath.append(os.path.join(projectDir, itemPath))
return srcPath
else:
srcPath.append(os.path.join(projectDir, 'src'))
return srcPath
else:
cfgFile = os.path.join(projectDir, 'build.gradle')
if os.path.exists(cfgFile):
cfgFp = open(cfgFile, 'r')
inSourceSetsCfg = False
braceCount = 0
for cfgLine in cfgFp:
stripLine = cfgLine.strip()
if stripLine.startswith('sourceSets'):
inSourceSetsCfg = True
if inSourceSetsCfg:
pos = stripLine.find('java.srcDirs')
if pos != -1:
stripLine = stripLine[pos + len('java.srcDirs'):].lstrip()
assert len(stripLine) > 2
if stripLine[0:2] == '+=':
temp = os.path.join(projectDir, 'src' + os.path.sep + 'main' + os.path.sep + 'java')
srcPath.append(temp)
stripLine = stripLine[2:]
stripLine = stripLine.lstrip(' [=').rstrip(']')
splitLine = stripLine.split(',')
for splitItem in splitLine:
splitItem = splitItem.strip(' \'"')
if len(splitItem) != 0:
if os.path.sep != '/':
splitItem = splitItem.replace('/', os.path.sep)
elif os.path.sep != '\\':
splitItem = splitItem.replace('\\', os.path.sep)
srcPath.append(os.path.join(projectDir, splitItem))
break
braceCount += stripLine.count('{')
braceCount -= stripLine.count('}')
if braceCount <= 0:
break
if len(srcPath) == 0:
srcPath.append(os.path.join(projectDir, 'src' + os.path.sep + 'main' + os.path.sep + 'java'))
return srcPath
else:
srcPath.append(os.path.join(projectDir, 'src' + os.path.sep + 'main' + os.path.sep + 'java'))
return srcPath
def countMethods(srcPathList):
srcCountList = []
classLineRegex = re.compile(r'enum\s+\S+.*?\{|class\s+\S+.*?\{|new\s+\S+\s*\(.*\)\s*\{')
# Iterate through all source code folders
for srcPath in srcPathList:
for (parent, _, fileNames) in os.walk(srcPath):
for fileName in fileNames:
# ignores non java code
if not fileName.endswith('.java'):
continue
# read java code to find used resource
fileFullPath = os.path.join(parent, fileName)
fp = open(fileFullPath, 'r')
fileContent = fp.readlines()
fp.close()
lineCount = len(fileContent)
braceStack = []
currentBraceCount = 0
classCount = 0
methodCount = 0
isInMultiComment = False
for fileLine in fileContent:
stripedLine = fileLine.strip()
if isInMultiComment:
endComment = stripedLine.rfind('*/')
if endComment == -1:
continue
else:
isInMultiComment = False
fileLine = stripedLine[endComment+2:]
if fileLine == '':
continue
else:
if stripedLine.startswith('//'):
continue
if stripedLine.startswith('/*'):
endComment = stripedLine.rfind('*/')
if endComment == -1:
isInMultiComment = True
continue
else:
fileLine = stripedLine[endComment+2:]
if fileLine == '':
continue
ret = classLineRegex.search(fileLine)
while ret:
group0 = ret.group(0)
group0Pos = fileLine.find(group0)
group0Left = fileLine[0:group0Pos]
group0Right = fileLine[group0Pos+len(group0):]
if currentBraceCount != 0:
for ch in group0Left:
if ch == '{':
currentBraceCount += 1
elif ch == '}':
currentBraceCount -= 1
if currentBraceCount == 1:
methodCount += 1
elif currentBraceCount == 0:
if len(braceStack) != 0:
currentBraceCount = braceStack.pop()
fileLine = group0Right
ret = classLineRegex.search(fileLine)
if currentBraceCount != 0:
braceStack.append(currentBraceCount)
currentBraceCount = 1
classCount += 1
if currentBraceCount != 0:
for ch in fileLine:
if ch == '{':
currentBraceCount += 1
elif ch == '}':
currentBraceCount -= 1
if currentBraceCount == 1:
methodCount += 1
elif currentBraceCount == 0:
if len(braceStack) != 0:
currentBraceCount = braceStack.pop()
fileRelativePath = fileFullPath[len(srcPath):]
srcCountList.append((fileRelativePath, lineCount, classCount, methodCount))
return srcCountList
def getReadableTime1(curTime):
year = curTime[0]
month = curTime[1]
day = curTime[2]
hour = curTime[3]
minute = curTime[4]
second = curTime[5]
readableTime = '%d%02d%02d_%02d%02d%02d' % (year, month, day, hour, minute, second)
return readableTime
def getReadableTime2(curTime):
year = curTime[0]
month = curTime[1]
day = curTime[2]
hour = curTime[3]
minute = curTime[4]
second = curTime[5]
readableTime = '%d-%02d-%02d %02d:%02d:%02d' % (year, month, day, hour, minute, second)
return readableTime
def process():
configParser = getConfigParser()
if configParser is None:
return
# Get the configurations
projectDir = configParser.get('Dir', 'ProjectDir')
isShowSingleFile = configParser.get('MethodsCounter', 'ShowSingleFile')
isShowSingleFile = isShowSingleFile.lower()
if isShowSingleFile == 'true':
isShowSingleFile = True
elif isShowSingleFile == 'false':
isShowSingleFile = False
else:
raise RuntimeError('Invalid ShowSingleFile parameter')
# project dir is not exist, raise exception
if not os.path.exists(projectDir):
raise RuntimeError('Invalid project directory')
# Check whether the project is Eclipse or Android Studio
isEclipse = isEclipseProject(projectDir)
isAndroidStudio = isAndroidStudioProject(projectDir)
# not Eclipse project,and not Android Studio project, raise exception
if not isEclipse and not isAndroidStudio:
raise RuntimeError('Unknown project type')
# get the source code folder in the project
srcPathList = getSrcPathList(isEclipse, projectDir)
for srcPath in srcPathList:
if not os.path.exists(srcPath):
raise RuntimeError('Cannot find src path ' + srcPath)
logContent.append('Project dir: ' + projectDir)
# get configed resource
srcCountList = countMethods(srcPathList)
totalLineCount = 0
totalClassCount = 0
totalMethodCount = 0
for (srcFile, lineCount, classCount, methodCount) in srcCountList:
if isShowSingleFile:
logContent.append('%s: %d %d %d' % (srcFile, lineCount, classCount, methodCount))
totalLineCount += lineCount
totalClassCount += classCount
totalMethodCount += methodCount
logContent.append('Total File Count: %d' % len(srcCountList))
logContent.append('Total Line Count: %d' % totalLineCount)
logContent.append('Total Class Count: %d' % totalClassCount)
logContent.append('Total Method Count: %d' % totalMethodCount)
def saveToLog():
curTime = time.localtime()
logFile = 'Count_' + getReadableTime1(curTime) + '.log'
logFp = open(logFile, 'w+')
logFp.write('------------------------------ ' + getReadableTime2(curTime) + ' ------------------------------\n')
logFp.writelines([i + '\n' for i in logContent])
logFp.close()
if __name__ == '__main__':
logContent = []
try:
# start clean process
process()
except Exception, e:
# append the exception message to log
logContent.append(e.message)
finally:
# save log to file
saveToLog()
print 'done'