tty.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  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.endTime.IsZero() {
  75. last.stop()
  76. }
  77. case Working:
  78. if !last.endTime.IsZero() {
  79. // already done, don't overwrite
  80. return
  81. }
  82. }
  83. last.Status = e.Status
  84. last.Text = e.Text
  85. last.StatusText = e.StatusText
  86. // progress can only go up
  87. if e.Total > last.Total {
  88. last.Total = e.Total
  89. }
  90. if e.Current > last.Current {
  91. last.Current = e.Current
  92. }
  93. if e.Percent > last.Percent {
  94. last.Percent = e.Percent
  95. }
  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. hideDetails bool
  215. total int64
  216. current int64
  217. completion []string
  218. )
  219. // only show the aggregated progress while the root operation is in-progress
  220. if parent := event; parent.Status == Working {
  221. for _, v := range w.eventIDs {
  222. child := w.events[v]
  223. if child.ParentID == parent.ID {
  224. if child.Status == Working && child.Total == 0 {
  225. // we don't have totals available for all the child events
  226. // so don't show the total progress yet
  227. hideDetails = true
  228. }
  229. total += child.Total
  230. current += child.Current
  231. completion = append(completion, percentChars[(len(percentChars)-1)*child.Percent/100])
  232. }
  233. }
  234. }
  235. // don't try to show detailed progress if we don't have any idea
  236. if total == 0 {
  237. hideDetails = true
  238. }
  239. var txt string
  240. if len(completion) > 0 {
  241. var details string
  242. if !hideDetails {
  243. details = fmt.Sprintf(" %7s / %-7s", units.HumanSize(float64(current)), units.HumanSize(float64(total)))
  244. }
  245. txt = fmt.Sprintf("%s [%s]%s %s",
  246. event.ID,
  247. SuccessColor(strings.Join(completion, "")),
  248. details,
  249. event.Text,
  250. )
  251. } else {
  252. txt = fmt.Sprintf("%s %s", event.ID, event.Text)
  253. }
  254. textLen := len(txt)
  255. padding := statusPadding - textLen
  256. if padding < 0 {
  257. padding = 0
  258. }
  259. // calculate the max length for the status text, on errors it
  260. // is 2-3 lines long and breaks the line formatting
  261. maxStatusLen := terminalWidth - textLen - statusPadding - 15
  262. status := event.StatusText
  263. // 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
  264. if maxStatusLen > 0 && len(status) > maxStatusLen {
  265. status = status[:maxStatusLen] + "..."
  266. }
  267. text := fmt.Sprintf("%s %s%s %s%s %s",
  268. pad,
  269. event.Spinner(),
  270. prefix,
  271. txt,
  272. strings.Repeat(" ", padding),
  273. event.Status.colorFn()(status),
  274. )
  275. timer := fmt.Sprintf("%.1fs ", elapsed)
  276. o := align(text, TimerColor(timer), terminalWidth)
  277. return o
  278. }
  279. func numDone(events map[string]Event) int {
  280. i := 0
  281. for _, e := range events {
  282. if e.Status != Working {
  283. i++
  284. }
  285. }
  286. return i
  287. }
  288. func align(l, r string, w int) string {
  289. ll := lenAnsi(l)
  290. lr := lenAnsi(r)
  291. pad := ""
  292. count := w - ll - lr
  293. if count > 0 {
  294. pad = strings.Repeat(" ", count)
  295. }
  296. return fmt.Sprintf("%s%s%s\n", l, pad, r)
  297. }
  298. // lenAnsi count of user-perceived characters in ANSI string.
  299. func lenAnsi(s string) int {
  300. length := 0
  301. ansiCode := false
  302. for _, r := range s {
  303. if r == '\x1b' {
  304. ansiCode = true
  305. continue
  306. }
  307. if ansiCode && r == 'm' {
  308. ansiCode = false
  309. continue
  310. }
  311. if !ansiCode {
  312. length++
  313. }
  314. }
  315. return length
  316. }
  317. var (
  318. percentChars = strings.Split("⠀⡀⣀⣄⣤⣦⣶⣷⣿", "")
  319. )