-
Notifications
You must be signed in to change notification settings - Fork 1
/
settings.go
84 lines (70 loc) · 2.29 KB
/
settings.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
package settings
import (
"os/user"
"path/filepath"
"github.com/govcms-tests/govcms-cli/pkg/utils"
"github.com/spf13/viper"
)
// Config is a struct of configurable options
type Config struct {
Workspace string `yaml:"workspace"` // The project workspace
OS string `yaml:"os"` // Operating system information
Tokens map[string]string `yaml:"tokens"` // Access tokens for various services
Database string `yaml:"database"` // The local database
}
// LoadConfig loads the configuration from the specified YAML file
func LoadConfig() (Config, error) {
var cfg Config
// Find the user's home directory
currentUser, err := user.Current()
if err != nil {
return cfg, err
}
homeDir := currentUser.HomeDir
viper.SetConfigType("yaml")
// Set the name of the configuration file (without extension)
viper.SetConfigName(".govcms-cli")
// Set the path to look for the configuration file
viper.AddConfigPath(homeDir)
// Read in the configuration file
if err := viper.ReadInConfig(); err != nil {
// If the config file is not found, create default config
if _, ok := err.(viper.ConfigFileNotFoundError); ok {
if err := createDefaultConfig(homeDir, &cfg); err != nil {
return cfg, err
}
} else {
// If there's an error other than file not found, return it
return cfg, err
}
}
// Unmarshal the config file into the Config struct
if err := viper.Unmarshal(&cfg); err != nil {
return cfg, err
}
return cfg, nil
}
// Creates and writes the default configuration to file
func createDefaultConfig(homeDir string, cfg *Config) error {
// Set default values
cfg.Tokens = map[string]string{
"Github": "---",
"Gitlab": "---",
"Docker": "---",
}
// Set default workspace directory
cfg.Workspace = filepath.Join(homeDir, "govcms")
// Set default SQLite database file location
cfg.Database = filepath.Join(homeDir, ".govcms.db")
// Set the default tokens and workspace in the viper instance
viper.Set("tokens", cfg.Tokens)
viper.Set("workspace", cfg.Workspace)
viper.Set("os", utils.GetOperatingSystem())
viper.Set("database", cfg.Database)
// Write the configuration to file
configFilePath := filepath.Join(homeDir, ".govcms-cli.yaml")
if err := viper.WriteConfigAs(configFilePath); err != nil {
return err
}
return nil
}