From 614896285e6a26fda75ba0033411745b0a34605e Mon Sep 17 00:00:00 2001 From: Anatolii Chakkaev Date: Thu, 29 Feb 2024 11:01:17 +0000 Subject: [PATCH] Update elapsed time when using Set --- README.md | 24 ++++++++++++++++++++++++ bar.go | 17 +++++++++++++++-- 2 files changed, 39 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 8bcfb1f..3e8c4bc 100644 --- a/README.md +++ b/README.md @@ -131,6 +131,30 @@ wg.Wait() uiprogress.Stop() ``` +### `Set` counter and tracking progress of the external process + +You can use progress bar to track the progress of any external process, for example +the process of execution of github actions workflow run. To get an accurate +elapsed time use `.WithStartedAt(time)` to initialize starting time for the progress +bar. + +``` +job, _ := FetchExternalJob() // request for external resource +totalStepsCount := len(job.Steps) + +uiprogress.Start() +bar := uiprogress.AddBar(totalStepsCount).WithStartedAt(job.StartedAt).AppendCompleted().PrependElapsed() +for !job.IsCompleted { + // poll resource status + job, _ = FetchExternalJob() + // update progress + bar.Set(job.GetCurrentStepNumber()) + // wait a second + time.Sleep(time.Second) +} +uiprogress.Stop() +``` + ## Installation ```sh diff --git a/bar.go b/bar.go index ffde171..527dba7 100644 --- a/bar.go +++ b/bar.go @@ -95,6 +95,8 @@ func (b *Bar) Set(n int) error { if n > b.Total { return ErrMaxCurrentReached } + + b.updateElapsed() b.current = n return nil } @@ -108,13 +110,17 @@ func (b *Bar) Incr() bool { if n > b.Total { return false } + b.updateElapsed() + b.current = n + return true +} + +func (b *Bar) updateElapsed() { var t time.Time if b.TimeStarted == t { b.TimeStarted = time.Now() } b.timeElapsed = time.Since(b.TimeStarted) - b.current = n - return true } // Current returns the current progress of the bar @@ -172,6 +178,13 @@ func (b *Bar) PrependElapsed() *Bar { return b } +// WithStartedAt initializes time of start for calculation of elapsed time +func (b *Bar) WithStartedAt(t time.Time) *Bar { + b.TimeStarted = t + b.updateElapsed() + return b +} + // Bytes returns the byte presentation of the progress bar func (b *Bar) Bytes() []byte { completedWidth := int(float64(b.Width) * (b.CompletedPercent() / 100.00))