sq/main.go

54 lines
1.2 KiB
Go
Raw Normal View History

2020-08-06 20:58:47 +03:00
// Package main contains sq's main function.
2016-10-17 07:14:01 +03:00
package main
import (
2020-08-06 20:58:47 +03:00
"context"
2016-10-17 07:14:01 +03:00
"os"
2020-08-06 20:58:47 +03:00
"os/signal"
"time"
_ "time/tzdata"
2016-10-17 07:14:01 +03:00
2020-08-06 20:58:47 +03:00
"github.com/neilotoole/sq/cli"
"github.com/neilotoole/sq/libsq/core/errz"
2016-10-17 07:14:01 +03:00
)
func main() {
const shutdownTimeout = time.Second * 2
var err error
2020-08-06 20:58:47 +03:00
ctx, cancelFn := context.WithCancel(context.Background())
defer func() {
cancelFn()
if err != nil {
os.Exit(1)
}
}()
2020-08-06 20:58:47 +03:00
go func() {
2024-01-27 04:42:27 +03:00
// Listen for interrupt signal (Ctrl-C) and call cancelFn.
stopCh := make(chan os.Signal, 1)
signal.Notify(stopCh, os.Interrupt)
2020-08-06 20:58:47 +03:00
<-stopCh
// The context cancellation should propagate down the stack,
// and cli.Execute should return, with the context.Canceled error.
2020-08-06 20:58:47 +03:00
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)
2020-08-06 20:58:47 +03:00
}()
err = cli.Execute(ctx, os.Stdin, os.Stdout, os.Stderr, os.Args[1:])
2016-10-17 07:14:01 +03:00
}