tty.go 7.1 KB

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