tty.go 5.9 KB

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