tty.go 7.9 KB

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