|
| 1 | +// Copyright © 2019 The Homeport Team |
| 2 | +// |
| 3 | +// Permission is hereby granted, free of charge, to any person obtaining a copy |
| 4 | +// of this software and associated documentation files (the "Software"), to deal |
| 5 | +// in the Software without restriction, including without limitation the rights |
| 6 | +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
| 7 | +// copies of the Software, and to permit persons to whom the Software is |
| 8 | +// furnished to do so, subject to the following conditions: |
| 9 | +// |
| 10 | +// The above copyright notice and this permission notice shall be included in |
| 11 | +// all copies or substantial portions of the Software. |
| 12 | +// |
| 13 | +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 14 | +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 15 | +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 16 | +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 17 | +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
| 18 | +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN |
| 19 | +// THE SOFTWARE. |
| 20 | + |
| 21 | +/* |
| 22 | +Package wait contains convenience functions to create a progress indicator for |
| 23 | +CLI applications, also know as a spinner. It is basically a text and a rapidly |
| 24 | +changing symbol that provides feedback to the user that something is still |
| 25 | +running even though there is no information how long it will continue to run. |
| 26 | +
|
| 27 | +Example: |
| 28 | + package main |
| 29 | +
|
| 30 | + import ( |
| 31 | + "time" |
| 32 | +
|
| 33 | + "github.com/gonvenience/wait" |
| 34 | + ) |
| 35 | +
|
| 36 | + func main() { |
| 37 | + pi := wait.NewProgressIndicator("operation in progress") |
| 38 | +
|
| 39 | + pi.SetTimeout(10 * time.Second) |
| 40 | + pi.Start() |
| 41 | +
|
| 42 | + time.Sleep(5 * time.Second) |
| 43 | +
|
| 44 | + pi.SetText("operation *still* in progress") |
| 45 | +
|
| 46 | + time.Sleep(5 * time.Second) |
| 47 | +
|
| 48 | + pi.Done("Ok, done") |
| 49 | + } |
| 50 | +*/ |
| 51 | +package wait |
| 52 | + |
| 53 | +import ( |
| 54 | + "fmt" |
| 55 | + "io" |
| 56 | + "math" |
| 57 | + "os" |
| 58 | + "strings" |
| 59 | + "sync/atomic" |
| 60 | + "time" |
| 61 | + |
| 62 | + "github.com/gonvenience/bunt" |
| 63 | + "github.com/gonvenience/term" |
| 64 | + "github.com/gonvenience/text" |
| 65 | + "github.com/lucasb-eyer/go-colorful" |
| 66 | +) |
| 67 | + |
| 68 | +const resetLine = "\r\x1b[K" |
| 69 | +const refreshIntervalInMs = 250 |
| 70 | + |
| 71 | +var symbols = []rune(`⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏`) |
| 72 | + |
| 73 | +var defaultElapsedTimeColor = bunt.DimGray |
| 74 | + |
| 75 | +// ProgressIndicator is a handle to a progress indicator (spinner). |
| 76 | +type ProgressIndicator struct { |
| 77 | + out io.Writer |
| 78 | + format string |
| 79 | + args []interface{} |
| 80 | + |
| 81 | + spin bool |
| 82 | + |
| 83 | + start time.Time |
| 84 | + running uint64 |
| 85 | + counter uint64 |
| 86 | + |
| 87 | + timeout time.Duration |
| 88 | + |
| 89 | + timeInfoText func(time.Duration) (string, colorful.Color) |
| 90 | +} |
| 91 | + |
| 92 | +// NewProgressIndicator creates a new progress indicator handle. The provided |
| 93 | +// text is shown as long as the progress indicator runs, or if new text is |
| 94 | +// supplied during runtime. |
| 95 | +func NewProgressIndicator(format string, args ...interface{}) *ProgressIndicator { |
| 96 | + return &ProgressIndicator{ |
| 97 | + out: os.Stderr, |
| 98 | + format: format, |
| 99 | + args: args, |
| 100 | + spin: !term.IsDumbTerminal(), |
| 101 | + timeout: 0 * time.Second, |
| 102 | + timeInfoText: TimeInfoText, |
| 103 | + } |
| 104 | +} |
| 105 | + |
| 106 | +// Start starts the progress indicator. If it is already started, the this |
| 107 | +// function returns immediately. |
| 108 | +func (pi *ProgressIndicator) Start() *ProgressIndicator { |
| 109 | + // No-op, in case it is already running |
| 110 | + if atomic.LoadUint64(&pi.running) > 0 { |
| 111 | + return pi |
| 112 | + } |
| 113 | + |
| 114 | + pi.start = time.Now() |
| 115 | + atomic.StoreUint64(&pi.running, 1) |
| 116 | + |
| 117 | + if pi.spin { |
| 118 | + term.HideCursor() |
| 119 | + |
| 120 | + go func() { |
| 121 | + for atomic.LoadUint64(&pi.running) > 0 { |
| 122 | + elapsedTime := time.Since(pi.start) |
| 123 | + |
| 124 | + // Timeout reached, stopping the progress indicator |
| 125 | + if pi.timeout > time.Nanosecond && elapsedTime > pi.timeout { |
| 126 | + pi.Done("timeout occurred") |
| 127 | + break |
| 128 | + } |
| 129 | + |
| 130 | + mainContentText := removeLineFeeds(bunt.Sprintf(pi.format, pi.args...)) |
| 131 | + elapsedTimeText, elapsedTimeColor := pi.timeInfoText(elapsedTime) |
| 132 | + |
| 133 | + availableSpace := term.GetTerminalWidth() - bunt.PlainTextLength(elapsedTimeText) - 4 |
| 134 | + |
| 135 | + // In case a timeout is set, smoothly blend the time info text color from |
| 136 | + // the provided color into red depending on how much time is left |
| 137 | + if pi.timeout > time.Nanosecond { |
| 138 | + // Use smooth curved gradient: http://fooplot.com/?lang=en#W3sidHlwZSI6MCwiZXEiOiIoMS1jb3MoeF4yKjMuMTQxNSkpLzIiLCJjb2xvciI6IiMwMDAwMDAifSx7InR5cGUiOjEwMDAsIndpbmRvdyI6WyIwIiwiMSIsIjAiLCIxIl19XQ-- |
| 139 | + blendFactor := 0.5 * (1.0 - math.Cos(math.Pow(elapsedTime.Seconds()/pi.timeout.Seconds(), 2)*math.Pi)) |
| 140 | + elapsedTimeColor = elapsedTimeColor.BlendLab(bunt.Red, blendFactor) |
| 141 | + } |
| 142 | + |
| 143 | + bunt.Fprint(pi.out, |
| 144 | + resetLine, " ", pi.nextSymbol(), " ", |
| 145 | + text.FixedLength(mainContentText, availableSpace), " ", |
| 146 | + bunt.Style(elapsedTimeText, bunt.Foreground(elapsedTimeColor)), |
| 147 | + ) |
| 148 | + |
| 149 | + time.Sleep(refreshIntervalInMs * time.Millisecond) |
| 150 | + } |
| 151 | + }() |
| 152 | + |
| 153 | + } else { |
| 154 | + bunt.Fprintf(pi.out, pi.format, pi.args...) |
| 155 | + bunt.Fprintln(pi.out) |
| 156 | + } |
| 157 | + |
| 158 | + return pi |
| 159 | +} |
| 160 | + |
| 161 | +// Stop stops the progress indicator by clearing the line one last time |
| 162 | +func (pi *ProgressIndicator) Stop() bool { |
| 163 | + if x := atomic.SwapUint64(&pi.running, 0); x > 0 { |
| 164 | + if pi.spin { |
| 165 | + term.ShowCursor() |
| 166 | + bunt.Fprint(pi.out, resetLine) |
| 167 | + } |
| 168 | + |
| 169 | + return true |
| 170 | + } |
| 171 | + |
| 172 | + return false |
| 173 | +} |
| 174 | + |
| 175 | +// SetText updates the waiting text. |
| 176 | +func (pi *ProgressIndicator) SetText(format string, args ...interface{}) { |
| 177 | + if bunt.Sprintf(format, args...) != bunt.Sprintf(pi.format, pi.args...) { |
| 178 | + pi.format = format |
| 179 | + pi.args = args |
| 180 | + |
| 181 | + if !pi.spin { |
| 182 | + bunt.Fprintf(pi.out, pi.format, pi.args...) |
| 183 | + bunt.Fprintln(pi.out) |
| 184 | + } |
| 185 | + } |
| 186 | +} |
| 187 | + |
| 188 | +// SetOutputWriter sets the output writer to used to print the progress |
| 189 | +// indicator texts to, e.g. `os.Stderr` or `os.Stdout`. |
| 190 | +func (pi *ProgressIndicator) SetOutputWriter(out io.Writer) { |
| 191 | + pi.out = out |
| 192 | +} |
| 193 | + |
| 194 | +// SetTimeout specifies that the progress indicator will timeout after the |
| 195 | +// provided duration. A timeout duration lower than one nanosecond means that |
| 196 | +// there is no timeout. |
| 197 | +func (pi *ProgressIndicator) SetTimeout(timeout time.Duration) { |
| 198 | + pi.timeout = timeout |
| 199 | +} |
| 200 | + |
| 201 | +// SetTimeInfoTextFunc sets a custom time info text function that is called to |
| 202 | +// create the string and the color to be used on the far right side of the |
| 203 | +// progress indicator. |
| 204 | +func (pi *ProgressIndicator) SetTimeInfoTextFunc(f func(time.Duration) (string, colorful.Color)) { |
| 205 | + pi.timeInfoText = f |
| 206 | +} |
| 207 | + |
| 208 | +// Done stops the progress indicator. |
| 209 | +func (pi *ProgressIndicator) Done(format string, args ...interface{}) bool { |
| 210 | + defer func() { |
| 211 | + bunt.Fprintf(pi.out, format, args...) |
| 212 | + bunt.Fprintln(pi.out) |
| 213 | + }() |
| 214 | + |
| 215 | + return pi.Stop() |
| 216 | +} |
| 217 | + |
| 218 | +func (pi *ProgressIndicator) nextSymbol() string { |
| 219 | + pi.counter++ |
| 220 | + return string(symbols[pi.counter%uint64(len(symbols))]) |
| 221 | +} |
| 222 | + |
| 223 | +// TimeInfoText is the default implementation for the time information text on |
| 224 | +// the far right side of the progress indicator line. |
| 225 | +func TimeInfoText(elapsedTime time.Duration) (string, colorful.Color) { |
| 226 | + return humanReadableDuration(elapsedTime), defaultElapsedTimeColor |
| 227 | +} |
| 228 | + |
| 229 | +func humanReadableDuration(duration time.Duration) string { |
| 230 | + if duration < time.Second { |
| 231 | + return "less than a second" |
| 232 | + } |
| 233 | + |
| 234 | + seconds := int(duration.Seconds()) |
| 235 | + minutes := 0 |
| 236 | + hours := 0 |
| 237 | + |
| 238 | + if seconds >= 60 { |
| 239 | + minutes = seconds / 60 |
| 240 | + seconds = seconds % 60 |
| 241 | + |
| 242 | + if minutes >= 60 { |
| 243 | + hours = minutes / 60 |
| 244 | + minutes = minutes % 60 |
| 245 | + } |
| 246 | + } |
| 247 | + |
| 248 | + parts := []string{} |
| 249 | + if hours > 0 { |
| 250 | + parts = append(parts, fmt.Sprintf("%d h", hours)) |
| 251 | + } |
| 252 | + |
| 253 | + if minutes > 0 { |
| 254 | + parts = append(parts, fmt.Sprintf("%d min", minutes)) |
| 255 | + } |
| 256 | + |
| 257 | + if seconds > 0 { |
| 258 | + parts = append(parts, fmt.Sprintf("%d sec", seconds)) |
| 259 | + } |
| 260 | + |
| 261 | + return strings.Join(parts, " ") |
| 262 | +} |
| 263 | + |
| 264 | +func removeLineFeeds(input string) string { |
| 265 | + return strings.Replace(input, "\n", " ", -1) |
| 266 | +} |
0 commit comments