# HG changeset patch # User Paul Boddie # Date 1225063268 -3600 # Node ID eb06eca515752bd4d53f7356fea44b514d886321 # Parent 77cb8923b1d42c39bc6fa8dce59b22676d475870 Fixed erroneous usage of global args in search_recursive instead of the directory parameter. Switched to using regular expressions instead of explicit operators. diff -r 77cb8923b1d4 -r eb06eca51575 astgrep.py --- a/astgrep.py Sun Oct 26 21:02:17 2008 +0100 +++ b/astgrep.py Mon Oct 27 00:21:08 2008 +0100 @@ -31,7 +31,7 @@ """ results = [] - for path, directories, filenames in os.walk(args["directory"]): + for path, directories, filenames in os.walk(directory): for filename in filenames: if os.path.splitext(filename)[-1] == os.path.extsep + "py": results += search_file(os.path.join(path, filename), term_type, term, op) @@ -64,7 +64,7 @@ results.append((node, None, filename)) else: for child in node.getChildren(): - if isinstance(child, (str, unicode, int, float, long, bool)) and op(unicode(child), term): + if isinstance(child, (str, unicode, int, float, long, bool)) and op(unicode(child)): results.append((node, child, filename)) break @@ -75,15 +75,6 @@ return results -def get_operator(name): - - "Return the operator having the given 'name'." - - if name is None: - return unicode.__eq__ - else: - return getattr(unicode, name) - def expand_results(results): """ @@ -106,12 +97,11 @@ # Command syntax. syntax_description = """ - [ -n ] - [ -v ] - -t - [ -o ] - [ -e ] - ( ( -r ) | ) + [ -n | --line-number ] + [ -p | --print-token ] + ( ( -t TERM_TYPE ) | ( --type=TERM_TYPE ) ) + [ ( -e PATTERN ) | ( --regexp=PATTERN ) ] + ( ( ( -r | -R | --recursive ) DIRECTORY ) | FILENAME ) """ # Main program. @@ -119,6 +109,7 @@ if __name__ == "__main__": import sys import cmdsyntax + import re import linecache # Match command arguments. @@ -135,20 +126,20 @@ # Get the search details. - term_type = args["term-type"] - term = args.get("expression") + term_type = args["TERM_TYPE"] + term = args.get("PATTERN") if term is None: op = None else: - op = get_operator(args.get("operator")) + op = re.compile(term).match # Perform the search either in a single file or in a directory hierarchy. - if args.has_key("filename"): - results = search_file(args["filename"], term_type, term, op) + if args.has_key("FILENAME"): + results = search_file(args["FILENAME"], term_type, term, op) else: - results = search_recursive(args["directory"], term_type, term, op) + results = search_recursive(args["DIRECTORY"], term_type, term, op) # Present the results. @@ -156,11 +147,11 @@ format = "%s:" output = [filename] - if args.has_key("n"): + if args.has_key("n") or args.has_key("line-number"): format += "%d:" output.append(lineno) - if args.has_key("v"): + if args.has_key("p"): if value is not None: format += "%r:" output.append(value)