tty.go 7.7 KB

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