From 2ec720b802af37dd2a1cadd64212e5d8777fad27 Mon Sep 17 00:00:00 2001 From: Harsh Seth Date: Fri, 2 Oct 2020 21:52:52 +0530 Subject: [PATCH] Added IsFinished method to progress bar. (#77) Add IsFinished Fixes #77 --- examples/customization/main.go | 24 +++++++++++++++++++----- progressbar.go | 5 +++++ progressbar_test.go | 27 +++++++++++++++++++++++++++ 3 files changed, 51 insertions(+), 5 deletions(-) diff --git a/examples/customization/main.go b/examples/customization/main.go index 5bb9b57..acb8b26 100644 --- a/examples/customization/main.go +++ b/examples/customization/main.go @@ -1,6 +1,7 @@ package main import ( + "fmt" "time" "github.com/k0kubun/go-ansi" @@ -8,6 +9,8 @@ import ( ) func main() { + doneCh := make(chan struct{}) + bar := progressbar.NewOptions(1000, progressbar.OptionSetWriter(ansi.NewAnsiStdout()), progressbar.OptionEnableColorCodes(true), @@ -20,9 +23,20 @@ func main() { SaucerPadding: " ", BarStart: "[", BarEnd: "]", - })) - for i := 0; i < 1000; i++ { - bar.Add(1) - time.Sleep(5 * time.Millisecond) - } + }), + progressbar.OptionOnCompletion(func() { + doneCh <- struct{}{} + }), + ) + + go func() { + for i := 0; i < 1000; i++ { + bar.Add(1) + time.Sleep(5 * time.Millisecond) + } + }() + + // got notified that progress bar is complete. + <-doneCh + fmt.Println("\n ======= progress bar completed ==========\n") } diff --git a/progressbar.go b/progressbar.go index d0244c4..d068a52 100644 --- a/progressbar.go +++ b/progressbar.go @@ -477,6 +477,11 @@ func (p *ProgressBar) ChangeMax64(newMax int64) { p.Add(0) // re-render } +// IsFinished returns true if progreess bar is completed +func (p *ProgressBar) IsFinished() bool { + return p.state.finished +} + // render renders the progress bar, updating the maximum // rendered line width. this function is not thread-safe, // so it must be called with an acquired lock. diff --git a/progressbar_test.go b/progressbar_test.go index fdb8610..16704b3 100644 --- a/progressbar_test.go +++ b/progressbar_test.go @@ -197,6 +197,33 @@ func TestSpinnerType(t *testing.T) { } } +func Test_IsFinished(t *testing.T) { + isCalled := false + bar := NewOptions(72, OptionOnCompletion(func() { + isCalled = true + })) + + // Test1: If bar is not fully completed. + bar.Add(5) + if bar.IsFinished() || isCalled { + t.Errorf("Successfully tested bar is not yet finished.") + } + + // Test2: Bar fully completed. + bar.Add(67) + if !bar.IsFinished() || !isCalled { + t.Errorf("Successfully tested bar is finished.") + } + + // Test3: If increases maximum bytes error should be thrown and + // bar finished will remain false. + bar.Reset() + err := bar.Add(73) + if err == nil || bar.IsFinished() { + t.Errorf("Successfully got error when bytes increases max bytes, bar finished: %v", bar.IsFinished()) + } +} + func ExampleIgnoreLength_WithSpeed() { /* IgnoreLength test with iterations and count