Implement dry-run modes and signal cancellation
Implement dry-run modes and signal cancellation
A dry run previews a change without applying it. Put the decision before the mutation boundary. signal.NotifyContext also lets a CLI cancel work on interrupt. Here the mutation is only an in-memory counter.
package main
import ( "context" "fmt" "io" "os")
func apply(ctx context.Context, dry bool, out io.Writer, change func() error) error { if err := ctx.Err(); err != nil { return err } if dry { _, err := fmt.Fprintln(out, "would update report") return err } return change()}func main() { n := 0 err := apply(context.Background(), true, os.Stdout, func() error { n++; return nil }) fmt.Println(n, err == nil)}Both modes should share argument and plan validation before apply. A preview is not a guarantee of success: permissions and concurrent state may differ when applying the change. Document any reads or other side effects your preview performs.
Expected output:
would update report0 trueConnect cancellation to the command boundary
package main
import ( "context" "errors" "fmt" "io" "os" "os/signal")
func apply(ctx context.Context, dry bool, out io.Writer, change func() error) error { if err := ctx.Err(); err != nil { return err } if dry { _, err := fmt.Fprintln(out, "would update report") return err } return change()}func main() { parent, cancel := context.WithCancel(context.Background()) defer cancel() ctx, stop := signal.NotifyContext(parent, os.Interrupt) defer stop() cancel() <-ctx.Done() n := 0 err := apply(ctx, false, io.Discard, func() error { n++; return nil }) fmt.Println(n, errors.Is(err, context.Canceled))}NotifyContext cancels on a registered signal, parent cancellation or stop. Here parent cancellation makes the example repeatable. Defer stop inside run to release resources. Cancellation is cooperative: long operations must check context; a cancellation between a check and a write cannot undo a completed change. Signal delivery varies by OS.
Expected output:
0 trueTry it locally
Run apply with dry=false and an uncanceled context; count mutation calls.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
CLI 06: Implement dry-run modes and signal cancellation
Check the lesson objective before moving on.
What must a dry run avoid?
What does context cancellation guarantee about a completed write?