78
|
1 |
#
|
|
2 |
# Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
|
|
3 |
# All rights reserved.
|
|
4 |
# This component and the accompanying materials are made available
|
|
5 |
# under the terms of "Eclipse Public License v1.0"
|
|
6 |
# which accompanies this distribution, and is available
|
|
7 |
# at the URL "http://www.eclipse.org/legal/epl-v10.html".
|
|
8 |
#
|
|
9 |
# Initial Contributors:
|
|
10 |
# Nokia Corporation - initial contribution.
|
|
11 |
#
|
|
12 |
# Contributors:
|
|
13 |
#
|
|
14 |
# Description: Check Java source code for inconsistencies. Includes following checks
|
|
15 |
# - is package defined and matching with file path
|
|
16 |
#
|
|
17 |
#! /usr/bin/python
|
|
18 |
|
|
19 |
import os, fnmatch, re, sys
|
|
20 |
from optparse import OptionParser
|
|
21 |
|
|
22 |
RE_PACKAGE = re.compile(r"package\s+([\w.]+)\s*;")
|
|
23 |
|
|
24 |
|
|
25 |
def getPackage(f):
|
|
26 |
''' Return the package of Java source file, or None if not defined '''
|
|
27 |
fin = file(f, "r")
|
|
28 |
for l in fin.readlines():
|
|
29 |
match = RE_PACKAGE.search(l)
|
|
30 |
if match:
|
|
31 |
return match.group(1)
|
|
32 |
|
|
33 |
return None
|
|
34 |
|
|
35 |
def checkPackage(f, package):
|
|
36 |
''' Check if package is correct in file path. Return True if incorrect. '''
|
|
37 |
|
|
38 |
if not package:
|
|
39 |
print "%s(0): error: no package defined" % f
|
|
40 |
return True
|
|
41 |
|
|
42 |
dir = os.path.dirname(f).replace("\\", "/")
|
|
43 |
if not dir.endswith(package.replace(".", "/")):
|
|
44 |
print "%s(0): error: package \"%s\" does not match filepath" % (f, package)
|
|
45 |
return True
|
|
46 |
|
|
47 |
return False
|
|
48 |
|
|
49 |
def checkHierarchy(root, exclude = None):
|
|
50 |
failures = False
|
|
51 |
for path, dirs, files in os.walk(root):
|
|
52 |
if exclude and exclude in path.replace("\\", "/").split("/"):
|
|
53 |
continue
|
|
54 |
|
|
55 |
filenames = [os.path.join(path, f) for f in fnmatch.filter(files, "*.java")]
|
|
56 |
for f in filenames:
|
|
57 |
result = checkPackage(f, getPackage(f))
|
|
58 |
failures = failures or result
|
|
59 |
|
|
60 |
return failures
|
|
61 |
|
|
62 |
def main():
|
|
63 |
parser = OptionParser()
|
|
64 |
parser.add_option("--exclude", dest = "exclude",
|
|
65 |
help = "Exclude paths having this directory component, e.g. tsrc")
|
|
66 |
(options, args) = parser.parse_args()
|
|
67 |
|
|
68 |
failures = False
|
|
69 |
for root in args:
|
|
70 |
failures = failures or checkHierarchy(root, options.exclude)
|
|
71 |
|
|
72 |
sys.exit(failures and 1 or 0)
|
|
73 |
|
|
74 |
if __name__ == "__main__":
|
|
75 |
main()
|