-
Notifications
You must be signed in to change notification settings - Fork 0
/
root.go
85 lines (71 loc) · 1.8 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
81
82
83
84
85
package ssh
import (
"fmt"
"log"
"os"
"path/filepath"
"github.com/fsnotify/fsnotify"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
// Ssh is largely clerical, will link sub commands here
var (
debug = false
Ssh = &cobra.Command{
Use: "ssh",
Short: "A profiling system for the SSH config file",
Long: "A profiling system for the SSH config file",
Run: func(cmd *cobra.Command, args []string) {
// If nothing is specified print help
// This is because I want a uniform CLI,
// So the user must use a command
if len(args) == 0 {
cmd.Help()
os.Exit(0)
}
},
}
)
// Execute is called on by the main process
func Execute() {
cobra.OnInitialize(initConfig)
// Debug - Add global flag
Ssh.PersistentFlags().BoolVarP(&debug, "debug", "d", false, "Show debugging information")
// Print errors
if err := Ssh.Execute(); err != nil {
log.Fatalln(err)
}
}
func initConfig() {
// Write or load config file: ~/.historian.yaml
if c, err := os.UserConfigDir(); err != nil {
log.Fatalln(err)
} else {
dir := filepath.Join(c, "ccp")
if _, err := os.Stat(dir); os.IsNotExist(err) {
os.Mkdir(dir, os.ModePerm)
}
viper.AddConfigPath(dir)
viper.SetConfigName("profiles")
viper.SetConfigType("yaml")
viper.AutomaticEnv()
// Debug - Print configuration file
if err := viper.ReadInConfig(); err == nil && debug {
fmt.Println("Using config file:", viper.ConfigFileUsed())
}
}
// Write or read config
if err := viper.SafeWriteConfig(); err != nil {
if err := viper.ReadInConfig(); err != nil {
log.Fatalf("cant read config: %s\n", err)
}
}
// Update during execution
viper.WatchConfig()
// Debug - notify on configuration change
if debug {
viper.OnConfigChange(func(e fsnotify.Event) {
fmt.Println("Config file changed:", e.Name, e.Op)
})
}
}