forked from mattes/migrate
/
pipe.go
77 lines (70 loc) · 1.69 KB
/
pipe.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
// Package pipe has functions for pipe channel handling.
package pipe
import (
"os"
)
// New creates a new pipe. A pipe is basically a channel.
func New() chan interface{} {
return make(chan interface{}, 0)
}
// Close closes a pipe and optionally sends an error
func Close(pipe chan interface{}, err error) {
if err != nil {
pipe <- err
}
close(pipe)
}
// WaitAndRedirect waits for pipe to be closed and
// redirects all messages from pipe to redirectPipe
// while it waits. It also checks if there was an
// interrupt send and will quit gracefully if yes.
func WaitAndRedirect(pipe, redirectPipe chan interface{}, interrupt chan os.Signal) (ok bool) {
errorReceived := false
interruptsReceived := 0
if pipe != nil && redirectPipe != nil {
for {
select {
case <-interrupt:
interruptsReceived += 1
if interruptsReceived > 1 {
os.Exit(5)
} else {
// add white space at beginning for ^C splitting
redirectPipe <- " Aborting after this migration ... Hit again to force quit."
}
case item, ok := <-pipe:
if !ok {
return !errorReceived && interruptsReceived == 0
} else {
redirectPipe <- item
switch item.(type) {
case error:
errorReceived = true
}
}
}
}
}
return !errorReceived && interruptsReceived == 0
}
// ReadErrors selects all received errors and returns them.
// This is helpful for synchronous migration functions.
func ReadErrors(pipe chan interface{}) []error {
err := make([]error, 0)
if pipe != nil {
for {
select {
case item, ok := <-pipe:
if !ok {
return err
} else {
switch item.(type) {
case error:
err = append(err, item.(error))
}
}
}
}
}
return err
}