File: composite.go

package info (click to toggle)
docker.io 27.5.1%2Bdfsg4-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 67,384 kB
  • sloc: sh: 5,847; makefile: 1,146; ansic: 664; python: 162; asm: 133
file content (44 lines) | stat: -rw-r--r-- 1,119 bytes parent folder | download | duplicates (5)
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...)
}