github.com/moby/docker@v26.1.3+incompatible/internal/cleanups/composite.go (about) 1 package cleanups 2 3 import ( 4 "context" 5 6 "github.com/docker/docker/internal/multierror" 7 ) 8 9 type Composite struct { 10 cleanups []func(context.Context) error 11 } 12 13 // Add adds a cleanup to be called. 14 func (c *Composite) Add(f func(context.Context) error) { 15 c.cleanups = append(c.cleanups, f) 16 } 17 18 // Call calls all cleanups in reverse order and returns an error combining all 19 // non-nil errors. 20 func (c *Composite) Call(ctx context.Context) error { 21 err := call(ctx, c.cleanups) 22 c.cleanups = nil 23 return err 24 } 25 26 // Release removes all cleanups, turning Call into a no-op. 27 // Caller still can call the cleanups by calling the returned function 28 // which is equivalent to calling the Call before Release was called. 29 func (c *Composite) Release() func(context.Context) error { 30 cleanups := c.cleanups 31 c.cleanups = nil 32 return func(ctx context.Context) error { 33 return call(ctx, cleanups) 34 } 35 } 36 37 func call(ctx context.Context, cleanups []func(context.Context) error) error { 38 var errs []error 39 for idx := len(cleanups) - 1; idx >= 0; idx-- { 40 c := cleanups[idx] 41 errs = append(errs, c(ctx)) 42 } 43 return multierror.Join(errs...) 44 }