-
Notifications
You must be signed in to change notification settings - Fork 0
/
runcmdopt.go
executable file
·120 lines (98 loc) · 2.35 KB
/
runcmdopt.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
package runcmdopt
import (
"reflect"
"github.com/Vincent20101/mongo-go-driver/core/readpref"
)
var runCmdBundle = new(RunCmdBundle)
// Option represents a RunCommand option.
type Option interface {
runCmdOption()
}
// optionFunc adds the option to the RunCmd instance.
type optionFunc func(*RunCmd) error
// RunCmd represents a run command.
type RunCmd struct {
ReadPreference *readpref.ReadPref
}
// RunCmdBundle is a bundle of RunCommand options.
type RunCmdBundle struct {
option Option
next *RunCmdBundle
}
func (*RunCmdBundle) runCmdOption() {}
func (optionFunc) runCmdOption() {}
// BundleRunCmd bundles RunCommand options
func BundleRunCmd(opts ...Option) *RunCmdBundle {
head := runCmdBundle
for _, opt := range opts {
newBundle := RunCmdBundle{
option: opt,
next: head,
}
head = &newBundle
}
return head
}
// ReadPreference sets the read preference.
func (rcb *RunCmdBundle) ReadPreference(rp *readpref.ReadPref) *RunCmdBundle {
return &RunCmdBundle{
option: ReadPreference(rp),
next: rcb,
}
}
// Unbundle unbundles the options, returning a RunCmd instance.
func (rcb *RunCmdBundle) Unbundle() (*RunCmd, error) {
database := &RunCmd{}
err := rcb.unbundle(database)
if err != nil {
return nil, err
}
return database, nil
}
// Helper that recursively unwraps the bundle.
func (rcb *RunCmdBundle) unbundle(database *RunCmd) error {
if rcb == nil {
return nil
}
for head := rcb; head != nil && head.option != nil; head = head.next {
var err error
switch opt := head.option.(type) {
case *RunCmdBundle:
err = opt.unbundle(database) // add all bundle's options to database
case optionFunc:
err = opt(database) // add option to database
default:
return nil
}
if err != nil {
return err
}
}
return nil
}
// String implements the Stringer interface
func (rcb *RunCmdBundle) String() string {
if rcb == nil {
return ""
}
str := ""
for head := rcb; head != nil && head.option != nil; head = head.next {
switch opt := head.option.(type) {
case *RunCmdBundle:
str += opt.String()
case optionFunc:
str += reflect.TypeOf(opt).String() + "\n"
}
}
return str
}
// ReadPreference sets the read preference.
func ReadPreference(rp *readpref.ReadPref) Option {
return optionFunc(
func(rc *RunCmd) error {
if rc.ReadPreference == nil {
rc.ReadPreference = rp
}
return nil
})
}