-
Notifications
You must be signed in to change notification settings - Fork 31
/
main.go
57 lines (47 loc) · 1.3 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
// Package main contains sq's main function.
package main
import (
"context"
"os"
"os/signal"
"time"
_ "time/tzdata"
"github.com/neilotoole/sq/cli"
"github.com/neilotoole/sq/libsq/core/errz"
)
func main() {
const shutdownTimeout = time.Second * 2
var err error
ctx, cancelFn := context.WithCancel(context.Background())
defer func() {
cancelFn()
if err != nil {
if code := errz.ExitCode(err); code > 0 {
os.Exit(code)
}
os.Exit(1)
}
}()
go func() {
// Listen for interrupt signal (Ctrl-C) and call cancelFn.
stopCh := make(chan os.Signal, 1)
signal.Notify(stopCh, os.Interrupt)
<-stopCh
// The context cancellation should propagate down the stack,
// and cli.Execute should return, with the context.Canceled error.
cancelFn()
// But... in theory the main goroutine could be blocked on something.
// So, we have some hard shutdown possibilities.
select {
case <-time.After(shutdownTimeout):
// We've waited long enough for a graceful shutdown.
cli.PrintError(ctx, nil, errz.New("hard shutdown (timeout)"))
case <-stopCh:
// We received a second interrupt from the user: they're really
// serious about exiting.
cli.PrintError(ctx, nil, errz.New("hard shutdown"))
}
os.Exit(1)
}()
err = cli.Execute(ctx, os.Stdin, os.Stdout, os.Stderr, os.Args[1:])
}