-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathservers.go
110 lines (95 loc) · 1.76 KB
/
servers.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
package geploy
import (
"fmt"
"sync"
)
const (
SequenceMode = 0
ParallelMode = 1
LooseMode = 1 << 1
)
type Group struct {
servers []*Server
flags int
stdouts []string
stderrs []string
errs []error
}
func GroupServers(servers ...*Server) *Group {
return &Group{
servers: servers,
flags: 0,
stdouts: make([]string, len(servers)),
stderrs: make([]string, len(servers)),
errs: make([]error, len(servers)),
}
}
func (g *Group) Sequence() *Group {
g.flags &^= 1
return g
}
func (g *Group) Parallel() *Group {
g.flags |= ParallelMode
return g
}
func (g *Group) Loose(on bool) *Group {
if on {
g.flags |= LooseMode
} else {
g.flags &^= LooseMode
}
return g
}
func (g *Group) Ignore() *Group {
for i := range g.errs {
g.errs[i] = nil
}
return g
}
func (g *Group) checkError() bool {
for i := range g.errs {
if g.errs[i] != nil {
if g.flags&LooseMode == 0 {
return true
} else {
g.errs[i] = nil
}
}
}
return false
}
func (g *Group) Run(cmds ...string) *Group {
if g.checkError() {
return g
}
wg := new(sync.WaitGroup)
mode := g.flags & (SequenceMode | ParallelMode)
for i, s := range g.servers {
switch mode {
case SequenceMode:
g.stdouts[i], g.stderrs[i], g.errs[i] = s.Run(cmds...)
case ParallelMode:
wg.Add(1)
go func(i int, s *Server) {
defer wg.Done()
g.stdouts[i], g.stderrs[i], g.errs[i] = s.Run(cmds...)
}(i, s)
}
}
wg.Wait()
return g
}
func (g *Group) Printf(format string, args ...any) *Group {
if !g.checkError() {
fmt.Printf(format, args...)
}
return g
}
func (g *Group) Println(args ...any) *Group {
if !g.checkError() {
fmt.Println(args...)
}
return g
}
func (g *Group) Errors() []error { return g.errs }
func (g *Group) Error(i int) error { return g.errs[i] }