-
Notifications
You must be signed in to change notification settings - Fork 18.7k
/
composite.go
44 lines (37 loc) · 1.09 KB
/
composite.go
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
package cleanups
import (
"context"
"github.com/docker/docker/internal/multierror"
)
type Composite struct {
cleanups []func(context.Context) error
}
// Add adds a cleanup to be called.
func (c *Composite) Add(f func(context.Context) error) {
c.cleanups = append(c.cleanups, f)
}
// Call calls all cleanups in reverse order and returns an error combining all
// non-nil errors.
func (c *Composite) Call(ctx context.Context) error {
err := call(ctx, c.cleanups)
c.cleanups = nil
return err
}
// Release removes all cleanups, turning Call into a no-op.
// Caller still can call the cleanups by calling the returned function
// which is equivalent to calling the Call before Release was called.
func (c *Composite) Release() func(context.Context) error {
cleanups := c.cleanups
c.cleanups = nil
return func(ctx context.Context) error {
return call(ctx, cleanups)
}
}
func call(ctx context.Context, cleanups []func(context.Context) error) error {
var errs []error
for idx := len(cleanups) - 1; idx >= 0; idx-- {
c := cleanups[idx]
errs = append(errs, c(ctx))
}
return multierror.Join(errs...)
}