tty.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  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. "strings"
  19. "sync"
  20. "time"
  21. "github.com/docker/compose/v2/pkg/api"
  22. "github.com/docker/compose/v2/pkg/utils"
  23. "github.com/buger/goterm"
  24. "github.com/docker/go-units"
  25. "github.com/morikuni/aec"
  26. )
  27. type ttyWriter struct {
  28. out io.Writer
  29. events map[string]Event
  30. eventIDs []string
  31. repeated bool
  32. numLines int
  33. done chan bool
  34. mtx *sync.Mutex
  35. tailEvents []string
  36. dryRun bool
  37. skipChildEvents bool
  38. progressTitle string
  39. hasFollowupAction bool
  40. }
  41. func (w *ttyWriter) Start(ctx context.Context) error {
  42. ticker := time.NewTicker(100 * time.Millisecond)
  43. defer ticker.Stop()
  44. for {
  45. select {
  46. case <-ctx.Done():
  47. w.print()
  48. w.printTailEvents()
  49. return ctx.Err()
  50. case <-w.done:
  51. w.print()
  52. w.printTailEvents()
  53. return nil
  54. case <-ticker.C:
  55. w.print()
  56. }
  57. }
  58. }
  59. func (w *ttyWriter) Stop() {
  60. w.done <- true
  61. }
  62. func (w *ttyWriter) HasMore(b bool) {
  63. w.hasFollowupAction = b
  64. }
  65. func (w *ttyWriter) Event(e Event) {
  66. w.mtx.Lock()
  67. defer w.mtx.Unlock()
  68. w.event(e)
  69. }
  70. func (w *ttyWriter) event(e Event) {
  71. if !utils.StringContains(w.eventIDs, e.ID) {
  72. w.eventIDs = append(w.eventIDs, e.ID)
  73. }
  74. if _, ok := w.events[e.ID]; ok {
  75. last := w.events[e.ID]
  76. if e.Status == Done && w.hasFollowupAction {
  77. e.Status = Working
  78. }
  79. switch e.Status {
  80. case Done, Error, Warning:
  81. if last.endTime.IsZero() {
  82. last.stop()
  83. }
  84. case Working:
  85. if !last.endTime.IsZero() {
  86. // already done, don't overwrite
  87. return
  88. }
  89. }
  90. last.Status = e.Status
  91. last.Text = e.Text
  92. last.StatusText = e.StatusText
  93. last.Total = e.Total
  94. last.Current = e.Current
  95. last.Percent = e.Percent
  96. // allow set/unset of parent, but not swapping otherwise prompt is flickering
  97. if last.ParentID == "" || e.ParentID == "" {
  98. last.ParentID = e.ParentID
  99. }
  100. w.events[e.ID] = last
  101. } else {
  102. e.startTime = time.Now()
  103. e.spinner = newSpinner()
  104. if e.Status == Done || e.Status == Error {
  105. e.stop()
  106. }
  107. w.events[e.ID] = e
  108. }
  109. }
  110. func (w *ttyWriter) Events(events []Event) {
  111. w.mtx.Lock()
  112. defer w.mtx.Unlock()
  113. for _, e := range events {
  114. w.event(e)
  115. }
  116. }
  117. func (w *ttyWriter) TailMsgf(msg string, args ...interface{}) {
  118. w.mtx.Lock()
  119. defer w.mtx.Unlock()
  120. msgWithPrefix := msg
  121. if w.dryRun {
  122. msgWithPrefix = strings.TrimSpace(api.DRYRUN_PREFIX + msg)
  123. }
  124. w.tailEvents = append(w.tailEvents, fmt.Sprintf(msgWithPrefix, args...))
  125. }
  126. func (w *ttyWriter) printTailEvents() {
  127. w.mtx.Lock()
  128. defer w.mtx.Unlock()
  129. for _, msg := range w.tailEvents {
  130. fmt.Fprintln(w.out, msg)
  131. }
  132. }
  133. func (w *ttyWriter) print() { //nolint:gocyclo
  134. w.mtx.Lock()
  135. defer w.mtx.Unlock()
  136. if len(w.eventIDs) == 0 {
  137. return
  138. }
  139. terminalWidth := goterm.Width()
  140. b := aec.EmptyBuilder
  141. for i := 0; i <= w.numLines; i++ {
  142. b = b.Up(1)
  143. }
  144. if !w.repeated {
  145. b = b.Down(1)
  146. }
  147. w.repeated = true
  148. fmt.Fprint(w.out, b.Column(0).ANSI)
  149. // Hide the cursor while we are printing
  150. fmt.Fprint(w.out, aec.Hide)
  151. defer fmt.Fprint(w.out, aec.Show)
  152. firstLine := fmt.Sprintf("[+] %s %d/%d", w.progressTitle, numDone(w.events), w.numLines)
  153. if w.numLines != 0 && numDone(w.events) == w.numLines {
  154. firstLine = DoneColor(firstLine)
  155. }
  156. fmt.Fprintln(w.out, firstLine)
  157. var statusPadding int
  158. for _, v := range w.eventIDs {
  159. event := w.events[v]
  160. l := len(fmt.Sprintf("%s %s", event.ID, event.Text))
  161. if statusPadding < l {
  162. statusPadding = l
  163. }
  164. if event.ParentID != "" {
  165. statusPadding -= 2
  166. }
  167. }
  168. if len(w.eventIDs) > goterm.Height()-2 {
  169. w.skipChildEvents = true
  170. }
  171. numLines := 0
  172. for _, v := range w.eventIDs {
  173. event := w.events[v]
  174. if event.ParentID != "" {
  175. continue
  176. }
  177. line := w.lineText(event, "", terminalWidth, statusPadding, w.dryRun)
  178. fmt.Fprint(w.out, line)
  179. numLines++
  180. for _, v := range w.eventIDs {
  181. ev := w.events[v]
  182. if ev.ParentID == event.ID {
  183. if w.skipChildEvents {
  184. continue
  185. }
  186. line := w.lineText(ev, " ", terminalWidth, statusPadding, w.dryRun)
  187. fmt.Fprint(w.out, line)
  188. numLines++
  189. }
  190. }
  191. }
  192. for i := numLines; i < w.numLines; i++ {
  193. if numLines < goterm.Height()-2 {
  194. fmt.Fprintln(w.out, strings.Repeat(" ", terminalWidth))
  195. numLines++
  196. }
  197. }
  198. w.numLines = numLines
  199. }
  200. func (w *ttyWriter) lineText(event Event, pad string, terminalWidth, statusPadding int, dryRun bool) string {
  201. endTime := time.Now()
  202. if event.Status != Working {
  203. endTime = event.startTime
  204. if (event.endTime != time.Time{}) {
  205. endTime = event.endTime
  206. }
  207. }
  208. prefix := ""
  209. if dryRun {
  210. prefix = PrefixColor(api.DRYRUN_PREFIX)
  211. }
  212. elapsed := endTime.Sub(event.startTime).Seconds()
  213. var (
  214. total int64
  215. current int64
  216. completion []string
  217. )
  218. for _, v := range w.eventIDs {
  219. ev := w.events[v]
  220. if ev.ParentID == event.ID {
  221. total += ev.Total
  222. current += ev.Current
  223. completion = append(completion, percentChars[(len(percentChars)-1)*ev.Percent/100])
  224. }
  225. }
  226. var txt string
  227. if len(completion) > 0 {
  228. txt = fmt.Sprintf("%s %s [%s] %7s/%-7s %s",
  229. event.ID,
  230. CountColor(fmt.Sprintf("%d layers", len(completion))),
  231. SuccessColor(strings.Join(completion, "")),
  232. units.HumanSize(float64(current)), units.HumanSize(float64(total)),
  233. event.Text)
  234. } else {
  235. txt = fmt.Sprintf("%s %s", event.ID, event.Text)
  236. }
  237. textLen := len(txt)
  238. padding := statusPadding - textLen
  239. if padding < 0 {
  240. padding = 0
  241. }
  242. // calculate the max length for the status text, on errors it
  243. // is 2-3 lines long and breaks the line formatting
  244. maxStatusLen := terminalWidth - textLen - statusPadding - 15
  245. status := event.StatusText
  246. // 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
  247. if maxStatusLen > 0 && len(status) > maxStatusLen {
  248. status = status[:maxStatusLen] + "..."
  249. }
  250. text := fmt.Sprintf("%s %s%s %s%s %s",
  251. pad,
  252. event.Spinner(),
  253. prefix,
  254. txt,
  255. strings.Repeat(" ", padding),
  256. event.Status.colorFn()(status),
  257. )
  258. timer := fmt.Sprintf("%.1fs ", elapsed)
  259. o := align(text, TimerColor(timer), terminalWidth)
  260. return o
  261. }
  262. func numDone(events map[string]Event) int {
  263. i := 0
  264. for _, e := range events {
  265. if e.Status != Working {
  266. i++
  267. }
  268. }
  269. return i
  270. }
  271. func align(l, r string, w int) string {
  272. ll := lenAnsi(l)
  273. lr := lenAnsi(r)
  274. pad := ""
  275. count := w - ll - lr
  276. if count > 0 {
  277. pad = strings.Repeat(" ", count)
  278. }
  279. return fmt.Sprintf("%s%s%s\n", l, pad, r)
  280. }
  281. // lenAnsi count of user-perceived characters in ANSI string.
  282. func lenAnsi(s string) int {
  283. length := 0
  284. ansiCode := false
  285. for _, r := range s {
  286. if r == '\x1b' {
  287. ansiCode = true
  288. continue
  289. }
  290. if ansiCode && r == 'm' {
  291. ansiCode = false
  292. continue
  293. }
  294. if !ansiCode {
  295. length++
  296. }
  297. }
  298. return length
  299. }
  300. var (
  301. percentChars = strings.Split("⠀⡀⣀⣄⣤⣦⣶⣷⣿", "")
  302. )