Use argparse for definition finder

This commit is contained in:
Mark Haines 2015-09-23 10:17:50 +01:00
parent 3559a835a2
commit 04abf53a56
1 changed files with 37 additions and 25 deletions

View File

@ -92,17 +92,28 @@ def used_names(prefix, defs, names):
if __name__ == '__main__': if __name__ == '__main__':
import sys, os import sys, os, argparse, re
if not sys.argv[1:]:
sys.stderr.write( parser = argparse.ArgumentParser(description='Find definitions.')
"Usage: definitions.py <directory> <regexp>\n" parser.add_argument(
" definitions.py <directory>\n" "--unused", action="store_true", help="Only list unused definitions"
"Either list the definitions matching the regexp or list\n"
" 'unused' definitions\n"
) )
parser.add_argument(
"--ignore", action="append", metavar="REGEXP", help="Ignore a pattern"
)
parser.add_argument(
"--pattern", nargs='+', action="append", metavar="REGEXP",
help="Search for a pattern"
)
parser.add_argument(
"directories", nargs='+', metavar="DIR",
help="Directories to search for definitions"
)
args = parser.parse_args()
definitions = {} definitions = {}
for root, dirs, files in os.walk(sys.argv[1]): for directory in args.directories:
for root, dirs, files in os.walk(directory):
for filename in files: for filename in files:
if filename.endswith(".py"): if filename.endswith(".py"):
filepath = os.path.join(root, filename) filepath = os.path.join(root, filename)
@ -115,16 +126,17 @@ if __name__ == '__main__':
for filepath, defs in definitions.items(): for filepath, defs in definitions.items():
used_names(filepath + ":", defs, names) used_names(filepath + ":", defs, names)
if sys.argv[2:]: patterns = [re.compile(pattern) for pattern in args.pattern or ()]
import re ignore = [re.compile(pattern) for pattern in args.ignore or ()]
pattern = re.compile(sys.argv[2])
for name in list(names):
if not pattern.match(name):
del names[name]
else:
for name in list(names):
if 'used' in names[name]:
del names[name]
yaml.dump(names, sys.stdout, default_flow_style=False) result = {}
#yaml.dump(definitions, sys.stdout, default_flow_style=False) for name, definition in names.items():
if patterns and not any(pattern.match(name) for pattern in patterns):
continue
if ignore and any(pattern.match(name) for pattern in ignore):
continue
if args.unused and definition.get('used'):
continue
result[name] = definition
yaml.dump(result, sys.stdout, default_flow_style=False)