Skip to content

Commit

Permalink
add program with context
Browse files Browse the repository at this point in the history
  • Loading branch information
dcentelles committed Jan 9, 2025
1 parent d07e133 commit 92eaab9
Showing 1 changed file with 16 additions and 2 deletions.
18 changes: 16 additions & 2 deletions program/program.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
package program

import (
"context"
"errors"
"fmt"
"io"
Expand Down Expand Up @@ -37,7 +38,7 @@ func reportProgress(reportChan chan<- ProgressReport, stage string, progress int
}
}

func sync(rw io.ReadWriter, progress chan<- ProgressReport) error {
func sync(ctx context.Context, rw io.ReadWriter, progress chan<- ProgressReport) error {
var err error

for i := 0; i < maxSyncAttempts; i++ {
Expand All @@ -52,6 +53,9 @@ func sync(rw io.ReadWriter, progress chan<- ProgressReport) error {
} else if !errors.Is(err, protocol.ErrNotSynced) {
return err
}
if ctx.Err() != nil {
return ctx.Err()
}
}

return err
Expand All @@ -62,11 +66,15 @@ func align(val, to uint32) uint32 {
}

func Program(rw io.ReadWriter, img *Image, progress chan<- ProgressReport) error {
return ProgramWithCtx(context.Background(), rw, img, progress)
}

func ProgramWithCtx(ctx context.Context, rw io.ReadWriter, img *Image, progress chan<- ProgressReport) error {
if progress != nil {
defer close(progress)
}

err := sync(rw, progress)
err := sync(ctx, rw, progress)
if err != nil {
return fmt.Errorf("sync: %v", err)
}
Expand Down Expand Up @@ -106,6 +114,9 @@ func Program(rw io.ReadWriter, img *Image, progress chan<- ProgressReport) error
if err != nil {
return fmt.Errorf("erase: %v", err)
}
if ctx.Err() != nil {
return ctx.Err()
}
}

reportProgress(progress, "Writing", 0, len(data))
Expand All @@ -125,6 +136,9 @@ func Program(rw io.ReadWriter, img *Image, progress chan<- ProgressReport) error
if err != nil {
return fmt.Errorf("write: %v", err)
}
if ctx.Err() != nil {
return ctx.Err()
}
}

reportProgress(progress, "Finalising", 0, 1)
Expand Down

0 comments on commit 92eaab9

Please sign in to comment.