tty.go 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  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-cli/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.RWMutex
  34. }
  35. func (w *ttyWriter) Start(ctx context.Context) error {
  36. ticker := time.NewTicker(100 * time.Millisecond)
  37. for {
  38. select {
  39. case <-ctx.Done():
  40. w.print()
  41. return ctx.Err()
  42. case <-w.done:
  43. w.print()
  44. return nil
  45. case <-ticker.C:
  46. w.print()
  47. }
  48. }
  49. }
  50. func (w *ttyWriter) Stop() {
  51. w.done <- true
  52. }
  53. func (w *ttyWriter) Event(e Event) {
  54. w.mtx.Lock()
  55. defer w.mtx.Unlock()
  56. if !utils.StringContains(w.eventIDs, e.ID) {
  57. w.eventIDs = append(w.eventIDs, e.ID)
  58. }
  59. if _, ok := w.events[e.ID]; ok {
  60. last := w.events[e.ID]
  61. switch e.Status {
  62. case Done, Error:
  63. if last.Status != e.Status {
  64. last.stop()
  65. }
  66. }
  67. last.Status = e.Status
  68. last.Text = e.Text
  69. last.StatusText = e.StatusText
  70. last.ParentID = e.ParentID
  71. w.events[e.ID] = last
  72. } else {
  73. e.startTime = time.Now()
  74. e.spinner = newSpinner()
  75. if e.Status == Done || e.Status == Error {
  76. e.stop()
  77. }
  78. w.events[e.ID] = e
  79. }
  80. }
  81. func (w *ttyWriter) print() {
  82. w.mtx.Lock()
  83. defer w.mtx.Unlock()
  84. if len(w.eventIDs) == 0 {
  85. return
  86. }
  87. terminalWidth := goterm.Width()
  88. b := aec.EmptyBuilder
  89. for i := 0; i <= w.numLines; i++ {
  90. b = b.Up(1)
  91. }
  92. if !w.repeated {
  93. b = b.Down(1)
  94. }
  95. w.repeated = true
  96. fmt.Fprint(w.out, b.Column(0).ANSI)
  97. // Hide the cursor while we are printing
  98. fmt.Fprint(w.out, aec.Hide)
  99. defer fmt.Fprint(w.out, aec.Show)
  100. firstLine := fmt.Sprintf("[+] Running %d/%d", numDone(w.events), w.numLines)
  101. if w.numLines != 0 && numDone(w.events) == w.numLines {
  102. firstLine = aec.Apply(firstLine, aec.BlueF)
  103. }
  104. fmt.Fprintln(w.out, firstLine)
  105. var statusPadding int
  106. for _, v := range w.eventIDs {
  107. event := w.events[v]
  108. l := len(fmt.Sprintf("%s %s", event.ID, event.Text))
  109. if statusPadding < l {
  110. statusPadding = l
  111. }
  112. if event.ParentID != "" {
  113. statusPadding -= 2
  114. }
  115. }
  116. numLines := 0
  117. for _, v := range w.eventIDs {
  118. event := w.events[v]
  119. if event.ParentID != "" {
  120. continue
  121. }
  122. line := lineText(event, "", terminalWidth, statusPadding, runtime.GOOS != "windows")
  123. // nolint: errcheck
  124. fmt.Fprint(w.out, line)
  125. numLines++
  126. for _, v := range w.eventIDs {
  127. ev := w.events[v]
  128. if ev.ParentID == event.ID {
  129. line := lineText(ev, " ", terminalWidth, statusPadding, runtime.GOOS != "windows")
  130. // nolint: errcheck
  131. fmt.Fprint(w.out, line)
  132. numLines++
  133. }
  134. }
  135. }
  136. w.numLines = numLines
  137. }
  138. func lineText(event Event, pad string, terminalWidth, statusPadding int, color bool) string {
  139. endTime := time.Now()
  140. if event.Status != Working {
  141. endTime = event.startTime
  142. if (event.endTime != time.Time{}) {
  143. endTime = event.endTime
  144. }
  145. }
  146. elapsed := endTime.Sub(event.startTime).Seconds()
  147. textLen := len(fmt.Sprintf("%s %s", event.ID, event.Text))
  148. padding := statusPadding - textLen
  149. if padding < 0 {
  150. padding = 0
  151. }
  152. // calculate the max length for the status text, on errors it
  153. // is 2-3 lines long and breaks the line formating
  154. maxStatusLen := terminalWidth - textLen - statusPadding - 15
  155. status := event.StatusText
  156. // 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
  157. if maxStatusLen > 0 && len(status) > maxStatusLen {
  158. status = status[:maxStatusLen] + "..."
  159. }
  160. text := fmt.Sprintf("%s %s %s %s%s %s",
  161. pad,
  162. event.spinner.String(),
  163. event.ID,
  164. event.Text,
  165. strings.Repeat(" ", padding),
  166. status,
  167. )
  168. timer := fmt.Sprintf("%.1fs\n", elapsed)
  169. o := align(text, timer, terminalWidth)
  170. if color {
  171. color := aec.WhiteF
  172. if event.Status == Done {
  173. color = aec.BlueF
  174. }
  175. if event.Status == Error {
  176. color = aec.RedF
  177. }
  178. return aec.Apply(o, color)
  179. }
  180. return o
  181. }
  182. func numDone(events map[string]Event) int {
  183. i := 0
  184. for _, e := range events {
  185. if e.Status == Done {
  186. i++
  187. }
  188. }
  189. return i
  190. }
  191. func align(l, r string, w int) string {
  192. return fmt.Sprintf("%-[2]*[1]s %[3]s", l, w-len(r)-1, r)
  193. }