tty.go 5.1 KB

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