|
| 1 | +// Package progress provides a simple progress indicator |
| 2 | +// for tracking the progress for input provided via stdin. |
| 3 | +// |
| 4 | +// It shows a progress bar when the limit is known and some simple stats when not. |
| 5 | +// |
| 6 | +// ------------------------------------ |
| 7 | +// #!/bin/bash |
| 8 | +// |
| 9 | +// urls=( |
| 10 | +// |
| 11 | +// "http://example.com/file1.txt" |
| 12 | +// "http://example.com/file2.txt" |
| 13 | +// "http://example.com/file3.txt" |
| 14 | +// |
| 15 | +// ) |
| 16 | +// |
| 17 | +// for url in "${urls[@]}"; do |
| 18 | +// |
| 19 | +// wget -q -nc "$url" |
| 20 | +// echo "Downloaded: $url" |
| 21 | +// |
| 22 | +// done | gum progress --show-output --limit ${#urls[@]} |
| 23 | +// ------------------------------------ |
| 24 | +package progress |
| 25 | + |
| 26 | +import ( |
| 27 | + "bufio" |
| 28 | + "fmt" |
| 29 | + "os" |
| 30 | + |
| 31 | + tea "github.com/charmbracelet/bubbletea" |
| 32 | + "github.com/mattn/go-isatty" |
| 33 | +) |
| 34 | + |
| 35 | +func (o Options) GetFormatString() string { |
| 36 | + if o.Format != "" { |
| 37 | + return o.Format |
| 38 | + } |
| 39 | + |
| 40 | + switch { |
| 41 | + case o.Limit == 0 && o.Title == "": |
| 42 | + return "[Elapsed ~ {Elapsed}] Iter {Iter}" |
| 43 | + case o.Limit == 0 && o.Title != "": |
| 44 | + return "[Elapsed ~ {Elapsed}] Iter {Iter} ~ {Title}" |
| 45 | + case o.Limit > 0 && o.Title == "": |
| 46 | + return "{Bar} {Pct}" |
| 47 | + case o.Limit > 0 && o.Title != "": |
| 48 | + return "{Title} ~ {Bar} {Pct}" |
| 49 | + default: |
| 50 | + return "{Iter}" |
| 51 | + } |
| 52 | +} |
| 53 | + |
| 54 | +func (o Options) Run() error { |
| 55 | + m := &model{ |
| 56 | + reader: bufio.NewReader(os.Stdin), |
| 57 | + output: o.ShowOutput, |
| 58 | + isTTY: isatty.IsTerminal(os.Stdout.Fd()), |
| 59 | + progressIndicator: o.ProgressIndicator, |
| 60 | + hideProgressIndicator: o.HideProgressIndicator, |
| 61 | + |
| 62 | + bfmt: newBarFormatter(o.GetFormatString(), o.ProgressColor), |
| 63 | + binfo: newBarInfo(o.TitleStyle.ToLipgloss().Render(o.Title), o.Limit), |
| 64 | + } |
| 65 | + p := tea.NewProgram(m, tea.WithOutput(os.Stderr)) |
| 66 | + if _, err := p.Run(); err != nil { |
| 67 | + return fmt.Errorf("failed to run progress: %w", err) |
| 68 | + } |
| 69 | + |
| 70 | + return m.err |
| 71 | +} |
0 commit comments