| 1 |
// Copyright (c) 2021 Brian J. Downs |
| 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 |
|
| 15 |
// Package spinner is a simple package to add a spinner / progress indicator to any terminal application. |
| 16 |
package spinner |
| 17 |
|
| 18 |
import ( |
| 19 |
"errors" |
| 20 |
"fmt" |
| 21 |
"io" |
| 22 |
"os" |
| 23 |
"runtime" |
| 24 |
"strconv" |
| 25 |
"strings" |
| 26 |
"sync" |
| 27 |
"time" |
| 28 |
"unicode/utf8" |
| 29 |
|
| 30 |
"github.com/fatih/color" |
| 31 |
"github.com/mattn/go-isatty" |
| 32 |
) |
| 33 |
|
| 34 |
// errInvalidColor is returned when attempting to set an invalid color |
| 35 |
var errInvalidColor = errors.New("invalid color") |
| 36 |
|
| 37 |
// validColors holds an array of the only colors allowed |
| 38 |
var validColors = map[string]bool{ |
| 39 |
// default colors for backwards compatibility |
| 40 |
"black": true, |
| 41 |
"red": true, |
| 42 |
"green": true, |
| 43 |
"yellow": true, |
| 44 |
"blue": true, |
| 45 |
"magenta": true, |
| 46 |
"cyan": true, |
| 47 |
"white": true, |
| 48 |
|
| 49 |
// attributes |
| 50 |
"reset": true, |
| 51 |
"bold": true, |
| 52 |
"faint": true, |
| 53 |
"italic": true, |
| 54 |
"underline": true, |
| 55 |
"blinkslow": true, |
| 56 |
"blinkrapid": true, |
| 57 |
"reversevideo": true, |
| 58 |
"concealed": true, |
| 59 |
"crossedout": true, |
| 60 |
|
| 61 |
// foreground text |
| 62 |
"fgBlack": true, |
| 63 |
"fgRed": true, |
| 64 |
"fgGreen": true, |
| 65 |
"fgYellow": true, |
| 66 |
"fgBlue": true, |
| 67 |
"fgMagenta": true, |
| 68 |
"fgCyan": true, |
| 69 |
"fgWhite": true, |
| 70 |
|
| 71 |
// foreground Hi-Intensity text |
| 72 |
"fgHiBlack": true, |
| 73 |
"fgHiRed": true, |
| 74 |
"fgHiGreen": true, |
| 75 |
"fgHiYellow": true, |
| 76 |
"fgHiBlue": true, |
| 77 |
"fgHiMagenta": true, |
| 78 |
"fgHiCyan": true, |
| 79 |
"fgHiWhite": true, |
| 80 |
|
| 81 |
// background text |
| 82 |
"bgBlack": true, |
| 83 |
"bgRed": true, |
| 84 |
"bgGreen": true, |
| 85 |
"bgYellow": true, |
| 86 |
"bgBlue": true, |
| 87 |
"bgMagenta": true, |
| 88 |
"bgCyan": true, |
| 89 |
"bgWhite": true, |
| 90 |
|
| 91 |
// background Hi-Intensity text |
| 92 |
"bgHiBlack": true, |
| 93 |
"bgHiRed": true, |
| 94 |
"bgHiGreen": true, |
| 95 |
"bgHiYellow": true, |
| 96 |
"bgHiBlue": true, |
| 97 |
"bgHiMagenta": true, |
| 98 |
"bgHiCyan": true, |
| 99 |
"bgHiWhite": true, |
| 100 |
} |
| 101 |
|
| 102 |
// returns true if the OS is windows and the WT_SESSION env variable is set. |
| 103 |
var isWindowsTerminalOnWindows = len(os.Getenv("WT_SESSION")) > 0 && runtime.GOOS == "windows" |
| 104 |
|
| 105 |
// returns a valid color's foreground text color attribute |
| 106 |
var colorAttributeMap = map[string]color.Attribute{ |
| 107 |
// default colors for backwards compatibility |
| 108 |
"black": color.FgBlack, |
| 109 |
"red": color.FgRed, |
| 110 |
"green": color.FgGreen, |
| 111 |
"yellow": color.FgYellow, |
| 112 |
"blue": color.FgBlue, |
| 113 |
"magenta": color.FgMagenta, |
| 114 |
"cyan": color.FgCyan, |
| 115 |
"white": color.FgWhite, |
| 116 |
|
| 117 |
// attributes |
| 118 |
"reset": color.Reset, |
| 119 |
"bold": color.Bold, |
| 120 |
"faint": color.Faint, |
| 121 |
"italic": color.Italic, |
| 122 |
"underline": color.Underline, |
| 123 |
"blinkslow": color.BlinkSlow, |
| 124 |
"blinkrapid": color.BlinkRapid, |
| 125 |
"reversevideo": color.ReverseVideo, |
| 126 |
"concealed": color.Concealed, |
| 127 |
"crossedout": color.CrossedOut, |
| 128 |
|
| 129 |
// foreground text colors |
| 130 |
"fgBlack": color.FgBlack, |
| 131 |
"fgRed": color.FgRed, |
| 132 |
"fgGreen": color.FgGreen, |
| 133 |
"fgYellow": color.FgYellow, |
| 134 |
"fgBlue": color.FgBlue, |
| 135 |
"fgMagenta": color.FgMagenta, |
| 136 |
"fgCyan": color.FgCyan, |
| 137 |
"fgWhite": color.FgWhite, |
| 138 |
|
| 139 |
// foreground Hi-Intensity text colors |
| 140 |
"fgHiBlack": color.FgHiBlack, |
| 141 |
"fgHiRed": color.FgHiRed, |
| 142 |
"fgHiGreen": color.FgHiGreen, |
| 143 |
"fgHiYellow": color.FgHiYellow, |
| 144 |
"fgHiBlue": color.FgHiBlue, |
| 145 |
"fgHiMagenta": color.FgHiMagenta, |
| 146 |
"fgHiCyan": color.FgHiCyan, |
| 147 |
"fgHiWhite": color.FgHiWhite, |
| 148 |
|
| 149 |
// background text colors |
| 150 |
"bgBlack": color.BgBlack, |
| 151 |
"bgRed": color.BgRed, |
| 152 |
"bgGreen": color.BgGreen, |
| 153 |
"bgYellow": color.BgYellow, |
| 154 |
"bgBlue": color.BgBlue, |
| 155 |
"bgMagenta": color.BgMagenta, |
| 156 |
"bgCyan": color.BgCyan, |
| 157 |
"bgWhite": color.BgWhite, |
| 158 |
|
| 159 |
// background Hi-Intensity text colors |
| 160 |
"bgHiBlack": color.BgHiBlack, |
| 161 |
"bgHiRed": color.BgHiRed, |
| 162 |
"bgHiGreen": color.BgHiGreen, |
| 163 |
"bgHiYellow": color.BgHiYellow, |
| 164 |
"bgHiBlue": color.BgHiBlue, |
| 165 |
"bgHiMagenta": color.BgHiMagenta, |
| 166 |
"bgHiCyan": color.BgHiCyan, |
| 167 |
"bgHiWhite": color.BgHiWhite, |
| 168 |
} |
| 169 |
|
| 170 |
// validColor will make sure the given color is actually allowed. |
| 171 |
func validColor(c string) bool { |
| 172 |
return validColors[c] |
| 173 |
} |
| 174 |
|
| 175 |
// Spinner struct to hold the provided options. |
| 176 |
type Spinner struct { |
| 177 |
mu *sync.RWMutex |
| 178 |
Delay time.Duration // Delay is the speed of the indicator |
| 179 |
chars []string // chars holds the chosen character set |
| 180 |
Prefix string // Prefix is the text preppended to the indicator |
| 181 |
Suffix string // Suffix is the text appended to the indicator |
| 182 |
FinalMSG string // string displayed after Stop() is called |
| 183 |
lastOutput string // last character(set) written |
| 184 |
color func(a ...interface{}) string // default color is white |
| 185 |
Writer io.Writer // to make testing better, exported so users have access. Use `WithWriter` to update after initialization. |
| 186 |
active bool // active holds the state of the spinner |
| 187 |
stopChan chan struct{} // stopChan is a channel used to stop the indicator |
| 188 |
HideCursor bool // hideCursor determines if the cursor is visible |
| 189 |
PreUpdate func(s *Spinner) // will be triggered before every spinner update |
| 190 |
PostUpdate func(s *Spinner) // will be triggered after every spinner update |
| 191 |
} |
| 192 |
|
| 193 |
// New provides a pointer to an instance of Spinner with the supplied options. |
| 194 |
func New(cs []string, d time.Duration, options ...Option) *Spinner { |
| 195 |
s := &Spinner{ |
| 196 |
Delay: d, |
| 197 |
chars: cs, |
| 198 |
color: color.New(color.FgWhite).SprintFunc(), |
| 199 |
mu: &sync.RWMutex{}, |
| 200 |
Writer: color.Output, |
| 201 |
stopChan: make(chan struct{}, 1), |
| 202 |
active: false, |
| 203 |
HideCursor: true, |
| 204 |
} |
| 205 |
|
| 206 |
for _, option := range options { |
| 207 |
option(s) |
| 208 |
} |
| 209 |
|
| 210 |
return s |
| 211 |
} |
| 212 |
|
| 213 |
// Option is a function that takes a spinner and applies |
| 214 |
// a given configuration. |
| 215 |
type Option func(*Spinner) |
| 216 |
|
| 217 |
// Options contains fields to configure the spinner. |
| 218 |
type Options struct { |
| 219 |
Color string |
| 220 |
Suffix string |
| 221 |
FinalMSG string |
| 222 |
HideCursor bool |
| 223 |
} |
| 224 |
|
| 225 |
// WithColor adds the given color to the spinner. |
| 226 |
func WithColor(color string) Option { |
| 227 |
return func(s *Spinner) { |
| 228 |
s.Color(color) |
| 229 |
} |
| 230 |
} |
| 231 |
|
| 232 |
// WithSuffix adds the given string to the spinner |
| 233 |
// as the suffix. |
| 234 |
func WithSuffix(suffix string) Option { |
| 235 |
return func(s *Spinner) { |
| 236 |
s.Suffix = suffix |
| 237 |
} |
| 238 |
} |
| 239 |
|
| 240 |
// WithFinalMSG adds the given string ot the spinner |
| 241 |
// as the final message to be written. |
| 242 |
func WithFinalMSG(finalMsg string) Option { |
| 243 |
return func(s *Spinner) { |
| 244 |
s.FinalMSG = finalMsg |
| 245 |
} |
| 246 |
} |
| 247 |
|
| 248 |
// WithHiddenCursor hides the cursor |
| 249 |
// if hideCursor = true given. |
| 250 |
func WithHiddenCursor(hideCursor bool) Option { |
| 251 |
return func(s *Spinner) { |
| 252 |
s.HideCursor = hideCursor |
| 253 |
} |
| 254 |
} |
| 255 |
|
| 256 |
// WithWriter adds the given writer to the spinner. This |
| 257 |
// function should be favored over directly assigning to |
| 258 |
// the struct value. |
| 259 |
func WithWriter(w io.Writer) Option { |
| 260 |
return func(s *Spinner) { |
| 261 |
s.mu.Lock() |
| 262 |
s.Writer = w |
| 263 |
s.mu.Unlock() |
| 264 |
} |
| 265 |
} |
| 266 |
|
| 267 |
// Active will return whether or not the spinner is currently active. |
| 268 |
func (s *Spinner) Active() bool { |
| 269 |
return s.active |
| 270 |
} |
| 271 |
|
| 272 |
// Start will start the indicator. |
| 273 |
func (s *Spinner) Start() { |
| 274 |
s.mu.Lock() |
| 275 |
if s.active || !isRunningInTerminal() { |
| 276 |
s.mu.Unlock() |
| 277 |
return |
| 278 |
} |
| 279 |
if s.HideCursor && !isWindowsTerminalOnWindows { |
| 280 |
// hides the cursor |
| 281 |
fmt.Fprint(s.Writer, "\033[?25l") |
| 282 |
} |
| 283 |
s.active = true |
| 284 |
s.mu.Unlock() |
| 285 |
|
| 286 |
go func() { |
| 287 |
for { |
| 288 |
for i := 0; i < len(s.chars); i++ { |
| 289 |
select { |
| 290 |
case <-s.stopChan: |
| 291 |
return |
| 292 |
default: |
| 293 |
s.mu.Lock() |
| 294 |
if !s.active { |
| 295 |
s.mu.Unlock() |
| 296 |
return |
| 297 |
} |
| 298 |
if !isWindowsTerminalOnWindows { |
| 299 |
s.erase() |
| 300 |
} |
| 301 |
|
| 302 |
if s.PreUpdate != nil { |
| 303 |
s.PreUpdate(s) |
| 304 |
} |
| 305 |
|
| 306 |
var outColor string |
| 307 |
if runtime.GOOS == "windows" { |
| 308 |
if s.Writer == os.Stderr { |
| 309 |
outColor = fmt.Sprintf("\r%s%s%s", s.Prefix, s.chars[i], s.Suffix) |
| 310 |
} else { |
| 311 |
outColor = fmt.Sprintf("\r%s%s%s", s.Prefix, s.color(s.chars[i]), s.Suffix) |
| 312 |
} |
| 313 |
} else { |
| 314 |
outColor = fmt.Sprintf("\r%s%s%s", s.Prefix, s.color(s.chars[i]), s.Suffix) |
| 315 |
} |
| 316 |
outPlain := fmt.Sprintf("\r%s%s%s", s.Prefix, s.chars[i], s.Suffix) |
| 317 |
fmt.Fprint(s.Writer, outColor) |
| 318 |
s.lastOutput = outPlain |
| 319 |
delay := s.Delay |
| 320 |
|
| 321 |
if s.PostUpdate != nil { |
| 322 |
s.PostUpdate(s) |
| 323 |
} |
| 324 |
|
| 325 |
s.mu.Unlock() |
| 326 |
time.Sleep(delay) |
| 327 |
} |
| 328 |
} |
| 329 |
} |
| 330 |
}() |
| 331 |
} |
| 332 |
|
| 333 |
// Stop stops the indicator. |
| 334 |
func (s *Spinner) Stop() { |
| 335 |
s.mu.Lock() |
| 336 |
defer s.mu.Unlock() |
| 337 |
if s.active { |
| 338 |
s.active = false |
| 339 |
if s.HideCursor && !isWindowsTerminalOnWindows { |
| 340 |
// makes the cursor visible |
| 341 |
fmt.Fprint(s.Writer, "\033[?25h") |
| 342 |
} |
| 343 |
s.erase() |
| 344 |
if s.FinalMSG != "" { |
| 345 |
if isWindowsTerminalOnWindows { |
| 346 |
fmt.Fprint(s.Writer, "\r", s.FinalMSG) |
| 347 |
} else { |
| 348 |
fmt.Fprint(s.Writer, s.FinalMSG) |
| 349 |
} |
| 350 |
} |
| 351 |
s.stopChan <- struct{}{} |
| 352 |
} |
| 353 |
} |
| 354 |
|
| 355 |
// Restart will stop and start the indicator. |
| 356 |
func (s *Spinner) Restart() { |
| 357 |
s.Stop() |
| 358 |
s.Start() |
| 359 |
} |
| 360 |
|
| 361 |
// Reverse will reverse the order of the slice assigned to the indicator. |
| 362 |
func (s *Spinner) Reverse() { |
| 363 |
s.mu.Lock() |
| 364 |
for i, j := 0, len(s.chars)-1; i < j; i, j = i+1, j-1 { |
| 365 |
s.chars[i], s.chars[j] = s.chars[j], s.chars[i] |
| 366 |
} |
| 367 |
s.mu.Unlock() |
| 368 |
} |
| 369 |
|
| 370 |
// Color will set the struct field for the given color to be used. The spinner |
| 371 |
// will need to be explicitly restarted. |
| 372 |
func (s *Spinner) Color(colors ...string) error { |
| 373 |
colorAttributes := make([]color.Attribute, len(colors)) |
| 374 |
|
| 375 |
// Verify colours are valid and place the appropriate attribute in the array |
| 376 |
for index, c := range colors { |
| 377 |
if !validColor(c) { |
| 378 |
return errInvalidColor |
| 379 |
} |
| 380 |
colorAttributes[index] = colorAttributeMap[c] |
| 381 |
} |
| 382 |
|
| 383 |
s.mu.Lock() |
| 384 |
s.color = color.New(colorAttributes...).SprintFunc() |
| 385 |
s.mu.Unlock() |
| 386 |
return nil |
| 387 |
} |
| 388 |
|
| 389 |
// UpdateSpeed will set the indicator delay to the given value. |
| 390 |
func (s *Spinner) UpdateSpeed(d time.Duration) { |
| 391 |
s.mu.Lock() |
| 392 |
s.Delay = d |
| 393 |
s.mu.Unlock() |
| 394 |
} |
| 395 |
|
| 396 |
// UpdateCharSet will change the current character set to the given one. |
| 397 |
func (s *Spinner) UpdateCharSet(cs []string) { |
| 398 |
s.mu.Lock() |
| 399 |
s.chars = cs |
| 400 |
s.mu.Unlock() |
| 401 |
} |
| 402 |
|
| 403 |
// erase deletes written characters on the current line. |
| 404 |
// Caller must already hold s.lock. |
| 405 |
func (s *Spinner) erase() { |
| 406 |
n := utf8.RuneCountInString(s.lastOutput) |
| 407 |
if runtime.GOOS == "windows" && !isWindowsTerminalOnWindows { |
| 408 |
clearString := "\r" + strings.Repeat(" ", n) + "\r" |
| 409 |
fmt.Fprint(s.Writer, clearString) |
| 410 |
s.lastOutput = "" |
| 411 |
return |
| 412 |
} |
| 413 |
|
| 414 |
// Taken from https://en.wikipedia.org/wiki/ANSI_escape_code: |
| 415 |
// \r - Carriage return - Moves the cursor to column zero |
| 416 |
// \033[K - Erases part of the line. If n is 0 (or missing), clear from |
| 417 |
// cursor to the end of the line. If n is 1, clear from cursor to beginning |
| 418 |
// of the line. If n is 2, clear entire line. Cursor position does not |
| 419 |
// change. |
| 420 |
fmt.Fprintf(s.Writer, "\r\033[K") |
| 421 |
s.lastOutput = "" |
| 422 |
} |
| 423 |
|
| 424 |
// Lock allows for manual control to lock the spinner. |
| 425 |
func (s *Spinner) Lock() { |
| 426 |
s.mu.Lock() |
| 427 |
} |
| 428 |
|
| 429 |
// Unlock allows for manual control to unlock the spinner. |
| 430 |
func (s *Spinner) Unlock() { |
| 431 |
s.mu.Unlock() |
| 432 |
} |
| 433 |
|
| 434 |
// GenerateNumberSequence will generate a slice of integers at the |
| 435 |
// provided length and convert them each to a string. |
| 436 |
func GenerateNumberSequence(length int) []string { |
| 437 |
numSeq := make([]string, length) |
| 438 |
for i := 0; i < length; i++ { |
| 439 |
numSeq[i] = strconv.Itoa(i) |
| 440 |
} |
| 441 |
return numSeq |
| 442 |
} |
| 443 |
|
| 444 |
// isRunningInTerminal check if stdout file descriptor is terminal |
| 445 |
func isRunningInTerminal() bool { |
| 446 |
return isatty.IsTerminal(os.Stdout.Fd()) |
| 447 |
} |