Some checks are pending
Docs Deploy / build_and_deploy (push) Waiting to run
Generate Docs / cli (push) Waiting to run
Generate Config Doc / cli (push) Waiting to run
Go formatting / go-formatting (push) Waiting to run
Check links / markdown-link-check (push) Waiting to run
Integration / pre-test (push) Waiting to run
Integration / test on (push) Blocked by required conditions
Integration / status (push) Blocked by required conditions
Lint / Lint Go code (push) Waiting to run
Test / test (ubuntu-latest) (push) Waiting to run
34 lines
689 B
Go
34 lines
689 B
Go
package clictx
|
|
|
|
import (
|
|
"context"
|
|
"os"
|
|
"os/signal"
|
|
)
|
|
|
|
// From creates a new context from ctx that is canceled when an exit signal received.
|
|
func From(ctx context.Context) context.Context {
|
|
var (
|
|
ctxend, cancel = context.WithCancel(ctx)
|
|
quit = make(chan os.Signal, 1)
|
|
)
|
|
signal.Notify(quit, os.Interrupt)
|
|
go func() {
|
|
<-quit
|
|
cancel()
|
|
}()
|
|
return ctxend
|
|
}
|
|
|
|
// Do runs fn and waits for its result unless ctx is canceled.
|
|
// Returns fn result or canceled context error.
|
|
func Do(ctx context.Context, fn func() error) error {
|
|
errc := make(chan error)
|
|
go func() { errc <- fn() }()
|
|
select {
|
|
case err := <-errc:
|
|
return err
|
|
case <-ctx.Done():
|
|
return ctx.Err()
|
|
}
|
|
}
|