2023-11-15 00:33:16 +00:00
|
|
|
package progress
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"strings"
|
2024-08-12 18:46:32 +00:00
|
|
|
"sync/atomic"
|
2023-11-15 00:33:16 +00:00
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
type Spinner struct {
|
2024-08-12 18:46:32 +00:00
|
|
|
message atomic.Value
|
2023-11-15 00:33:16 +00:00
|
|
|
messageWidth int
|
|
|
|
|
|
|
|
parts []string
|
|
|
|
|
|
|
|
value int
|
|
|
|
|
|
|
|
ticker *time.Ticker
|
|
|
|
started time.Time
|
|
|
|
stopped time.Time
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewSpinner(message string) *Spinner {
|
|
|
|
s := &Spinner{
|
|
|
|
parts: []string{
|
|
|
|
"⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏",
|
|
|
|
},
|
|
|
|
started: time.Now(),
|
|
|
|
}
|
2024-08-12 18:46:32 +00:00
|
|
|
s.SetMessage(message)
|
2023-11-15 00:33:16 +00:00
|
|
|
go s.start()
|
|
|
|
return s
|
|
|
|
}
|
|
|
|
|
2024-08-12 18:46:32 +00:00
|
|
|
func (s *Spinner) SetMessage(message string) {
|
|
|
|
s.message.Store(message)
|
|
|
|
}
|
|
|
|
|
2023-11-15 00:33:16 +00:00
|
|
|
func (s *Spinner) String() string {
|
2023-11-19 18:43:21 +00:00
|
|
|
var sb strings.Builder
|
2024-08-12 18:46:32 +00:00
|
|
|
|
|
|
|
if message, ok := s.message.Load().(string); ok && len(message) > 0 {
|
|
|
|
message := strings.TrimSpace(message)
|
2023-11-15 00:33:16 +00:00
|
|
|
if s.messageWidth > 0 && len(message) > s.messageWidth {
|
|
|
|
message = message[:s.messageWidth]
|
|
|
|
}
|
|
|
|
|
2023-11-19 18:43:21 +00:00
|
|
|
fmt.Fprintf(&sb, "%s", message)
|
2023-11-19 00:23:03 +00:00
|
|
|
if padding := s.messageWidth - sb.Len(); padding > 0 {
|
|
|
|
sb.WriteString(strings.Repeat(" ", padding))
|
2023-11-15 00:33:16 +00:00
|
|
|
}
|
|
|
|
|
2023-11-19 18:43:21 +00:00
|
|
|
sb.WriteString(" ")
|
2023-11-15 00:33:16 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if s.stopped.IsZero() {
|
|
|
|
spinner := s.parts[s.value]
|
2023-11-19 18:43:21 +00:00
|
|
|
sb.WriteString(spinner)
|
|
|
|
sb.WriteString(" ")
|
2023-11-15 00:33:16 +00:00
|
|
|
}
|
|
|
|
|
2023-11-19 18:43:21 +00:00
|
|
|
return sb.String()
|
2023-11-15 00:33:16 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Spinner) start() {
|
|
|
|
s.ticker = time.NewTicker(100 * time.Millisecond)
|
|
|
|
for range s.ticker.C {
|
|
|
|
s.value = (s.value + 1) % len(s.parts)
|
|
|
|
if !s.stopped.IsZero() {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Spinner) Stop() {
|
|
|
|
if s.stopped.IsZero() {
|
|
|
|
s.stopped = time.Now()
|
|
|
|
}
|
|
|
|
}
|