From 6b88f0a36b216c8656b302f825a9526b6a1bc6e1 Mon Sep 17 00:00:00 2001 From: Dylan Lott Date: Wed, 17 Oct 2018 14:23:44 -0600 Subject: [PATCH] Moves CollectErrors into pkg/utils (#493) Merging but creating a PR for tests shortly --- cmd/captplanet/run.go | 32 +------------------------------- pkg/utils/utils.go | 31 +++++++++++++++++++++++++++++++ 2 files changed, 32 insertions(+), 31 deletions(-) diff --git a/cmd/captplanet/run.go b/cmd/captplanet/run.go index 7e927ea6e..eb6d689aa 100644 --- a/cmd/captplanet/run.go +++ b/cmd/captplanet/run.go @@ -147,35 +147,5 @@ func cmdRun(cmd *cobra.Command, args []string) (err error) { errch <- runCfg.Uplink.Run(ctx) }() - return collectErrors(errch, 5*time.Second) -} - -// collectErrors returns first error from channel and all errors that happen within duration -func collectErrors(errch chan error, duration time.Duration) error { - errch = discardNil(errch) - errs := []error{<-errch} - timeout := time.After(duration) - for { - select { - case err := <-errch: - errs = append(errs, err) - case <-timeout: - return utils.CombineErrors(errs...) - } - } -} - -// discard nil errors that are returned from services -func discardNil(ch chan error) chan error { - r := make(chan error) - go func() { - for err := range ch { - if err == nil { - continue - } - r <- err - } - close(r) - }() - return r + return utils.CollectErrors(errch, 5*time.Second) } diff --git a/pkg/utils/utils.go b/pkg/utils/utils.go index e3a0132b4..6a556efa3 100644 --- a/pkg/utils/utils.go +++ b/pkg/utils/utils.go @@ -8,6 +8,7 @@ import ( "encoding/gob" "net/url" "strings" + "time" ) // GetBytes transforms an empty interface type into a byte slice @@ -75,3 +76,33 @@ func (errs combinedError) Error() string { } return "" } + +// CollectErrors returns first error from channel and all errors that happen within duration +func CollectErrors(errch chan error, duration time.Duration) error { + errch = discardNil(errch) + errs := []error{<-errch} + timeout := time.After(duration) + for { + select { + case err := <-errch: + errs = append(errs, err) + case <-timeout: + return CombineErrors(errs...) + } + } +} + +// discard nil errors that are returned from services +func discardNil(ch chan error) chan error { + r := make(chan error) + go func() { + for err := range ch { + if err == nil { + continue + } + r <- err + } + close(r) + }() + return r +}