tty.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  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:
  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. last.ParentID = e.ParentID
  75. w.events[e.ID] = last
  76. } else {
  77. e.startTime = time.Now()
  78. e.spinner = newSpinner()
  79. if e.Status == Done || e.Status == Error {
  80. e.stop()
  81. }
  82. w.events[e.ID] = e
  83. }
  84. }
  85. func (w *ttyWriter) Events(events []Event) {
  86. for _, e := range events {
  87. w.Event(e)
  88. }
  89. }
  90. func (w *ttyWriter) TailMsgf(msg string, args ...interface{}) {
  91. w.mtx.Lock()
  92. defer w.mtx.Unlock()
  93. w.tailEvents = append(w.tailEvents, fmt.Sprintf(msg, args...))
  94. }
  95. func (w *ttyWriter) printTailEvents() {
  96. w.mtx.Lock()
  97. defer w.mtx.Unlock()
  98. for _, msg := range w.tailEvents {
  99. fmt.Fprintln(w.out, msg)
  100. }
  101. }
  102. func (w *ttyWriter) print() {
  103. w.mtx.Lock()
  104. defer w.mtx.Unlock()
  105. if len(w.eventIDs) == 0 {
  106. return
  107. }
  108. terminalWidth := goterm.Width()
  109. b := aec.EmptyBuilder
  110. for i := 0; i <= w.numLines; i++ {
  111. b = b.Up(1)
  112. }
  113. if !w.repeated {
  114. b = b.Down(1)
  115. }
  116. w.repeated = true
  117. fmt.Fprint(w.out, b.Column(0).ANSI)
  118. // Hide the cursor while we are printing
  119. fmt.Fprint(w.out, aec.Hide)
  120. defer fmt.Fprint(w.out, aec.Show)
  121. firstLine := fmt.Sprintf("[+] Running %d/%d", numDone(w.events), w.numLines)
  122. if w.numLines != 0 && numDone(w.events) == w.numLines {
  123. firstLine = aec.Apply(firstLine, aec.BlueF)
  124. }
  125. fmt.Fprintln(w.out, firstLine)
  126. var statusPadding int
  127. for _, v := range w.eventIDs {
  128. event := w.events[v]
  129. l := len(fmt.Sprintf("%s %s", event.ID, event.Text))
  130. if statusPadding < l {
  131. statusPadding = l
  132. }
  133. if event.ParentID != "" {
  134. statusPadding -= 2
  135. }
  136. }
  137. numLines := 0
  138. for _, v := range w.eventIDs {
  139. event := w.events[v]
  140. if event.ParentID != "" {
  141. continue
  142. }
  143. line := lineText(event, "", terminalWidth, statusPadding, runtime.GOOS != "windows")
  144. // nolint: errcheck
  145. fmt.Fprint(w.out, line)
  146. numLines++
  147. for _, v := range w.eventIDs {
  148. ev := w.events[v]
  149. if ev.ParentID == event.ID {
  150. line := lineText(ev, " ", terminalWidth, statusPadding, runtime.GOOS != "windows")
  151. // nolint: errcheck
  152. fmt.Fprint(w.out, line)
  153. numLines++
  154. }
  155. }
  156. }
  157. w.numLines = numLines
  158. }
  159. func lineText(event Event, pad string, terminalWidth, statusPadding int, color bool) string {
  160. endTime := time.Now()
  161. if event.Status != Working {
  162. endTime = event.startTime
  163. if (event.endTime != time.Time{}) {
  164. endTime = event.endTime
  165. }
  166. }
  167. elapsed := endTime.Sub(event.startTime).Seconds()
  168. textLen := len(fmt.Sprintf("%s %s", event.ID, event.Text))
  169. padding := statusPadding - textLen
  170. if padding < 0 {
  171. padding = 0
  172. }
  173. // calculate the max length for the status text, on errors it
  174. // is 2-3 lines long and breaks the line formatting
  175. maxStatusLen := terminalWidth - textLen - statusPadding - 15
  176. status := event.StatusText
  177. // 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
  178. if maxStatusLen > 0 && len(status) > maxStatusLen {
  179. status = status[:maxStatusLen] + "..."
  180. }
  181. text := fmt.Sprintf("%s %s %s %s%s %s",
  182. pad,
  183. event.spinner.String(),
  184. event.ID,
  185. event.Text,
  186. strings.Repeat(" ", padding),
  187. status,
  188. )
  189. timer := fmt.Sprintf("%.1fs\n", elapsed)
  190. o := align(text, timer, terminalWidth)
  191. if color {
  192. color := aec.WhiteF
  193. if event.Status == Done {
  194. color = aec.BlueF
  195. }
  196. if event.Status == Error {
  197. color = aec.RedF
  198. }
  199. return aec.Apply(o, color)
  200. }
  201. return o
  202. }
  203. func numDone(events map[string]Event) int {
  204. i := 0
  205. for _, e := range events {
  206. if e.Status == Done {
  207. i++
  208. }
  209. }
  210. return i
  211. }
  212. func align(l, r string, w int) string {
  213. return fmt.Sprintf("%-[2]*[1]s %[3]s", l, w-len(r)-1, r)
  214. }