Debian Codegraph @

tests/logexceptions.py

raw
1 # logexceptions.py - Write files containing info about Mercurial exceptions
2 #
3 # Copyright 2017 Olivia Mackall <[email protected]>
4 #
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2 or any later version.
7
8
9 import inspect
10 import os
11 import sys
12 import traceback
13 import uuid
14
15 from mercurial import (
16 dispatch,
17 extensions,
18 )
19
20
21 def handleexception(orig, ui):
22 res = orig(ui)
23
24 if not ui.environ.get(b'HGEXCEPTIONSDIR'):
25 return res
26
27 dest = os.path.join(
28 ui.environ[b'HGEXCEPTIONSDIR'], str(uuid.uuid4()).encode('ascii')
29 )
30
31 exc_type, exc_value, exc_tb = sys.exc_info()
32
33 stack = []
34 tb = exc_tb
35 while tb:
36 stack.append(tb)
37 tb = tb.tb_next
38 stack.reverse()
39
40 hgframe = 'unknown'
41 hgline = 'unknown'
42
43 # Find the first Mercurial frame in the stack.
44 for tb in stack:
45 mod = inspect.getmodule(tb)
46 if not mod.__name__.startswith(('hg', 'mercurial')):
47 continue
48
49 frame = tb.tb_frame
50
51 try:
52 with open(inspect.getsourcefile(tb)) as fh:
53 hgline = fh.readlines()[frame.f_lineno - 1].strip()
54 except (IndexError, OSError):
55 pass
56
57 hgframe = '%s:%d' % (frame.f_code.co_filename, frame.f_lineno)
58 break
59
60 primary = traceback.extract_tb(exc_tb)[-1]
61 primaryframe = '%s:%d' % (primary.filename, primary.lineno)
62
63 with open(dest, 'wb') as fh:
64 parts = [
65 str(exc_value),
66 primaryframe,
67 hgframe,
68 hgline,
69 ui.environ[b'TESTNAME'].decode('utf-8', 'replace'),
70 ]
71 fh.write(b'\0'.join(p.encode('utf-8', 'replace') for p in parts))
72
73
74 def extsetup(ui):
75 extensions.wrapfunction(dispatch, 'handlecommandexception', handleexception)