-
Notifications
You must be signed in to change notification settings - Fork 2.8k
/
provide.go
98 lines (87 loc) · 2.35 KB
/
provide.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
// SPDX-License-Identifier: Apache-2.0
// Copyright Authors of Cilium
package cell
import (
"fmt"
"sort"
"strings"
"go.uber.org/dig"
"github.com/cilium/cilium/pkg/hive/internal"
)
// provider is a set of constructors
type provider struct {
ctors []any
infos []dig.ProvideInfo
export bool
}
func (p *provider) Apply(c container) error {
p.infos = make([]dig.ProvideInfo, len(p.ctors))
for i, ctor := range p.ctors {
if err := c.Provide(ctor, dig.Export(p.export), dig.FillProvideInfo(&p.infos[i])); err != nil {
return err
}
}
return nil
}
func (p *provider) Info(container) Info {
n := &InfoNode{}
for i, ctor := range p.ctors {
info := p.infos[i]
privateSymbol := ""
if !p.export {
privateSymbol = "🔒️"
}
ctorNode := NewInfoNode(fmt.Sprintf("🚧%s %s", privateSymbol, internal.FuncNameAndLocation(ctor)))
ctorNode.condensed = true
var ins, outs []string
for _, input := range info.Inputs {
ins = append(ins, internal.TrimName(input.String()))
}
sort.Strings(ins)
for _, output := range info.Outputs {
outs = append(outs, internal.TrimName(output.String()))
}
sort.Strings(outs)
if len(ins) > 0 {
ctorNode.AddLeaf("⇨ %s", strings.Join(ins, ", "))
}
ctorNode.AddLeaf("⇦ %s", strings.Join(outs, ", "))
n.Add(ctorNode)
}
return n
}
// Provide constructs a new cell with the given constructors.
// Constructor is any function that takes zero or more parameters and returns
// one or more values and optionally an error. For example, the following forms
// are accepted:
//
// func() A
// func(A, B, C) (D, error).
//
// If the constructor depends on a type that is not provided by any constructor
// the hive will fail to run with an error pointing at the missing type.
//
// A constructor can also take as parameter a structure of parameters annotated
// with `cell.In`, or return a struct annotated with `cell.Out`:
//
// type params struct {
// cell.In
// Flower *Flower
// Sun *Sun
// }
//
// type out struct {
// cell.Out
// Honey *Honey
// Nectar *Nectar
// }
//
// func newBee(params) (out, error)
func Provide(ctors ...any) Cell {
return &provider{ctors: ctors, export: true}
}
// ProvidePrivate is like Provide, but the constructed objects are only
// available within the module it is defined and nested modules.
func ProvidePrivate(ctors ...any) Cell {
return &provider{ctors: ctors, export: false}
}