1#!/usr/bin/python3
2
3import glob
4import os
5import re
6import sys
7
8project_path = os.getcwd()
9exit_code = 0
10
11def report_error(msg, *args):
12  global exit_code
13  sys.stderr.write("\033[31mError:\033[0m ")
14  sys.stderr.write((msg % args))
15  sys.stderr.write("\n")
16  exit_code = 1
17
18def find_java_files(dir):
19  for root, path, files in os.walk(dir):
20    for name in files:
21      if name.endswith(".java"):
22        yield os.path.sep.join([root, name])
23
24def get_java_package(file):
25  with open(file, "rt") as f:
26    for line in f:
27      m = re.match(r'\s*package\s+(.+);', line)
28      if m:
29        return m.group(1)
30  return None
31
32def verify_package_path(file, srcdir):
33  assert file.startswith(srcdir)
34  package = get_java_package(file)
35  if package is None:
36    report_error("can't find package declaration in %s", file)
37
38  dir_package = ".".join(file[len(srcdir):].split(os.path.sep)[:-1])
39  if dir_package != package:
40    report_error("package declaration in %s does not match expected package based on it's path: '%s' != '%s'", file, package, dir_package)
41
42
43java_src_dir = os.path.sep.join([project_path, "java", ""])
44javatests_src_dir = os.path.sep.join([project_path, "javatests", ""])
45
46
47for java in find_java_files(project_path):
48  if java.startswith(java_src_dir):
49    verify_package_path(java, java_src_dir)
50  elif java.startswith(javatests_src_dir):
51    verify_package_path(java, javatests_src_dir)
52  else:
53    report_error("java file not inside java/ or javatests/: %s", java)
54
55if exit_code != 0:
56  sys.stderr.write("All java files in this project should go in java/ or javatests/ in a directory matching its package.\n")
57
58sys.exit(exit_code)
59