-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.go
73 lines (62 loc) · 1.74 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
package config
import (
"fmt"
"os"
"path/filepath"
"github.com/spf13/viper"
)
// Initialize initializes the viper instance. It will only run once.
func Initialize() error {
homedir, err := os.UserHomeDir()
if err != nil {
return fmt.Errorf("failed to get user home directory: %w", err)
}
filePath := filepath.Join(homedir, ".acli")
viper.SetDefault("kch.defaults.resource", "pod")
viper.SetDefault("kch.defaults.namespace", "default")
viper.SetConfigName(".acli")
viper.SetConfigType("yaml")
viper.AddConfigPath(homedir)
err = viper.ReadInConfig()
if err == nil {
return nil
}
_, ok := err.(viper.ConfigFileNotFoundError)
if !ok {
// Config file was found but another error was produced
return fmt.Errorf("failed to get acli config file: %w", err)
}
return writeConfigFile(filePath)
}
// writeConfigFile creates a new acli config file in the user's home directory.
func writeConfigFile(filePath string) error {
file, err := os.OpenFile(filePath, os.O_CREATE|os.O_RDWR, 0644)
if err != nil {
return fmt.Errorf("failed to create acli config file: %w", err)
}
file.Close()
return nil
}
// Get reads a config string from the acli config file.
func GetString(key string) string {
return viper.GetString(key)
}
// GetStringSlice reads a config string slice from the acli config file.
func GetStringSlice(key string) []string {
return viper.GetStringSlice(key)
}
func GetBool(key string) bool {
return viper.GetBool(key)
}
func UnmarshalConfig(key any) error {
return viper.Unmarshal(key)
}
// Set writes a config value to the acli config file.
func Set(key string, value any) error {
viper.Set(key, value)
err := viper.WriteConfig()
if err != nil {
return fmt.Errorf("fatal error writing viper config file: %w", err)
}
return nil
}