-
Notifications
You must be signed in to change notification settings - Fork 13
/
main.go
88 lines (74 loc) · 1.89 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
package main
import (
"errors"
"fmt"
"os"
"path/filepath"
"time"
"github.com/GGP1/kure/auth"
"github.com/GGP1/kure/commands/root"
"github.com/GGP1/kure/config"
"github.com/GGP1/kure/sig"
"github.com/spf13/pflag"
"github.com/awnumar/memguard"
bolt "go.etcd.io/bbolt"
)
func main() {
if err := validateFlags(); err != nil {
if errors.Is(err, pflag.ErrHelp) {
os.Exit(0)
}
fmt.Fprintln(os.Stderr, "error:", err)
os.Exit(1)
}
if err := config.Init(); err != nil {
fmt.Fprintln(os.Stderr, "couldn't initialize the configuration:", err)
os.Exit(1)
}
// Check for and run stateless commands
if len(os.Args) < 2 || root.IsStatelessCommand(os.Args[1]) {
if err := root.NewCmd(nil).Execute(); err != nil {
fmt.Fprintln(os.Stderr, "error:", err)
os.Exit(1)
}
os.Exit(0)
}
dbPath := filepath.Clean(config.GetString("database.path"))
db, err := bolt.Open(dbPath, 0o600, &bolt.Options{Timeout: 200 * time.Millisecond})
if err != nil {
fmt.Fprintln(os.Stderr, "couldn't open the database:", err)
os.Exit(1)
}
if err := auth.Login(db); err != nil {
fmt.Fprintln(os.Stderr, "error:", err)
db.Close()
memguard.SafeExit(1)
}
// Listen for a signal to release resources and delete sensitive information
sig.Signal.Listen(db)
if err := root.NewCmd(db).Execute(); err != nil {
fmt.Fprintln(os.Stderr, "error:", err)
db.Close()
memguard.SafeExit(1)
}
db.Close()
memguard.SafeExit(0)
}
// validateFlags looks for the command called and parses its flags. If the flag is `--help`,
// it will print the command's help message and return the error pflag.ErrHelp.
func validateFlags() error {
cmd, args, err := root.NewCmd(nil).Find(os.Args[1:])
if err != nil {
return err
}
if err := cmd.ParseFlags(args); err != nil {
if errors.Is(err, pflag.ErrHelp) {
if err := cmd.Help(); err != nil {
return err
}
return pflag.ErrHelp
}
return err
}
return nil
}