hub/internal/progress/progress.go
trvon c4ca0f1497
All checks were successful
release / build (push) Successful in 3m58s
progress: show self-update steps and a spinner on slow fleet calls
self-update prints each step (checking releases, verifying signature,
downloading with MB and percent, verifying sha256, replacing binary). Fleet
commands show a spinner after 400 ms while an API call is in flight. Output
goes to stderr on a terminal only; never with --json, TERM=dumb or
HUB_NO_PROGRESS=1. stdout and exit codes are unchanged.
2026-11-14 14:38:13 -07:00

186 lines
4.4 KiB
Go

// SPDX-License-Identifier: GPL-3.0-or-later
// Package progress draws small progress indicators on stderr. They are cosmetic: callers decide with Enabled
// whether to use them, and a Nop reporter stands in everywhere else. Nothing here writes to stdout.
package progress
import (
"fmt"
"io"
"os"
"sync"
"time"
)
// Reporter shows what a long operation is doing. A step stays open until the next Step, Done or Fail.
type Reporter interface {
Step(name string)
Bytes(done, total int64)
Done()
Fail()
}
// Nop is the reporter for non-interactive runs: it does nothing.
type Nop struct{}
func (Nop) Step(string) {}
func (Nop) Bytes(int64, int64) {}
func (Nop) Done() {}
func (Nop) Fail() {}
const clearLine = "\r\x1b[K"
// Term draws \r-updated lines on an io.Writer.
type Term struct {
mu sync.Mutex
w io.Writer
name string
open bool
}
// New returns a Term writing to w.
func New(w io.Writer) *Term { return &Term{w: w} }
// Step starts a step; a step still open is finished first.
func (t *Term) Step(name string) {
t.mu.Lock()
defer t.mu.Unlock()
t.finish("ok")
t.name, t.open = name, true
fmt.Fprint(t.w, clearLine+name)
}
// Bytes redraws the open step as `name 3.4/10.1 MB 34%`; an unknown total (<= 0) shows only the bytes done.
func (t *Term) Bytes(done, total int64) {
t.mu.Lock()
defer t.mu.Unlock()
if !t.open {
return
}
fmt.Fprint(t.w, clearLine+t.name+" "+FormatBytes(done, total))
}
// Done finishes the open step.
func (t *Term) Done() {
t.mu.Lock()
defer t.mu.Unlock()
t.finish("ok")
}
// Fail finishes the open step as failed.
func (t *Term) Fail() {
t.mu.Lock()
defer t.mu.Unlock()
t.finish("failed")
}
func (t *Term) finish(status string) {
if !t.open {
return
}
fmt.Fprint(t.w, clearLine+t.name+" "+status+"\n")
t.open = false
}
// FormatBytes renders done/total in MB with a percentage, e.g. `3.4/10.1 MB 34%`.
func FormatBytes(done, total int64) string {
const mb = 1024 * 1024
if total <= 0 {
return fmt.Sprintf("%.1f MB", float64(done)/mb)
}
pct := done * 100 / total
if pct > 100 {
pct = 100
}
return fmt.Sprintf("%.1f/%.1f MB %d%%", float64(done)/mb, float64(total)/mb, pct)
}
// Reader counts the bytes read from R and reports them.
type Reader struct {
R io.Reader
Total int64
Rep Reporter
done int64
}
// NewReader wraps r; rep nil means Nop.
func NewReader(r io.Reader, total int64, rep Reporter) *Reader {
if rep == nil {
rep = Nop{}
}
return &Reader{R: r, Total: total, Rep: rep}
}
func (r *Reader) Read(p []byte) (int, error) {
n, err := r.R.Read(p)
if n > 0 {
r.done += int64(n)
r.Rep.Bytes(r.done, r.Total)
}
return n, err
}
// Count is the number of bytes read so far.
func (r *Reader) Count() int64 { return r.done }
// IsTerminal reports whether w is an *os.File that is a character device (an interactive terminal).
func IsTerminal(w io.Writer) bool {
f, ok := w.(*os.File)
if !ok {
return false
}
st, err := f.Stat()
return err == nil && st.Mode()&os.ModeCharDevice != 0
}
// Enabled is the single gate: a terminal, not --json, HUB_NO_PROGRESS not 1, TERM not dumb.
func Enabled(tty, asJSON bool, lookup func(string) (string, bool)) bool {
if !tty || asJSON {
return false
}
if v, ok := lookup("HUB_NO_PROGRESS"); ok && v == "1" {
return false
}
if v, ok := lookup("TERM"); ok && v == "dumb" {
return false
}
return true
}
// SpinnerDelay is how long work must run before the spinner appears; faster calls print nothing. A var so tests can shorten it.
var SpinnerDelay = 400 * time.Millisecond
var frames = []string{"|", "/", "-", "\\"}
// Spin starts a spinner with label on w after delay and returns a stop function that clears the line. If stop
// runs before the delay, nothing was ever written. stop is safe to call more than once.
func Spin(w io.Writer, label string, delay time.Duration) (stop func()) {
quit := make(chan struct{})
finished := make(chan struct{})
go func() {
defer close(finished)
timer := time.NewTimer(delay)
defer timer.Stop()
select {
case <-quit:
return
case <-timer.C:
}
tick := time.NewTicker(100 * time.Millisecond)
defer tick.Stop()
for i := 0; ; i++ {
fmt.Fprint(w, clearLine+frames[i%len(frames)]+" "+label)
select {
case <-quit:
fmt.Fprint(w, clearLine)
return
case <-tick.C:
}
}
}()
var once sync.Once
return func() {
once.Do(func() { close(quit) })
<-finished
}
}