Browse Source

Refactor calling the progress writer to make it easier

Djordje Lukic 5 years ago
parent
commit
a1bb04ebe1
3 changed files with 32 additions and 37 deletions
  1. 2 19
      cli/cmd/compose/up.go
  2. 4 18
      cli/cmd/run/run.go
  3. 26 0
      progress/writer.go

+ 2 - 19
cli/cmd/compose/up.go

@@ -30,10 +30,8 @@ package compose
 import (
 	"context"
 	"errors"
-	"os"
 
 	"github.com/spf13/cobra"
-	"golang.org/x/sync/errgroup"
 
 	"github.com/docker/api/client"
 	"github.com/docker/api/compose"
@@ -67,22 +65,7 @@ func runUp(ctx context.Context, opts compose.ProjectOptions) error {
 		return errors.New("compose not implemented in current context")
 	}
 
-	eg, _ := errgroup.WithContext(ctx)
-	w, err := progress.NewWriter(os.Stderr)
-	if err != nil {
-		return err
-	}
-	eg.Go(func() error {
-		return w.Start(context.Background())
-	})
-
-	ctx = progress.WithContextWriter(ctx, w)
-
-	eg.Go(func() error {
-		defer w.Stop()
-		err := composeService.Up(ctx, opts)
-		return err
+	return progress.Run(ctx, func(ctx context.Context) error {
+		return composeService.Up(ctx, opts)
 	})
-
-	return eg.Wait()
 }

+ 4 - 18
cli/cmd/run/run.go

@@ -30,10 +30,8 @@ package run
 import (
 	"context"
 	"fmt"
-	"os"
 
 	"github.com/spf13/cobra"
-	"golang.org/x/sync/errgroup"
 
 	"github.com/docker/api/cli/options/run"
 	"github.com/docker/api/client"
@@ -71,23 +69,11 @@ func runRun(ctx context.Context, image string, opts run.Opts) error {
 		return err
 	}
 
-	eg, _ := errgroup.WithContext(ctx)
-	w, err := progress.NewWriter(os.Stderr)
-	if err != nil {
-		return err
-	}
-	eg.Go(func() error {
-		return w.Start(context.Background())
-	})
-
-	ctx = progress.WithContextWriter(ctx, w)
-
-	eg.Go(func() error {
-		defer w.Stop()
+	err = progress.Run(ctx, func(ctx context.Context) error {
 		return c.ContainerService().Run(ctx, containerConfig)
 	})
-
-	err = eg.Wait()
-	fmt.Println(opts.Name)
+	if err == nil {
+		fmt.Println(opts.Name)
+	}
 	return err
 }

+ 26 - 0
progress/writer.go

@@ -2,11 +2,13 @@ package progress
 
 import (
 	"context"
+	"os"
 	"sync"
 	"time"
 
 	"github.com/containerd/console"
 	"github.com/moby/term"
+	"golang.org/x/sync/errgroup"
 )
 
 // EventStatus indicates the status of an action
@@ -59,6 +61,30 @@ func ContextWriter(ctx context.Context) Writer {
 	return s
 }
 
+type progressFunc func(context.Context) error
+
+// Run will run a writer and the progress function
+// in parallel
+func Run(ctx context.Context, pf progressFunc) error {
+	eg, _ := errgroup.WithContext(ctx)
+	w, err := NewWriter(os.Stderr)
+	if err != nil {
+		return err
+	}
+	eg.Go(func() error {
+		return w.Start(context.Background())
+	})
+
+	ctx = WithContextWriter(ctx, w)
+
+	eg.Go(func() error {
+		defer w.Stop()
+		return pf(ctx)
+	})
+
+	return eg.Wait()
+}
+
 // NewWriter returns a new multi-progress writer
 func NewWriter(out console.File) (Writer, error) {
 	_, isTerminal := term.GetFdInfo(out)