Skip to content

Commit f21316e

Browse files
committed
Improve output when interrupted (^C)
1 parent b3bfecd commit f21316e

File tree

2 files changed

+31
-6
lines changed

2 files changed

+31
-6
lines changed

pre_commit/error_handler.py

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -44,9 +44,11 @@ def _log_and_exit(msg, exc, formatted):
4444
def error_handler():
4545
try:
4646
yield
47-
except FatalError as e:
48-
_log_and_exit('An error has occurred', e, traceback.format_exc())
49-
except Exception as e:
50-
_log_and_exit(
51-
'An unexpected error has occurred', e, traceback.format_exc(),
52-
)
47+
except (Exception, KeyboardInterrupt) as e:
48+
if isinstance(e, FatalError):
49+
msg = 'An error has occurred'
50+
elif isinstance(e, KeyboardInterrupt):
51+
msg = 'Interrupted (^C)'
52+
else:
53+
msg = 'An unexpected error has occurred'
54+
_log_and_exit(msg, e, traceback.format_exc())

tests/error_handler_test.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,29 @@ def test_error_handler_uncaught_error(mocked_log_and_exit):
7373
)
7474

7575

76+
def test_error_handler_keyboardinterrupt(mocked_log_and_exit):
77+
exc = KeyboardInterrupt()
78+
with error_handler.error_handler():
79+
raise exc
80+
81+
mocked_log_and_exit.assert_called_once_with(
82+
'Interrupted (^C)',
83+
exc,
84+
# Tested below
85+
mock.ANY,
86+
)
87+
assert re.match(
88+
r'Traceback \(most recent call last\):\n'
89+
r' File ".+pre_commit.error_handler.py", line \d+, in error_handler\n'
90+
r' yield\n'
91+
r' File ".+tests.error_handler_test.py", line \d+, '
92+
r'in test_error_handler_keyboardinterrupt\n'
93+
r' raise exc\n'
94+
r'KeyboardInterrupt\n',
95+
mocked_log_and_exit.call_args[0][2],
96+
)
97+
98+
7699
def test_log_and_exit(cap_out, mock_store_dir):
77100
with pytest.raises(SystemExit):
78101
error_handler._log_and_exit(

0 commit comments

Comments
 (0)