Skip to content

Instantly share code, notes, and snippets.

@renefritze
Created August 28, 2012 09:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save renefritze/3496531 to your computer and use it in GitHub Desktop.
Save renefritze/3496531 to your computer and use it in GitHub Desktop.
finds cpp files from given dir that are never included in given dir
#!/usr/bin/env python
import sys
import re
import pprint
import os
import fnmatch
headers = { 'cpp': ['*.h', '*.hh', '*.hpp'] }
sources = { 'cpp': ['*.c', '*.cpp', '*.cc']}
main_returns = ['void', 'int', 'long', 'char', 'short']
mains = [ '%s main'%ret for ret in main_returns]
def cpp_line_check(line):
pos = line.find('include')
if pos > -1:
imp = (line[pos+len('include'):]).strip(' "<>\n\r')
last = imp.split('/')[-1]
return last
return None
def get_files(search_dir, lang):
os.chdir(search_dir)
ext = headers[lang] + sources[lang]
patterns = re.compile('|'.join(fnmatch.translate(p) for p in ext))
matches = []
for root, dirs, files in os.walk(search_dir):
matches.extend([os.path.join(root,f) for f in files if patterns.match(f)])
return matches
def build_imports(fn, lang, line_check):
with open(fn,'rb') as code:
imps = set()
for line in code:
imp = line_check(line)
if imp:
imps.add(imp)
return imps
def has_main(fn):
with open(fn,'rb') as code:
for line in code:
if 'main' in line:
if line.strip()[:line.find('main')-1] in main_returns:
return True
return False
try:
search_dir = sys.argv[1]
except:
search_dir = '.'
lang = 'cpp'
all_files = get_files(search_dir, lang)
includes = set()
for fn in all_files:
includes.update( build_imports(fn, lang, cpp_line_check) )
orphans = [fn for fn in all_files if (os.path.basename(fn) not in includes) and not has_main(fn) ]
pp = pprint.PrettyPrinter(indent=2)
pp.pprint(orphans)
print('total orphans %d of %d files checked'%(len(orphans), len(includes)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment