blob: bad24ea2935eb66b30e315cd55e5823f535d4d43 [file] [log] [blame]
Lorenz Brun78e59052021-12-15 18:46:18 +01001package clicontext
2
3import (
4 "context"
5 "os"
6 "os/signal"
7)
8
9// WithInterrupt returns a context for use in a command-line utility. It gets
10// cancelled if the user interrupts the command, for example by pressing
11// Ctrl+C.
12func WithInterrupt(parent context.Context) context.Context {
13 ctx, cancel := context.WithCancel(parent)
14 c := make(chan os.Signal, 1)
15 signal.Notify(c, os.Interrupt)
16 go func() {
17 <-c
18 cancel()
19 }()
20 return ctx
21}