~verterok/bzr-xmloutput/threads

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
from bzrlib.lazy_import import lazy_import
lazy_import(globals(), """
import bzrlib
from bzrlib import (
    errors,
    debug,
    )
""")

from bzrlib.xml_serializer import _escape_cdata
from bzrlib import trace

class XMLError(errors.BzrError):
    internal_error = False

    def __init__(self, error):
        self.error = error

    def __str__(self):
        xml = '<?xml version="1.0" encoding="%s"?>' % bzrlib.user_encoding
        try:
            xml += '<error>%s</error>' % self.get_cause_xml()
        except Exception, e:
            xml += '<error><message>%s</message></error>' % \
                _escape_cdata(str(e))
        return xml
    
    def get_cause_xml(self):
        s = '<class>%s</class><dict>%s</dict>' \
                '<message>%s</message>' \
                % (self.error.__class__.__name__,
                   self._get_dict_as_xml(self.error.__dict__),
                   _escape_cdata(str(self.error)))
        return s
                   
    def _get_dict_as_xml(self, dict):
        return ''.join(['<key>%s</key><value>%s</value>' % \
            (_escape_cdata(key), 
            _escape_cdata(str(val))) \
                    for key, val in dict.iteritems() if val is not None])


def report_exception(exc_info, err_file): 
    """ replace the default report_exception with a custom one that returns 
    a xml representation of the error. 

    :return: The appropriate exit code for this error.
    """
    exc_type, exc_object, exc_tb = exc_info
    # Log the full traceback to ~/.bzr.log
    trace.log_exception_quietly()
    err_file.write(str(XMLError(exc_object)))
    return errors.EXIT_ERROR


def handle_error_xml(func):

    def xml_error_handling(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except:
            import sys, os
            exitcode = report_exception(sys.exc_info(), sys.stderr)
            if os.environ.get('BZR_PDB'):
                print '**** entering debugger'
                import pdb
                pdb.post_mortem(sys.exc_traceback)
            return exitcode
    
    return xml_error_handling