tty.go 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. /*
  2. Copyright 2020 Docker Compose CLI authors
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package progress
  14. import (
  15. "context"
  16. "fmt"
  17. "io"
  18. "strings"
  19. "sync"
  20. "time"
  21. "github.com/docker/compose/v2/pkg/api"
  22. "github.com/docker/compose/v2/pkg/utils"
  23. "github.com/buger/goterm"
  24. "github.com/docker/go-units"
  25. "github.com/morikuni/aec"
  26. )
  27. type ttyWriter struct {
  28. out io.Writer
  29. events map[string]Event
  30. eventIDs []string
  31. repeated bool
  32. numLines int
  33. done chan bool
  34. mtx *sync.Mutex
  35. tailEvents []string
  36. dryRun bool
  37. skipChildEvents bool
  38. }
  39. func (w *ttyWriter) Start(ctx context.Context) error {
  40. ticker := time.NewTicker(100 * time.Millisecond)
  41. defer ticker.Stop()
  42. for {
  43. select {
  44. case <-ctx.Done():
  45. w.print()
  46. w.printTailEvents()
  47. return ctx.Err()
  48. case <-w.done:
  49. w.print()
  50. w.printTailEvents()
  51. return nil
  52. case <-ticker.C:
  53. w.print()
  54. }
  55. }
  56. }
  57. func (w *ttyWriter) Stop() {
  58. w.done <- true
  59. }
  60. func (w *ttyWriter) Event(e Event) {
  61. w.mtx.Lock()
  62. defer w.mtx.Unlock()
  63. if !utils.StringContains(w.eventIDs, e.ID) {
  64. w.eventIDs = append(w.eventIDs, e.ID)
  65. }
  66. if _, ok := w.events[e.ID]; ok {
  67. last := w.events[e.ID]
  68. switch e.Status {
  69. case Done, Error, Warning:
  70. if last.Status != e.Status {
  71. last.stop()
  72. }
  73. }
  74. last.Status = e.Status
  75. last.Text = e.Text
  76. last.StatusText = e.StatusText
  77. last.Total = e.Total
  78. last.Current = e.Current
  79. last.Percent = e.Percent
  80. // allow set/unset of parent, but not swapping otherwise prompt is flickering
  81. if last.ParentID == "" || e.ParentID == "" {
  82. last.ParentID = e.ParentID
  83. }
  84. w.events[e.ID] = last
  85. } else {
  86. e.startTime = time.Now()
  87. e.spinner = newSpinner()
  88. if e.Status == Done || e.Status == Error {
  89. e.stop()
  90. }
  91. w.events[e.ID] = e
  92. }
  93. }
  94. func (w *ttyWriter) Events(events []Event) {
  95. for _, e := range events {
  96. w.Event(e)
  97. }
  98. }
  99. func (w *ttyWriter) TailMsgf(msg string, args ...interface{}) {
  100. w.mtx.Lock()
  101. defer w.mtx.Unlock()
  102. msgWithPrefix := msg
  103. if w.dryRun {
  104. msgWithPrefix = strings.TrimSpace(api.DRYRUN_PREFIX + msg)
  105. }
  106. w.tailEvents = append(w.tailEvents, fmt.Sprintf(msgWithPrefix, args...))
  107. }
  108. func (w *ttyWriter) printTailEvents() {
  109. w.mtx.Lock()
  110. defer w.mtx.Unlock()
  111. for _, msg := range w.tailEvents {
  112. fmt.Fprintln(w.out, msg)
  113. }
  114. }
  115. func (w *ttyWriter) print() { //nolint:gocyclo
  116. w.mtx.Lock()
  117. defer w.mtx.Unlock()
  118. if len(w.eventIDs) == 0 {
  119. return
  120. }
  121. terminalWidth := goterm.Width()
  122. b := aec.EmptyBuilder
  123. for i := 0; i <= w.numLines; i++ {
  124. b = b.Up(1)
  125. }
  126. if !w.repeated {
  127. b = b.Down(1)
  128. }
  129. w.repeated = true
  130. fmt.Fprint(w.out, b.Column(0).ANSI)
  131. // Hide the cursor while we are printing
  132. fmt.Fprint(w.out, aec.Hide)
  133. defer fmt.Fprint(w.out, aec.Show)
  134. firstLine := fmt.Sprintf("[+] Running %d/%d", numDone(w.events), w.numLines)
  135. if w.numLines != 0 && numDone(w.events) == w.numLines {
  136. firstLine = DoneColor(firstLine)
  137. }
  138. fmt.Fprintln(w.out, firstLine)
  139. var statusPadding int
  140. for _, v := range w.eventIDs {
  141. event := w.events[v]
  142. l := len(fmt.Sprintf("%s %s", event.ID, event.Text))
  143. if statusPadding < l {
  144. statusPadding = l
  145. }
  146. if event.ParentID != "" {
  147. statusPadding -= 2
  148. }
  149. }
  150. if len(w.eventIDs) > goterm.Height()-2 {
  151. w.skipChildEvents = true
  152. }
  153. numLines := 0
  154. for _, v := range w.eventIDs {
  155. event := w.events[v]
  156. if event.ParentID != "" {
  157. continue
  158. }
  159. line := w.lineText(event, "", terminalWidth, statusPadding, w.dryRun)
  160. fmt.Fprint(w.out, line)
  161. numLines++
  162. for _, v := range w.eventIDs {
  163. ev := w.events[v]
  164. if ev.ParentID == event.ID {
  165. if w.skipChildEvents {
  166. continue
  167. }
  168. line := w.lineText(ev, " ", terminalWidth, statusPadding, w.dryRun)
  169. fmt.Fprint(w.out, line)
  170. numLines++
  171. }
  172. }
  173. }
  174. for i := numLines; i < w.numLines; i++ {
  175. if numLines < goterm.Height()-2 {
  176. fmt.Fprintln(w.out, strings.Repeat(" ", terminalWidth))
  177. numLines++
  178. }
  179. }
  180. w.numLines = numLines
  181. }
  182. func (w *ttyWriter) lineText(event Event, pad string, terminalWidth, statusPadding int, dryRun bool) string {
  183. endTime := time.Now()
  184. if event.Status != Working {
  185. endTime = event.startTime
  186. if (event.endTime != time.Time{}) {
  187. endTime = event.endTime
  188. }
  189. }
  190. prefix := ""
  191. if dryRun {
  192. prefix = PrefixColor(api.DRYRUN_PREFIX)
  193. }
  194. elapsed := endTime.Sub(event.startTime).Seconds()
  195. var (
  196. total int64
  197. current int64
  198. completion []string
  199. )
  200. for _, v := range w.eventIDs {
  201. ev := w.events[v]
  202. if ev.ParentID == event.ID {
  203. total += ev.Total
  204. current += ev.Current
  205. completion = append(completion, percentChars[(len(percentChars)-1)*ev.Percent/100])
  206. }
  207. }
  208. var txt string
  209. if len(completion) > 0 {
  210. txt = fmt.Sprintf("%s %s [%s] %7s/%-7s %s",
  211. event.ID,
  212. CountColor(fmt.Sprintf("%d layers", len(completion))),
  213. SuccessColor(strings.Join(completion, "")),
  214. units.HumanSize(float64(current)), units.HumanSize(float64(total)),
  215. event.Text)
  216. } else {
  217. txt = fmt.Sprintf("%s %s", event.ID, event.Text)
  218. }
  219. textLen := len(txt)
  220. padding := statusPadding - textLen
  221. if padding < 0 {
  222. padding = 0
  223. }
  224. // calculate the max length for the status text, on errors it
  225. // is 2-3 lines long and breaks the line formatting
  226. maxStatusLen := terminalWidth - textLen - statusPadding - 15
  227. status := event.StatusText
  228. // 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
  229. if maxStatusLen > 0 && len(status) > maxStatusLen {
  230. status = status[:maxStatusLen] + "..."
  231. }
  232. text := fmt.Sprintf("%s %s%s %s%s %s",
  233. pad,
  234. event.Spinner(),
  235. prefix,
  236. txt,
  237. strings.Repeat(" ", padding),
  238. event.Status.colorFn()(status),
  239. )
  240. timer := fmt.Sprintf("%.1fs ", elapsed)
  241. o := align(text, TimerColor(timer), terminalWidth)
  242. return o
  243. }
  244. func numDone(events map[string]Event) int {
  245. i := 0
  246. for _, e := range events {
  247. if e.Status != Working {
  248. i++
  249. }
  250. }
  251. return i
  252. }
  253. func align(l, r string, w int) string {
  254. ll := lenAnsi(l)
  255. lr := lenAnsi(r)
  256. pad := ""
  257. count := w - ll - lr
  258. if count > 0 {
  259. pad = strings.Repeat(" ", count)
  260. }
  261. return fmt.Sprintf("%s%s%s\n", l, pad, r)
  262. }
  263. // lenAnsi count of user-perceived characters in ANSI string.
  264. func lenAnsi(s string) int {
  265. length := 0
  266. ansiCode := false
  267. for _, r := range s {
  268. if r == '\x1b' {
  269. ansiCode = true
  270. continue
  271. }
  272. if ansiCode && r == 'm' {
  273. ansiCode = false
  274. continue
  275. }
  276. if !ansiCode {
  277. length++
  278. }
  279. }
  280. return length
  281. }
  282. var (
  283. percentChars = strings.Split("⠀⡀⣀⣄⣤⣦⣶⣷⣿", "")
  284. )