tty.go 5.1 KB

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