import os.path

##### Begin things you want/need to set for yourself #####
propsroot = '/Users/bobby/work/ws/v3/extras/upgrade/upgrade-jar/src/main/resources'
srcroot = '/Users/bobby/work/ws/v3/extras/upgrade/upgrade-jar/src/main/java'

# file names to check. to add more, separate with commas
propfiles = [ 'LocalStrings.properties' ]

# source file extensions
sources = [ '.java' ]

# directories to skip
skipdirs = [ '.svn' ]
##### End things you want/need to set #####

def addkeys(keymap, propsdir, propsfile):
  for line in open(os.path.join(propsdir, propsfile)):
    line = line.strip()
    if not line or line[0] == '#':
      continue
    if '=' in line:
      key = line.split('=')[0]
      if key in keymap:
        print 'WARNING: the following key appears more than once in', propsdir
        print '\t', key
      else:
        keymap[key] = 0

def parsesource(keymap, sourcefile):
  wholefileasstring = open(sourcefile).read()
  for key in keymap:
    if key in wholefileasstring:
      keymap[key] = keymap[key] + 1

# in Java terms, this is Map<package name, Map<key, number of uses>>
propmapbypackage = {}

# Step 1, grab all the properties
print 'Parsing resource files relative to', propsroot
for (dirname, dirs, files) in os.walk(propsroot):
  # remove dirs we want to skip first
  for s in skipdirs:
    if s in dirs:
      dirs.remove(s)
  # now look for properties files to parse
  for file in files:
    if file in propfiles:
      # grrr, can't use os.path.relpath() on some platforms
      relpath = dirname.replace(propsroot, '')
      if relpath not in propmapbypackage:
        propmapbypackage[relpath] = {}
      print 'Parsing', file, 'in', relpath
      addkeys(propmapbypackage[relpath], dirname, file)

# Step 2, find out how many times each prop is used
print '\nFinished property parsing. Checking source files relative to', srcroot
nokeypackages = []
for (dirname, dirs, files) in os.walk(srcroot):
  relpath = dirname.replace(srcroot, '')
  #print 'Checking', relpath # uncomment if you're curious
  # remove dirs we want to skip first
  for s in skipdirs:
    if s in dirs:
      dirs.remove(s)
  # now check the source
  for file in files:
    for s in sources: # can't recall how to get file extension
      if file.endswith(s):
        if relpath in propmapbypackage:
          parsesource(propmapbypackage[relpath], os.path.join(dirname, file))
        elif relpath not in nokeypackages:
          nokeypackages.append(relpath)
if nokeypackages:
  print 'The following directories were skipped because no keys were found:'
  for p in nokeypackages:
    print '\t', p
    
# Step 3, report report report
print '\nResults:'
for package in propmapbypackage:
  print 'Keys not used in', package
  keymap = propmapbypackage[package]
  for key in keymap:
    if keymap[key] == 0:
      print '\t', key

print '\nDone'