forked from pre-commit/pre-commit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patherror_handler.py
More file actions
80 lines (66 loc) · 2.1 KB
/
error_handler.py
File metadata and controls
80 lines (66 loc) · 2.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
import contextlib
import os.path
import sys
import traceback
import six
import pre_commit.constants as C
from pre_commit import five
from pre_commit import output
from pre_commit.store import Store
class FatalError(RuntimeError):
pass
def _to_bytes(exc):
try:
return bytes(exc)
except Exception:
return six.text_type(exc).encode('UTF-8')
def _log_and_exit(msg, exc, formatted):
error_msg = b''.join((
five.to_bytes(msg), b': ',
five.to_bytes(type(exc).__name__), b': ',
_to_bytes(exc),
))
output.write_line(error_msg)
store = Store()
log_path = os.path.join(store.directory, 'pre-commit.log')
output.write_line('Check the log at {}'.format(log_path))
with open(log_path, 'wb') as log:
def _log_line(*s): # type: (*str) -> None
output.write_line(*s, stream=log)
_log_line('### version information')
_log_line()
_log_line('```')
_log_line('pre-commit version: {}'.format(C.VERSION))
_log_line('sys.version:')
for line in sys.version.splitlines():
_log_line(' {}'.format(line))
_log_line('sys.executable: {}'.format(sys.executable))
_log_line('os.name: {}'.format(os.name))
_log_line('sys.platform: {}'.format(sys.platform))
_log_line('```')
_log_line()
_log_line('### error information')
_log_line()
_log_line('```')
_log_line(error_msg)
_log_line('```')
_log_line()
_log_line('```')
_log_line(formatted)
_log_line('```')
raise SystemExit(1)
@contextlib.contextmanager
def error_handler():
try:
yield
except (Exception, KeyboardInterrupt) as e:
if isinstance(e, FatalError):
msg = 'An error has occurred'
elif isinstance(e, KeyboardInterrupt):
msg = 'Interrupted (^C)'
else:
msg = 'An unexpected error has occurred'
_log_and_exit(msg, e, traceback.format_exc())