~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/cleanup.py

  • Committer: Andrew Bennetts
  • Date: 2009-10-15 02:53:30 UTC
  • mto: This revision was merged to the branch mainline in revision 4775.
  • Revision ID: andrew.bennetts@canonical.com-20091015025330-9cwu80sdkttu7v58
Add OperationWithCleanups helper, use it to make commit.py simpler and more robust.

Show diffs side-by-side

added added

removed removed

Lines of Context:
94
94
            seen_error |= _run_cleanup_reporting_errors(func)
95
95
 
96
96
 
 
97
class OperationWithCleanups(object):
 
98
    """A helper for using do_with_cleanups with a dynamic cleanup list.
 
99
 
 
100
    This provides a way to add cleanups while the function-with-cleanups is
 
101
    running.
 
102
 
 
103
    Typical use::
 
104
 
 
105
        operation = OperationWithCleanups(some_func)
 
106
        operation.run(args...)
 
107
 
 
108
    where `some_func` is::
 
109
 
 
110
        def some_func(operation, args, ...)
 
111
            do_something()
 
112
            operation.add_cleanup(something)
 
113
            # etc
 
114
    """
 
115
 
 
116
    def __init__(self, func):
 
117
        self.func = func
 
118
        self.cleanups = []
 
119
 
 
120
    def add_cleanup(self, cleanup_func):
 
121
        """Add a cleanup to run.  Cleanups will be executed in LIFO order."""
 
122
        self.cleanups.insert(0, cleanup_func)
 
123
 
 
124
    def run(self, *args, **kwargs):
 
125
        func = lambda: self.func(self, *args, **kwargs)
 
126
        return do_with_cleanups(func, self.cleanups)
 
127
 
 
128
 
97
129
def do_with_cleanups(func, cleanup_funcs):
98
130
    """Run `func`, then call all the cleanup_funcs.
99
131
 
116
148
       running (but the first exception encountered is still the one
117
149
       propagated).
118
150
 
119
 
    Unike `run_cleanup`, `do_with_cleanups` can propagate an exception from a
 
151
    Unike `_run_cleanup`, `do_with_cleanups` can propagate an exception from a
120
152
    cleanup, but only if there is no exception from func.
121
153
    """
122
154
    # As correct as Python 2.4 allows.