tty.go 6.9 KB

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