progressbar.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  1. // Copyright 2016 CoreOS Inc
  2. //
  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. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package progressutil
  15. import (
  16. "fmt"
  17. "io"
  18. "os"
  19. "strings"
  20. "sync"
  21. "golang.org/x/crypto/ssh/terminal"
  22. )
  23. var (
  24. // ErrorProgressOutOfBounds is returned if the progress is set to a value
  25. // not between 0 and 1.
  26. ErrorProgressOutOfBounds = fmt.Errorf("progress is out of bounds (0 to 1)")
  27. // ErrorNoBarsAdded is returned when no progress bars have been added to a
  28. // ProgressBarPrinter before PrintAndWait is called.
  29. ErrorNoBarsAdded = fmt.Errorf("AddProgressBar hasn't been called yet")
  30. )
  31. // ProgressBar represents one progress bar in a ProgressBarPrinter. Should not
  32. // be created directly, use the AddProgressBar on a ProgressBarPrinter to
  33. // create these.
  34. type ProgressBar struct {
  35. lock sync.Mutex
  36. currentProgress float64
  37. printBefore string
  38. printAfter string
  39. done bool
  40. }
  41. func (pb *ProgressBar) clone() *ProgressBar {
  42. pb.lock.Lock()
  43. pbClone := &ProgressBar{
  44. currentProgress: pb.currentProgress,
  45. printBefore: pb.printBefore,
  46. printAfter: pb.printAfter,
  47. done: pb.done,
  48. }
  49. pb.lock.Unlock()
  50. return pbClone
  51. }
  52. func (pb *ProgressBar) GetCurrentProgress() float64 {
  53. pb.lock.Lock()
  54. val := pb.currentProgress
  55. pb.lock.Unlock()
  56. return val
  57. }
  58. // SetCurrentProgress sets the progress of this ProgressBar. The progress must
  59. // be between 0 and 1 inclusive.
  60. func (pb *ProgressBar) SetCurrentProgress(progress float64) error {
  61. if progress < 0 || progress > 1 {
  62. return ErrorProgressOutOfBounds
  63. }
  64. pb.lock.Lock()
  65. pb.currentProgress = progress
  66. pb.lock.Unlock()
  67. return nil
  68. }
  69. // GetDone returns whether or not this progress bar is done
  70. func (pb *ProgressBar) GetDone() bool {
  71. pb.lock.Lock()
  72. val := pb.done
  73. pb.lock.Unlock()
  74. return val
  75. }
  76. // SetDone sets whether or not this progress bar is done
  77. func (pb *ProgressBar) SetDone(val bool) {
  78. pb.lock.Lock()
  79. pb.done = val
  80. pb.lock.Unlock()
  81. }
  82. // GetPrintBefore gets the text printed on the line before the progress bar.
  83. func (pb *ProgressBar) GetPrintBefore() string {
  84. pb.lock.Lock()
  85. val := pb.printBefore
  86. pb.lock.Unlock()
  87. return val
  88. }
  89. // SetPrintBefore sets the text printed on the line before the progress bar.
  90. func (pb *ProgressBar) SetPrintBefore(before string) {
  91. pb.lock.Lock()
  92. pb.printBefore = before
  93. pb.lock.Unlock()
  94. }
  95. // GetPrintAfter gets the text printed on the line after the progress bar.
  96. func (pb *ProgressBar) GetPrintAfter() string {
  97. pb.lock.Lock()
  98. val := pb.printAfter
  99. pb.lock.Unlock()
  100. return val
  101. }
  102. // SetPrintAfter sets the text printed on the line after the progress bar.
  103. func (pb *ProgressBar) SetPrintAfter(after string) {
  104. pb.lock.Lock()
  105. pb.printAfter = after
  106. pb.lock.Unlock()
  107. }
  108. // ProgressBarPrinter will print out the progress of some number of
  109. // ProgressBars.
  110. type ProgressBarPrinter struct {
  111. lock sync.Mutex
  112. // DisplayWidth can be set to influence how large the progress bars are.
  113. // The bars will be scaled to attempt to produce lines of this number of
  114. // characters, but lines of different lengths may still be printed. When
  115. // this value is 0 (aka unset), 80 character columns are assumed.
  116. DisplayWidth int
  117. // PadToBeEven, when set to true, will make Print pad the printBefore text
  118. // with trailing spaces and the printAfter text with leading spaces to make
  119. // the progress bars the same length.
  120. PadToBeEven bool
  121. numLinesInLastPrint int
  122. progressBars []*ProgressBar
  123. maxBefore int
  124. maxAfter int
  125. }
  126. // AddProgressBar will create a new ProgressBar, register it with this
  127. // ProgressBarPrinter, and return it. This must be called at least once before
  128. // PrintAndWait is called.
  129. func (pbp *ProgressBarPrinter) AddProgressBar() *ProgressBar {
  130. pb := &ProgressBar{}
  131. pbp.lock.Lock()
  132. pbp.progressBars = append(pbp.progressBars, pb)
  133. pbp.lock.Unlock()
  134. return pb
  135. }
  136. // Print will print out progress information for each ProgressBar that has been
  137. // added to this ProgressBarPrinter. The progress will be written to printTo,
  138. // and if printTo is a terminal it will draw progress bars. AddProgressBar
  139. // must be called at least once before Print is called. If printing to a
  140. // terminal, all draws after the first one will move the cursor up to draw over
  141. // the previously printed bars.
  142. func (pbp *ProgressBarPrinter) Print(printTo io.Writer) (bool, error) {
  143. pbp.lock.Lock()
  144. var bars []*ProgressBar
  145. for _, bar := range pbp.progressBars {
  146. bars = append(bars, bar.clone())
  147. }
  148. numColumns := pbp.DisplayWidth
  149. pbp.lock.Unlock()
  150. if len(bars) == 0 {
  151. return false, ErrorNoBarsAdded
  152. }
  153. if numColumns == 0 {
  154. numColumns = 80
  155. }
  156. if isTerminal(printTo) {
  157. moveCursorUp(printTo, pbp.numLinesInLastPrint)
  158. }
  159. for _, bar := range bars {
  160. beforeSize := len(bar.GetPrintBefore())
  161. afterSize := len(bar.GetPrintAfter())
  162. if beforeSize > pbp.maxBefore {
  163. pbp.maxBefore = beforeSize
  164. }
  165. if afterSize > pbp.maxAfter {
  166. pbp.maxAfter = afterSize
  167. }
  168. }
  169. allDone := true
  170. for _, bar := range bars {
  171. if isTerminal(printTo) {
  172. bar.printToTerminal(printTo, numColumns, pbp.PadToBeEven, pbp.maxBefore, pbp.maxAfter)
  173. } else {
  174. bar.printToNonTerminal(printTo)
  175. }
  176. allDone = allDone && bar.GetCurrentProgress() == 1
  177. }
  178. pbp.numLinesInLastPrint = len(bars)
  179. return allDone, nil
  180. }
  181. // moveCursorUp moves the cursor up numLines in the terminal
  182. func moveCursorUp(printTo io.Writer, numLines int) {
  183. if numLines > 0 {
  184. fmt.Fprintf(printTo, "\033[%dA", numLines)
  185. }
  186. }
  187. func (pb *ProgressBar) printToTerminal(printTo io.Writer, numColumns int, padding bool, maxBefore, maxAfter int) {
  188. before := pb.GetPrintBefore()
  189. after := pb.GetPrintAfter()
  190. if padding {
  191. before = before + strings.Repeat(" ", maxBefore-len(before))
  192. after = strings.Repeat(" ", maxAfter-len(after)) + after
  193. }
  194. progressBarSize := numColumns - (len(fmt.Sprintf("%s [] %s", before, after)))
  195. progressBar := ""
  196. if progressBarSize > 0 {
  197. currentProgress := int(pb.GetCurrentProgress() * float64(progressBarSize))
  198. progressBar = fmt.Sprintf("[%s%s] ",
  199. strings.Repeat("=", currentProgress),
  200. strings.Repeat(" ", progressBarSize-currentProgress))
  201. } else {
  202. // If we can't fit the progress bar, better to not pad the before/after.
  203. before = pb.GetPrintBefore()
  204. after = pb.GetPrintAfter()
  205. }
  206. fmt.Fprintf(printTo, "%s %s%s\n", before, progressBar, after)
  207. }
  208. func (pb *ProgressBar) printToNonTerminal(printTo io.Writer) {
  209. if !pb.GetDone() {
  210. fmt.Fprintf(printTo, "%s %s\n", pb.printBefore, pb.printAfter)
  211. if pb.GetCurrentProgress() == 1 {
  212. pb.SetDone(true)
  213. }
  214. }
  215. }
  216. // isTerminal returns True when w is going to a tty, and false otherwise.
  217. func isTerminal(w io.Writer) bool {
  218. if f, ok := w.(*os.File); ok {
  219. return terminal.IsTerminal(int(f.Fd()))
  220. }
  221. return false
  222. }