-
Notifications
You must be signed in to change notification settings - Fork 233
/
remote.go
96 lines (77 loc) · 1.75 KB
/
remote.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
package builds
import (
"context"
"regexp"
"strings"
"time"
"github.com/superfly/flyctl/api"
)
type BuildMonitor struct {
client *api.Client
buildID string
err error
build *api.Build
}
func NewBuildMonitor(buildID string, client *api.Client) *BuildMonitor {
return &BuildMonitor{client: client, buildID: buildID}
}
func (b *BuildMonitor) Err() error {
return b.err
}
func (b *BuildMonitor) Build() *api.Build {
return b.build
}
func (b *BuildMonitor) Status() string {
return b.build.Status
}
func (b *BuildMonitor) Failed() bool {
return b.Status() == "failed"
}
func (b *BuildMonitor) Logs(ctx context.Context) <-chan string {
out := make(chan string, 0)
go func() {
defer close(out)
pos := 0
var interval time.Duration
for {
select {
case <-time.After(interval):
interval = 1 * time.Second
build, err := fetchBuild(b.client, b.buildID)
if err != nil {
b.err = err
return
}
b.build = build
lines := strings.Split(strings.TrimSpace(build.Logs), "\n")
if len(lines) > pos {
for _, line := range lines[pos:] {
out <- cleanLogLine(line)
// out <- strings.Join(cleanLogLine(line), "\n")
}
pos = len(lines)
}
if !build.InProgress {
return
}
case <-ctx.Done():
b.err = ctx.Err()
return
}
}
}()
return out
}
func fetchBuild(client *api.Client, buildID string) (build *api.Build, err error) {
for attempts := 0; attempts < 3; attempts++ {
build, err = client.GetBuild(buildID)
if err == nil {
break
}
}
return build, err
}
var timestampPrefixPattern = regexp.MustCompile(`^\[\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d{2}:\d{2}\]\s`)
func cleanLogLine(line string) string {
return timestampPrefixPattern.ReplaceAllString(line, "")
}