-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
89 lines (77 loc) · 1.72 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package main
import (
"context"
"fmt"
"os"
"os/signal"
"syscall"
"github.com/spf13/cobra"
// a universal mechanism to manage goroutine lifecycles
"github.com/oklog/run"
"github.com/pkg/errors"
"github.com/fatih/color"
)
type Solution interface {
Solve(context.Context)
}
func newRootCommand() *cobra.Command {
return &cobra.Command{
Use: "goeuler [sub]",
Short: "Run Project Euler solutions",
Run: func(cmd *cobra.Command, args []string) {
if len(args) == 0 {
cmd.Help()
os.Exit(0)
}
},
}
}
func main() {
ctx, cancel := context.WithCancel(context.Background())
rootCmd := newRootCommand()
genPrimesCmd := NewGenPrimesCmd(ctx)
solveCmd := NewSolveCmd(ctx)
rootCmd.AddCommand(genPrimesCmd)
rootCmd.AddCommand(solveCmd)
runGroup := run.Group{}
{
cancelInterrupt := make(chan struct{})
runGroup.Add(
createSignalWatcher(ctx, cancelInterrupt, cancel),
func(error) {
close(cancelInterrupt)
})
}
{
runGroup.Add(func() error {
return rootCmd.Execute()
}, func(error) {
cancel()
})
}
err := runGroup.Run()
if err != nil {
fmt.Fprintf(os.Stderr, "exit reason: %s\n", err)
os.Exit(1)
}
color.New(color.FgGreen).Fprintln(os.Stderr, "Done!")
}
// This function just sits and waits for ctrl-C
func createSignalWatcher(ctx context.Context, cancelInterruptChan <-chan struct{}, cancel context.CancelFunc) func() error {
return func() error {
c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGINT, syscall.SIGTERM)
select {
case sig := <-c:
err := errors.Errorf("received signal %s", sig)
fmt.Fprintf(os.Stderr, "%s\n", err)
signal.Stop(c)
cancel()
return err
case <-ctx.Done():
return nil
case <-cancelInterruptChan:
return nil
}
}
}