tty.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  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. "runtime"
  19. "strings"
  20. "sync"
  21. "time"
  22. "github.com/docker/compose/v2/pkg/utils"
  23. "github.com/buger/goterm"
  24. "github.com/morikuni/aec"
  25. )
  26. type ttyWriter struct {
  27. out io.Writer
  28. events map[string]Event
  29. eventIDs []string
  30. repeated bool
  31. numLines int
  32. done chan bool
  33. mtx *sync.Mutex
  34. tailEvents []string
  35. }
  36. func (w *ttyWriter) Start(ctx context.Context) error {
  37. ticker := time.NewTicker(100 * time.Millisecond)
  38. defer ticker.Stop()
  39. for {
  40. select {
  41. case <-ctx.Done():
  42. w.print()
  43. w.printTailEvents()
  44. return ctx.Err()
  45. case <-w.done:
  46. w.print()
  47. w.printTailEvents()
  48. return nil
  49. case <-ticker.C:
  50. w.print()
  51. }
  52. }
  53. }
  54. func (w *ttyWriter) Stop() {
  55. w.done <- true
  56. }
  57. func (w *ttyWriter) Event(e Event) {
  58. w.mtx.Lock()
  59. defer w.mtx.Unlock()
  60. if !utils.StringContains(w.eventIDs, e.ID) {
  61. w.eventIDs = append(w.eventIDs, e.ID)
  62. }
  63. if _, ok := w.events[e.ID]; ok {
  64. last := w.events[e.ID]
  65. switch e.Status {
  66. case Done, Error, Warning:
  67. if last.Status != e.Status {
  68. last.stop()
  69. }
  70. }
  71. last.Status = e.Status
  72. last.Text = e.Text
  73. last.StatusText = e.StatusText
  74. // allow set/unset of parent, but not swapping otherwise prompt is flickering
  75. if last.ParentID == "" || e.ParentID == "" {
  76. last.ParentID = e.ParentID
  77. }
  78. w.events[e.ID] = last
  79. } else {
  80. e.startTime = time.Now()
  81. e.spinner = newSpinner()
  82. if e.Status == Done || e.Status == Error {
  83. e.stop()
  84. }
  85. w.events[e.ID] = e
  86. }
  87. }
  88. func (w *ttyWriter) Events(events []Event) {
  89. for _, e := range events {
  90. w.Event(e)
  91. }
  92. }
  93. func (w *ttyWriter) TailMsgf(msg string, args ...interface{}) {
  94. w.mtx.Lock()
  95. defer w.mtx.Unlock()
  96. w.tailEvents = append(w.tailEvents, fmt.Sprintf(msg, args...))
  97. }
  98. func (w *ttyWriter) printTailEvents() {
  99. w.mtx.Lock()
  100. defer w.mtx.Unlock()
  101. for _, msg := range w.tailEvents {
  102. fmt.Fprintln(w.out, msg)
  103. }
  104. }
  105. func (w *ttyWriter) print() { //nolint:gocyclo
  106. w.mtx.Lock()
  107. defer w.mtx.Unlock()
  108. if len(w.eventIDs) == 0 {
  109. return
  110. }
  111. terminalWidth := goterm.Width()
  112. b := aec.EmptyBuilder
  113. for i := 0; i <= w.numLines; i++ {
  114. b = b.Up(1)
  115. }
  116. if !w.repeated {
  117. b = b.Down(1)
  118. }
  119. w.repeated = true
  120. fmt.Fprint(w.out, b.Column(0).ANSI)
  121. // Hide the cursor while we are printing
  122. fmt.Fprint(w.out, aec.Hide)
  123. defer fmt.Fprint(w.out, aec.Show)
  124. firstLine := fmt.Sprintf("[+] Running %d/%d", numDone(w.events), w.numLines)
  125. if w.numLines != 0 && numDone(w.events) == w.numLines {
  126. firstLine = aec.Apply(firstLine, aec.BlueF)
  127. }
  128. fmt.Fprintln(w.out, firstLine)
  129. var statusPadding int
  130. for _, v := range w.eventIDs {
  131. event := w.events[v]
  132. l := len(fmt.Sprintf("%s %s", event.ID, event.Text))
  133. if statusPadding < l {
  134. statusPadding = l
  135. }
  136. if event.ParentID != "" {
  137. statusPadding -= 2
  138. }
  139. }
  140. skipChildEvents := false
  141. if len(w.eventIDs) > goterm.Height()-2 {
  142. skipChildEvents = true
  143. }
  144. numLines := 0
  145. for _, v := range w.eventIDs {
  146. event := w.events[v]
  147. if event.ParentID != "" {
  148. continue
  149. }
  150. line := lineText(event, "", terminalWidth, statusPadding, runtime.GOOS != "windows")
  151. fmt.Fprint(w.out, line)
  152. numLines++
  153. for _, v := range w.eventIDs {
  154. ev := w.events[v]
  155. if ev.ParentID == event.ID {
  156. if skipChildEvents {
  157. continue
  158. }
  159. line := lineText(ev, " ", terminalWidth, statusPadding, runtime.GOOS != "windows")
  160. fmt.Fprint(w.out, line)
  161. numLines++
  162. }
  163. }
  164. }
  165. for i := numLines; i < w.numLines; i++ {
  166. if numLines < goterm.Height()-2 {
  167. fmt.Fprintln(w.out, strings.Repeat(" ", terminalWidth))
  168. numLines++
  169. }
  170. }
  171. w.numLines = numLines
  172. }
  173. func lineText(event Event, pad string, terminalWidth, statusPadding int, color bool) string {
  174. endTime := time.Now()
  175. if event.Status != Working {
  176. endTime = event.startTime
  177. if (event.endTime != time.Time{}) {
  178. endTime = event.endTime
  179. }
  180. }
  181. elapsed := endTime.Sub(event.startTime).Seconds()
  182. textLen := len(fmt.Sprintf("%s %s", event.ID, event.Text))
  183. padding := statusPadding - textLen
  184. if padding < 0 {
  185. padding = 0
  186. }
  187. // calculate the max length for the status text, on errors it
  188. // is 2-3 lines long and breaks the line formatting
  189. maxStatusLen := terminalWidth - textLen - statusPadding - 15
  190. status := event.StatusText
  191. // 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
  192. if maxStatusLen > 0 && len(status) > maxStatusLen {
  193. status = status[:maxStatusLen] + "..."
  194. }
  195. text := fmt.Sprintf("%s %s %s %s%s %s",
  196. pad,
  197. event.spinner.String(),
  198. event.ID,
  199. event.Text,
  200. strings.Repeat(" ", padding),
  201. status,
  202. )
  203. timer := fmt.Sprintf("%.1fs\n", elapsed)
  204. o := align(text, timer, terminalWidth)
  205. if color {
  206. color := aec.WhiteF
  207. if event.Status == Done {
  208. color = aec.BlueF
  209. }
  210. if event.Status == Error {
  211. color = aec.RedF
  212. }
  213. if event.Status == Warning {
  214. color = aec.YellowF
  215. }
  216. return aec.Apply(o, color)
  217. }
  218. return o
  219. }
  220. func numDone(events map[string]Event) int {
  221. i := 0
  222. for _, e := range events {
  223. if e.Status == Done {
  224. i++
  225. }
  226. }
  227. return i
  228. }
  229. func align(l, r string, w int) string {
  230. return fmt.Sprintf("%-[2]*[1]s %[3]s", l, w-len(r)-1, r)
  231. }