/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/cleanup.py

  • Committer: Andrew Bennetts
  • Date: 2009-10-15 02:19:43 UTC
  • mfrom: (4634.85.12 cleanup-hof)
  • mto: This revision was merged to the branch mainline in revision 4775.
  • Revision ID: andrew.bennetts@canonical.com-20091015021943-l8tuonz6q30tc4t6
Merge do_with_cleanups from cleanup-hof, and drop (or at least make private) everything else from that branch.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2009 Canonical Ltd
 
2
#
 
3
# This program is free software; you can redistribute it and/or modify
 
4
# it under the terms of the GNU General Public License as published by
 
5
# the Free Software Foundation; either version 2 of the License, or
 
6
# (at your option) any later version.
 
7
#
 
8
# This program is distributed in the hope that it will be useful,
 
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
11
# GNU General Public License for more details.
 
12
#
 
13
# You should have received a copy of the GNU General Public License
 
14
# along with this program; if not, write to the Free Software
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
16
 
 
17
"""Helpers for managing cleanup functions and the errors they might raise.
 
18
 
 
19
The usual way to run cleanup code in Python is::
 
20
 
 
21
    try:
 
22
        do_something()
 
23
    finally:
 
24
        cleanup_something()
 
25
 
 
26
However if both `do_something` and `cleanup_something` raise an exception
 
27
Python will forget the original exception and propagate the one from
 
28
cleanup_something.  Unfortunately, this is almost always much less useful than
 
29
the original exception.
 
30
 
 
31
If you want to be certain that the first, and only the first, error is raised,
 
32
then use::
 
33
 
 
34
    do_with_cleanups(do_something, cleanups)
 
35
 
 
36
This is more inconvenient (because you need to make every try block a
 
37
function), but will ensure that the first error encountered is the one raised,
 
38
while also ensuring all cleanups are run.
 
39
"""
 
40
 
 
41
 
 
42
import sys
 
43
from bzrlib import (
 
44
    debug,
 
45
    trace,
 
46
    )
 
47
 
 
48
def _log_cleanup_error(exc):
 
49
    trace.mutter('Cleanup failed:')
 
50
    trace.log_exception_quietly()
 
51
    if 'cleanup' in debug.debug_flags:
 
52
        trace.warning('bzr: warning: Cleanup failed: %s', exc)
 
53
 
 
54
 
 
55
def _run_cleanup(func, *args, **kwargs):
 
56
    """Run func(*args, **kwargs), logging but not propagating any error it
 
57
    raises.
 
58
 
 
59
    :returns: True if func raised no errors, else False.
 
60
    """
 
61
    try:
 
62
        func(*args, **kwargs)
 
63
    except KeyboardInterrupt:
 
64
        raise
 
65
    except Exception, exc:
 
66
        _log_cleanup_error(exc)
 
67
        return False
 
68
    return True
 
69
 
 
70
 
 
71
def _run_cleanup_reporting_errors(func, *args, **kwargs):
 
72
    try:
 
73
        func(*args, **kwargs)
 
74
    except KeyboardInterrupt:
 
75
        raise
 
76
    except Exception, exc:
 
77
        trace.mutter('Cleanup failed:')
 
78
        trace.log_exception_quietly()
 
79
        trace.warning('Cleanup failed: %s', exc)
 
80
        return False
 
81
    return True
 
82
 
 
83
 
 
84
def _run_cleanups(funcs, on_error='log'):
 
85
    """Run a series of cleanup functions.
 
86
 
 
87
    :param errors: One of 'log', 'warn first', 'warn all'
 
88
    """
 
89
    seen_error = False
 
90
    for func in funcs:
 
91
        if on_error == 'log' or (on_error == 'warn first' and seen_error):
 
92
            seen_error |= _run_cleanup(func)
 
93
        else:
 
94
            seen_error |= _run_cleanup_reporting_errors(func)
 
95
 
 
96
 
 
97
def do_with_cleanups(func, cleanup_funcs):
 
98
    """Run `func`, then call all the cleanup_funcs.
 
99
 
 
100
    All the cleanup_funcs are guaranteed to be run.  The first exception raised
 
101
    by func or any of the cleanup_funcs is the one that will be propagted by
 
102
    this function (subsequent errors are caught and logged).
 
103
 
 
104
    Conceptually similar to::
 
105
 
 
106
        try:
 
107
            return func()
 
108
        finally:
 
109
            for cleanup in cleanup_funcs:
 
110
                cleanup()
 
111
 
 
112
    It avoids several problems with using try/finally directly:
 
113
     * an exception from func will not be obscured by a subsequent exception
 
114
       from a cleanup.
 
115
     * an exception from a cleanup will not prevent other cleanups from
 
116
       running (but the first exception encountered is still the one
 
117
       propagated).
 
118
 
 
119
    Unike `run_cleanup`, `do_with_cleanups` can propagate an exception from a
 
120
    cleanup, but only if there is no exception from func.
 
121
    """
 
122
    # As correct as Python 2.4 allows.
 
123
    try:
 
124
        result = func()
 
125
    except:
 
126
        # We have an exception from func already, so suppress cleanup errors.
 
127
        _run_cleanups(cleanup_funcs)
 
128
        raise
 
129
    else:
 
130
        # No exception from func, so allow the first exception from
 
131
        # cleanup_funcs to propagate if one occurs (but only after running all
 
132
        # of them).
 
133
        exc_info = None
 
134
        for cleanup in cleanup_funcs:
 
135
            # XXX: Hmm, if KeyboardInterrupt arrives at exactly this line, we
 
136
            # won't run all cleanups... perhaps we should temporarily install a
 
137
            # SIGINT handler?
 
138
            if exc_info is None:
 
139
                try:
 
140
                    cleanup()
 
141
                except:
 
142
                    # This is the first cleanup to fail, so remember its
 
143
                    # details.
 
144
                    exc_info = sys.exc_info()
 
145
            else:
 
146
                # We already have an exception to propagate, so log any errors
 
147
                # but don't propagate them.
 
148
                _run_cleanup(cleanup)
 
149
        if exc_info is not None:
 
150
            raise exc_info[0], exc_info[1], exc_info[2]
 
151
        # No error, so we can return the result
 
152
        return result
 
153
 
 
154