/
root.go
53 lines (39 loc) · 1.01 KB
/
root.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
package cmd
import (
"encoding/base64"
"fmt"
"github.com/rs/zerolog"
"github.com/spf13/cobra"
"github.com/go-pg/pg/v10"
)
var (
debug bool = false
apiKey string
pgDSN string
pgDB *pg.DB
)
func NewRootCommand() *cobra.Command {
root := cobra.Command{
Use: "wakaexporter",
}
root.PersistentFlags().BoolVar(&debug, "debug", debug, "enable debug log")
root.PersistentFlags().StringVar(&apiKey, "api-key", apiKey, "wakatime's secret api key")
root.PersistentFlags().StringVar(&pgDSN, "pg", pgDSN, "dsn of postgresql, if you want to save heartbeats to postgresql")
root.PersistentPreRunE = func(*cobra.Command, []string) error {
if debug {
zerolog.SetGlobalLevel(zerolog.DebugLevel)
} else {
zerolog.SetGlobalLevel(zerolog.InfoLevel)
}
if len(apiKey) > 0 {
apiKey = base64.StdEncoding.EncodeToString([]byte(apiKey))
}
opts, err := pg.ParseURL(pgDSN)
if err != nil {
return fmt.Errorf("invalid pg dsn %s: %w", pgDSN, err)
}
pgDB = pg.Connect(opts)
return nil
}
return &root
}