forked from MattSurabian/pact
/
config.go
109 lines (90 loc) · 2.3 KB
/
config.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package main
import (
"encoding/json"
"fmt"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"os"
"os/user"
"path/filepath"
)
var ConfigFileType string
var ConfigFileName string
var ConfigDirectory string
type config struct {
PublicKeyPath string
PrivateKeyPath string
Pacts map[string][]string
}
var Configuration config
var ConfigCmd = &cobra.Command{
Use: "config",
Short: "Generates a new configuration file",
Long: `Generates a new configuration file and will refuse to overwrite an existing one.`,
Run: func(cmd *cobra.Command, args []string) {
if configFileExists() {
fmt.Println("Configuration file already exists, refusing to overwrite.")
os.Exit(400)
}
SetDefaultPact()
HydrateConfigurationModel()
PersistConfiguration()
},
}
func init() {
currentUser, err := user.Current()
if err != nil {
panic(err)
}
userHomeDir := currentUser.HomeDir
fileSeperator := string(filepath.Separator)
ConfigDirectory = userHomeDir + fileSeperator + ".config" + fileSeperator + "pact" + fileSeperator
ConfigFileName = "pact"
ConfigFileType = "json"
viper.SetConfigType(ConfigFileType)
viper.SetConfigName(ConfigFileName)
viper.AddConfigPath(ConfigDirectory)
err = viper.ReadInConfig()
if err != nil {
fmt.Println("No config file found. The config command will generate one.")
} else {
HydrateConfigurationModel()
}
}
func HydrateConfigurationModel() {
viper.Marshal(&Configuration)
}
/**
* PersistConfigurtaion
* Method which writes the current configuration model to disk.
*/
func PersistConfiguration() {
//viper.Marshal(&Configuration)
configurationString, err := json.MarshalIndent(Configuration, "", " ")
if err != nil {
panic(err)
}
f, err := os.Create(GetConfigFilePath())
if err != nil {
panic(err)
}
defer f.Close()
f.WriteString(string(configurationString))
}
/**
* configFileExists
* @returns bool
* Heloer method to determine if a configuration file exists.
*/
func configFileExists() bool {
_, configExistsError := os.Stat(GetConfigFilePath())
return !os.IsNotExist(configExistsError)
}
/**
* GetConfigFilePath
* @returns string Absolute path to the configuration file
* Helper method which returns the path to the configuration file.
*/
func GetConfigFilePath() string {
return ConfigDirectory + ConfigFileName + "." + ConfigFileType
}