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. "slices"
  19. "strings"
  20. "sync"
  21. "time"
  22. "github.com/docker/compose/v2/pkg/api"
  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 !slices.Contains(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 func() {
  149. _, _ = fmt.Fprint(w.out, aec.Show)
  150. }()
  151. firstLine := fmt.Sprintf("[+] %s %d/%d", w.progressTitle, numDone(w.events), len(w.events))
  152. if w.numLines != 0 && numDone(w.events) == w.numLines {
  153. firstLine = DoneColor(firstLine)
  154. }
  155. _, _ = fmt.Fprintln(w.out, firstLine)
  156. var statusPadding int
  157. for _, v := range w.eventIDs {
  158. event := w.events[v]
  159. l := len(fmt.Sprintf("%s %s", event.ID, event.Text))
  160. if statusPadding < l {
  161. statusPadding = l
  162. }
  163. if event.ParentID != "" {
  164. statusPadding -= 2
  165. }
  166. }
  167. if len(w.eventIDs) > goterm.Height()-2 {
  168. w.skipChildEvents = true
  169. }
  170. numLines := 0
  171. for _, v := range w.eventIDs {
  172. event := w.events[v]
  173. if event.ParentID != "" {
  174. continue
  175. }
  176. line := w.lineText(event, "", terminalWidth, statusPadding, w.dryRun)
  177. _, _ = fmt.Fprint(w.out, line)
  178. numLines++
  179. for _, v := range w.eventIDs {
  180. ev := w.events[v]
  181. if ev.ParentID == event.ID {
  182. if w.skipChildEvents {
  183. continue
  184. }
  185. line := w.lineText(ev, " ", terminalWidth, statusPadding, w.dryRun)
  186. _, _ = fmt.Fprint(w.out, line)
  187. numLines++
  188. }
  189. }
  190. }
  191. for i := numLines; i < w.numLines; i++ {
  192. if numLines < goterm.Height()-2 {
  193. _, _ = fmt.Fprintln(w.out, strings.Repeat(" ", terminalWidth))
  194. numLines++
  195. }
  196. }
  197. w.numLines = numLines
  198. }
  199. func (w *ttyWriter) lineText(event Event, pad string, terminalWidth, statusPadding int, dryRun bool) string {
  200. endTime := time.Now()
  201. if event.Status != Working {
  202. endTime = event.startTime
  203. if (event.endTime != time.Time{}) {
  204. endTime = event.endTime
  205. }
  206. }
  207. prefix := ""
  208. if dryRun {
  209. prefix = PrefixColor(api.DRYRUN_PREFIX)
  210. }
  211. elapsed := endTime.Sub(event.startTime).Seconds()
  212. var (
  213. hideDetails bool
  214. total int64
  215. current int64
  216. completion []string
  217. )
  218. // only show the aggregated progress while the root operation is in-progress
  219. if parent := event; parent.Status == Working {
  220. for _, v := range w.eventIDs {
  221. child := w.events[v]
  222. if child.ParentID == parent.ID {
  223. if child.Status == Working && child.Total == 0 {
  224. // we don't have totals available for all the child events
  225. // so don't show the total progress yet
  226. hideDetails = true
  227. }
  228. total += child.Total
  229. current += child.Current
  230. completion = append(completion, percentChars[(len(percentChars)-1)*child.Percent/100])
  231. }
  232. }
  233. }
  234. // don't try to show detailed progress if we don't have any idea
  235. if total == 0 {
  236. hideDetails = true
  237. }
  238. var txt string
  239. if len(completion) > 0 {
  240. var details string
  241. if !hideDetails {
  242. details = fmt.Sprintf(" %7s / %-7s", units.HumanSize(float64(current)), units.HumanSize(float64(total)))
  243. }
  244. txt = fmt.Sprintf("%s [%s]%s %s",
  245. event.ID,
  246. SuccessColor(strings.Join(completion, "")),
  247. details,
  248. event.Text,
  249. )
  250. } else {
  251. txt = fmt.Sprintf("%s %s", event.ID, event.Text)
  252. }
  253. textLen := len(txt)
  254. padding := statusPadding - textLen
  255. if padding < 0 {
  256. padding = 0
  257. }
  258. // calculate the max length for the status text, on errors it
  259. // is 2-3 lines long and breaks the line formatting
  260. maxStatusLen := terminalWidth - textLen - statusPadding - 15
  261. status := event.StatusText
  262. // 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
  263. if maxStatusLen > 0 && len(status) > maxStatusLen {
  264. status = status[:maxStatusLen] + "..."
  265. }
  266. text := fmt.Sprintf("%s %s%s %s%s %s",
  267. pad,
  268. event.Spinner(),
  269. prefix,
  270. txt,
  271. strings.Repeat(" ", padding),
  272. event.Status.colorFn()(status),
  273. )
  274. timer := fmt.Sprintf("%.1fs ", elapsed)
  275. o := align(text, TimerColor(timer), terminalWidth)
  276. return o
  277. }
  278. func numDone(events map[string]Event) int {
  279. i := 0
  280. for _, e := range events {
  281. if e.Status != Working {
  282. i++
  283. }
  284. }
  285. return i
  286. }
  287. func align(l, r string, w int) string {
  288. ll := lenAnsi(l)
  289. lr := lenAnsi(r)
  290. pad := ""
  291. count := w - ll - lr
  292. if count > 0 {
  293. pad = strings.Repeat(" ", count)
  294. }
  295. return fmt.Sprintf("%s%s%s\n", l, pad, r)
  296. }
  297. // lenAnsi count of user-perceived characters in ANSI string.
  298. func lenAnsi(s string) int {
  299. length := 0
  300. ansiCode := false
  301. for _, r := range s {
  302. if r == '\x1b' {
  303. ansiCode = true
  304. continue
  305. }
  306. if ansiCode && r == 'm' {
  307. ansiCode = false
  308. continue
  309. }
  310. if !ansiCode {
  311. length++
  312. }
  313. }
  314. return length
  315. }
  316. var percentChars = strings.Split("⠀⡀⣀⣄⣤⣦⣶⣷⣿", "")