/
root.go
80 lines (68 loc) · 2.3 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
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
package cmd
import (
"fmt"
"os"
"path/filepath"
"sync"
"github.com/cloud66-oss/trackman/utils"
"github.com/mitchellh/go-homedir"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
var rootCmd = &cobra.Command{
Use: "trackman",
Short: "Trackman is a tool to run commands in a sequence",
PersistentPreRun: checkForUpdates,
}
var (
cfgFile string
// UpdateDone makes sure background updater is done before the app is closed
UpdateDone *sync.WaitGroup
)
func init() {
UpdateDone = &sync.WaitGroup{}
cobra.OnInitialize(initConfig)
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.trackman.yaml)")
rootCmd.PersistentFlags().String("log-level", "info", "log level. Use debug to see process output")
rootCmd.PersistentFlags().String("log-type", "stdout", "log type. Valid values are stdout, stderr, discard and file")
rootCmd.PersistentFlags().String("log-format", "text", "log format. Valid values are text and json")
rootCmd.PersistentFlags().String("log-file", "trackman.log", "file path for logs. Only used when log-type is file")
rootCmd.PersistentFlags().Bool("no-update", false, "turn off auto update")
_ = viper.BindPFlag("log-level", rootCmd.PersistentFlags().Lookup("log-level"))
_ = viper.BindPFlag("log-file", rootCmd.PersistentFlags().Lookup("log-file"))
_ = viper.BindPFlag("log-type", rootCmd.PersistentFlags().Lookup("log-type"))
_ = viper.BindPFlag("log-format", rootCmd.PersistentFlags().Lookup("log-format"))
_ = viper.BindPFlag("no-update", rootCmd.PersistentFlags().Lookup("no-update"))
}
func initConfig() {
if cfgFile != "" {
viper.SetConfigFile(cfgFile)
} else {
home, err := homedir.Dir()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
viper.AddConfigPath(".")
viper.AddConfigPath(filepath.Join(home, ".trackman"))
viper.AddConfigPath("/etc/trackman")
viper.SetConfigName("config")
}
_ = viper.ReadInConfig()
}
func checkForUpdates(cmd *cobra.Command, args []string) {
if utils.Channel != "dev" && cmd.Name() != "update" && cmd.Name() != "version" && !viper.GetBool("no-update") {
go func() {
UpdateDone.Add(1)
defer UpdateDone.Done()
update(true)
}()
}
}
// Execute main cobra entry point
func Execute() {
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}