-
Notifications
You must be signed in to change notification settings - Fork 2.8k
/
decorator.go
62 lines (53 loc) · 1.33 KB
/
decorator.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
// SPDX-License-Identifier: Apache-2.0
// Copyright Authors of Cilium
package cell
import (
"fmt"
"github.com/cilium/cilium/pkg/hive/internal"
)
// Decorate takes a decorator function and a set of cells and returns
// a decorator cell.
//
// A decorator function is a function that takes as arguments objects
// in the hive and returns one or more augmented objects. The cells wrapped
// with a decorator will be provided the returned augmented objects.
//
// Example:
//
// cell.Decorate(
// func(e Example) Example {
// return e.WithMoreMagic()
// },
// cell.Invoke(func(e Example) {
// // e now has more magic
// },
// )
func Decorate(dtor any, cells ...Cell) Cell {
return &decorator{
decorator: dtor,
cells: cells,
}
}
type decorator struct {
decorator any
cells []Cell
}
func (d *decorator) Apply(c container) error {
scope := c.Scope(fmt.Sprintf("(decorate %s)", internal.PrettyType(d.decorator)))
if err := scope.Decorate(d.decorator); err != nil {
return err
}
for _, cell := range d.cells {
if err := cell.Apply(scope); err != nil {
return err
}
}
return nil
}
func (d *decorator) Info(c container) Info {
n := NewInfoNode(fmt.Sprintf("🔀 %s: %s", internal.FuncNameAndLocation(d.decorator), internal.PrettyType(d.decorator)))
for _, cell := range d.cells {
n.Add(cell.Info(c))
}
return n
}