From 830ea6d8c8c64f7fa5dc7459f37a6168a5ecd836 Mon Sep 17 00:00:00 2001 From: Anthony Sottile Date: Thu, 19 Jun 2014 17:41:53 -0700 Subject: [PATCH] Give a better message when ast is not parseable. --- pre_commit_hooks/debug_statement_hook.py | 14 +++++++++++--- testing/resources/cannot_parse_ast.notpy | 1 + tests/debug_statement_hook_test.py | 5 +++++ 3 files changed, 17 insertions(+), 3 deletions(-) create mode 100644 testing/resources/cannot_parse_ast.notpy diff --git a/pre_commit_hooks/debug_statement_hook.py b/pre_commit_hooks/debug_statement_hook.py index 92f7c07..0ff94cf 100644 --- a/pre_commit_hooks/debug_statement_hook.py +++ b/pre_commit_hooks/debug_statement_hook.py @@ -1,9 +1,10 @@ from __future__ import print_function +from __future__ import unicode_literals import argparse import ast import collections -import sys +import traceback from pre_commit_hooks.util import entry @@ -35,7 +36,14 @@ class ImportStatementParser(ast.NodeVisitor): def check_file_for_debug_statements(filename): - ast_obj = ast.parse(open(filename).read()) + try: + ast_obj = ast.parse(open(filename).read(), filename=filename) + except SyntaxError: + print('{0} - Could not parse ast'.format(filename)) + print() + print('\t' + traceback.format_exc().replace('\n', '\n\t')) + print() + return 1 visitor = ImportStatementParser() visitor.visit(ast_obj) if visitor.debug_import_statements: @@ -67,4 +75,4 @@ def debug_statement_hook(argv): if __name__ == '__main__': - sys.exit(debug_statement_hook()) + exit(debug_statement_hook()) diff --git a/testing/resources/cannot_parse_ast.notpy b/testing/resources/cannot_parse_ast.notpy new file mode 100644 index 0000000..150ca8d --- /dev/null +++ b/testing/resources/cannot_parse_ast.notpy @@ -0,0 +1 @@ +if True: diff --git a/tests/debug_statement_hook_test.py b/tests/debug_statement_hook_test.py index 44c462f..66d7307 100644 --- a/tests/debug_statement_hook_test.py +++ b/tests/debug_statement_hook_test.py @@ -65,3 +65,8 @@ def test_returns_one_for_failing_file(): def test_returns_zero_for_passing_file(): ret = debug_statement_hook([__file__]) assert ret == 0 + + +def test_syntaxerror_file(): + ret = debug_statement_hook([get_resource_path('cannot_parse_ast.notpy')]) + assert ret == 1