File: tty.go

package info (click to toggle)
docker-compose 2.32.4-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 3,300 kB
  • sloc: makefile: 113; sh: 2
file content (348 lines) | stat: -rw-r--r-- 7,918 bytes parent folder | download
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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
/*
   Copyright 2020 Docker Compose CLI authors

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

package progress

import (
	"context"
	"fmt"
	"io"
	"strings"
	"sync"
	"time"

	"github.com/docker/compose/v2/pkg/api"
	"github.com/docker/compose/v2/pkg/utils"

	"github.com/buger/goterm"
	"github.com/docker/go-units"
	"github.com/morikuni/aec"
)

type ttyWriter struct {
	out             io.Writer
	events          map[string]Event
	eventIDs        []string
	repeated        bool
	numLines        int
	done            chan bool
	mtx             *sync.Mutex
	tailEvents      []string
	dryRun          bool
	skipChildEvents bool
	progressTitle   string
}

func (w *ttyWriter) Start(ctx context.Context) error {
	ticker := time.NewTicker(100 * time.Millisecond)
	defer ticker.Stop()

	for {
		select {
		case <-ctx.Done():
			w.print()
			w.printTailEvents()
			return ctx.Err()
		case <-w.done:
			w.print()
			w.printTailEvents()
			return nil
		case <-ticker.C:
			w.print()
		}
	}
}

func (w *ttyWriter) Stop() {
	w.done <- true
}

func (w *ttyWriter) Event(e Event) {
	w.mtx.Lock()
	defer w.mtx.Unlock()
	w.event(e)
}

func (w *ttyWriter) event(e Event) {
	if !utils.StringContains(w.eventIDs, e.ID) {
		w.eventIDs = append(w.eventIDs, e.ID)
	}
	if _, ok := w.events[e.ID]; ok {
		last := w.events[e.ID]
		switch e.Status {
		case Done, Error, Warning:
			if last.Status != e.Status {
				last.stop()
			}
		case Working:
			last.hasMore()
		}
		last.Status = e.Status
		last.Text = e.Text
		last.StatusText = e.StatusText
		// progress can only go up
		if e.Total > last.Total {
			last.Total = e.Total
		}
		if e.Current > last.Current {
			last.Current = e.Current
		}
		if e.Percent > last.Percent {
			last.Percent = e.Percent
		}
		// allow set/unset of parent, but not swapping otherwise prompt is flickering
		if last.ParentID == "" || e.ParentID == "" {
			last.ParentID = e.ParentID
		}
		w.events[e.ID] = last
	} else {
		e.startTime = time.Now()
		e.spinner = newSpinner()
		if e.Status == Done || e.Status == Error {
			e.stop()
		}
		w.events[e.ID] = e
	}
}

func (w *ttyWriter) Events(events []Event) {
	w.mtx.Lock()
	defer w.mtx.Unlock()
	for _, e := range events {
		w.event(e)
	}
}

func (w *ttyWriter) TailMsgf(msg string, args ...interface{}) {
	w.mtx.Lock()
	defer w.mtx.Unlock()
	msgWithPrefix := msg
	if w.dryRun {
		msgWithPrefix = strings.TrimSpace(api.DRYRUN_PREFIX + msg)
	}
	w.tailEvents = append(w.tailEvents, fmt.Sprintf(msgWithPrefix, args...))
}

func (w *ttyWriter) printTailEvents() {
	w.mtx.Lock()
	defer w.mtx.Unlock()
	for _, msg := range w.tailEvents {
		_, _ = fmt.Fprintln(w.out, msg)
	}
}

func (w *ttyWriter) print() { //nolint:gocyclo
	w.mtx.Lock()
	defer w.mtx.Unlock()
	if len(w.eventIDs) == 0 {
		return
	}
	terminalWidth := goterm.Width()
	b := aec.EmptyBuilder
	for i := 0; i <= w.numLines; i++ {
		b = b.Up(1)
	}
	if !w.repeated {
		b = b.Down(1)
	}
	w.repeated = true
	_, _ = fmt.Fprint(w.out, b.Column(0).ANSI)

	// Hide the cursor while we are printing
	_, _ = fmt.Fprint(w.out, aec.Hide)
	defer func() {
		_, _ = fmt.Fprint(w.out, aec.Show)
	}()

	firstLine := fmt.Sprintf("[+] %s %d/%d", w.progressTitle, numDone(w.events), len(w.events))
	if w.numLines != 0 && numDone(w.events) == w.numLines {
		firstLine = DoneColor(firstLine)
	}
	_, _ = fmt.Fprintln(w.out, firstLine)

	var statusPadding int
	for _, v := range w.eventIDs {
		event := w.events[v]
		l := len(fmt.Sprintf("%s %s", event.ID, event.Text))
		if statusPadding < l {
			statusPadding = l
		}
		if event.ParentID != "" {
			statusPadding -= 2
		}
	}

	if len(w.eventIDs) > goterm.Height()-2 {
		w.skipChildEvents = true
	}
	numLines := 0
	for _, v := range w.eventIDs {
		event := w.events[v]
		if event.ParentID != "" {
			continue
		}
		line := w.lineText(event, "", terminalWidth, statusPadding, w.dryRun)
		_, _ = fmt.Fprint(w.out, line)
		numLines++
		for _, v := range w.eventIDs {
			ev := w.events[v]
			if ev.ParentID == event.ID {
				if w.skipChildEvents {
					continue
				}
				line := w.lineText(ev, "  ", terminalWidth, statusPadding, w.dryRun)
				_, _ = fmt.Fprint(w.out, line)
				numLines++
			}
		}
	}
	for i := numLines; i < w.numLines; i++ {
		if numLines < goterm.Height()-2 {
			_, _ = fmt.Fprintln(w.out, strings.Repeat(" ", terminalWidth))
			numLines++
		}
	}
	w.numLines = numLines
}

func (w *ttyWriter) lineText(event Event, pad string, terminalWidth, statusPadding int, dryRun bool) string {
	endTime := time.Now()
	if event.Status != Working {
		endTime = event.startTime
		if (event.endTime != time.Time{}) {
			endTime = event.endTime
		}
	}
	prefix := ""
	if dryRun {
		prefix = PrefixColor(api.DRYRUN_PREFIX)
	}

	elapsed := endTime.Sub(event.startTime).Seconds()

	var (
		hideDetails bool
		total       int64
		current     int64
		completion  []string
	)

	// only show the aggregated progress while the root operation is in-progress
	if parent := event; parent.Status == Working {
		for _, v := range w.eventIDs {
			child := w.events[v]
			if child.ParentID == parent.ID {
				if child.Status == Working && child.Total == 0 {
					// we don't have totals available for all the child events
					// so don't show the total progress yet
					hideDetails = true
				}
				total += child.Total
				current += child.Current
				completion = append(completion, percentChars[(len(percentChars)-1)*child.Percent/100])
			}
		}
	}

	// don't try to show detailed progress if we don't have any idea
	if total == 0 {
		hideDetails = true
	}

	var txt string
	if len(completion) > 0 {
		var details string
		if !hideDetails {
			details = fmt.Sprintf(" %7s / %-7s", units.HumanSize(float64(current)), units.HumanSize(float64(total)))
		}
		txt = fmt.Sprintf("%s [%s]%s %s",
			event.ID,
			SuccessColor(strings.Join(completion, "")),
			details,
			event.Text,
		)
	} else {
		txt = fmt.Sprintf("%s %s", event.ID, event.Text)
	}
	textLen := len(txt)
	padding := statusPadding - textLen
	if padding < 0 {
		padding = 0
	}
	// calculate the max length for the status text, on errors it
	// is 2-3 lines long and breaks the line formatting
	maxStatusLen := terminalWidth - textLen - statusPadding - 15
	status := event.StatusText
	// in some cases (debugging under VS Code), terminalWidth is set to zero by goterm.Width() ; ensuring we don't tweak strings with negative char index
	if maxStatusLen > 0 && len(status) > maxStatusLen {
		status = status[:maxStatusLen] + "..."
	}
	text := fmt.Sprintf("%s %s%s %s%s %s",
		pad,
		event.Spinner(),
		prefix,
		txt,
		strings.Repeat(" ", padding),
		event.Status.colorFn()(status),
	)
	timer := fmt.Sprintf("%.1fs ", elapsed)
	o := align(text, TimerColor(timer), terminalWidth)

	return o
}

func numDone(events map[string]Event) int {
	i := 0
	for _, e := range events {
		if e.Status != Working {
			i++
		}
	}
	return i
}

func align(l, r string, w int) string {
	ll := lenAnsi(l)
	lr := lenAnsi(r)
	pad := ""
	count := w - ll - lr
	if count > 0 {
		pad = strings.Repeat(" ", count)
	}
	return fmt.Sprintf("%s%s%s\n", l, pad, r)
}

// lenAnsi count of user-perceived characters in ANSI string.
func lenAnsi(s string) int {
	length := 0
	ansiCode := false
	for _, r := range s {
		if r == '\x1b' {
			ansiCode = true
			continue
		}
		if ansiCode && r == 'm' {
			ansiCode = false
			continue
		}
		if !ansiCode {
			length++
		}
	}
	return length
}

var percentChars = strings.Split("⠀⡀⣀⣄⣤⣦⣶⣷⣿", "")