tty.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  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() {
  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. numLines := 0
  141. for _, v := range w.eventIDs {
  142. event := w.events[v]
  143. if event.ParentID != "" {
  144. continue
  145. }
  146. line := lineText(event, "", terminalWidth, statusPadding, runtime.GOOS != "windows")
  147. fmt.Fprint(w.out, line)
  148. numLines++
  149. for _, v := range w.eventIDs {
  150. ev := w.events[v]
  151. if ev.ParentID == event.ID {
  152. line := lineText(ev, " ", terminalWidth, statusPadding, runtime.GOOS != "windows")
  153. fmt.Fprint(w.out, line)
  154. numLines++
  155. }
  156. }
  157. }
  158. w.numLines = numLines
  159. }
  160. func lineText(event Event, pad string, terminalWidth, statusPadding int, color bool) string {
  161. endTime := time.Now()
  162. if event.Status != Working {
  163. endTime = event.startTime
  164. if (event.endTime != time.Time{}) {
  165. endTime = event.endTime
  166. }
  167. }
  168. elapsed := endTime.Sub(event.startTime).Seconds()
  169. textLen := len(fmt.Sprintf("%s %s", event.ID, event.Text))
  170. padding := statusPadding - textLen
  171. if padding < 0 {
  172. padding = 0
  173. }
  174. // calculate the max length for the status text, on errors it
  175. // is 2-3 lines long and breaks the line formatting
  176. maxStatusLen := terminalWidth - textLen - statusPadding - 15
  177. status := event.StatusText
  178. // 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
  179. if maxStatusLen > 0 && len(status) > maxStatusLen {
  180. status = status[:maxStatusLen] + "..."
  181. }
  182. text := fmt.Sprintf("%s %s %s %s%s %s",
  183. pad,
  184. event.spinner.String(),
  185. event.ID,
  186. event.Text,
  187. strings.Repeat(" ", padding),
  188. status,
  189. )
  190. timer := fmt.Sprintf("%.1fs\n", elapsed)
  191. o := align(text, timer, terminalWidth)
  192. if color {
  193. color := aec.WhiteF
  194. if event.Status == Done {
  195. color = aec.BlueF
  196. }
  197. if event.Status == Error {
  198. color = aec.RedF
  199. }
  200. if event.Status == Warning {
  201. color = aec.YellowF
  202. }
  203. return aec.Apply(o, color)
  204. }
  205. return o
  206. }
  207. func numDone(events map[string]Event) int {
  208. i := 0
  209. for _, e := range events {
  210. if e.Status == Done {
  211. i++
  212. }
  213. }
  214. return i
  215. }
  216. func align(l, r string, w int) string {
  217. return fmt.Sprintf("%-[2]*[1]s %[3]s", l, w-len(r)-1, r)
  218. }