-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathmain.go
More file actions
64 lines (56 loc) · 1.5 KB
/
main.go
File metadata and controls
64 lines (56 loc) · 1.5 KB
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
58
59
60
61
62
63
64
package main
import (
"context"
"errors"
"fmt"
"os"
"os/signal"
"syscall"
"go.uber.org/zap"
"github.com/timescale/tiger-cli/internal/tiger/cmd"
"github.com/timescale/tiger-cli/internal/tiger/logging"
)
func main() {
if err := run(); err != nil {
// Check if it's a custom exit code error
if exitErr, ok := err.(interface{ ExitCode() int }); ok {
os.Exit(exitErr.ExitCode())
}
os.Exit(1)
}
os.Exit(0)
}
func run() (err error) {
ctx, cancel := notifyContext(context.Background())
defer func() {
cancel()
if r := recover(); r != nil {
err = errors.Join(err, fmt.Errorf("panic: %v", r))
_, _ = fmt.Fprintln(os.Stderr, err.Error())
}
}()
err = cmd.Execute(ctx)
return
}
// noifyContext sets up graceful shutdown handling and returns a context and
// cleanup function. This is nearly identical to [signal.NotifyContext], except
// that it logs a message when a signal is received and also restores the default
// signal handling behavior.
func notifyContext(parent context.Context) (context.Context, context.CancelFunc) {
ctx, cancel := context.WithCancel(parent)
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)
go func() {
select {
case sig := <-sigChan:
logging.Info("Received interrupt signal, press control-C again to exit", zap.Stringer("signal", sig))
signal.Stop(sigChan) // Restore default signal handling behavior
cancel()
case <-ctx.Done():
}
}()
return ctx, func() {
cancel()
signal.Stop(sigChan)
}
}