-
Notifications
You must be signed in to change notification settings - Fork 2
/
viper.go
89 lines (78 loc) · 2.18 KB
/
viper.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
package store
import (
"context"
"os"
"path/filepath"
"github.com/hashicorp/go-version"
"github.com/spf13/viper"
"github.com/toitlang/tpkg/commands"
"github.com/toitlang/tpkg/config"
"github.com/toitlang/tpkg/pkg/tpkg"
)
type Viper struct {
cacheDir string
sdkVersion string
noAutosync bool
noDefaultRegistry bool
}
func NewViper(cacheDir string, sdkVersion string, noAutosync bool, noDefaultRegistry bool) *Viper {
return &Viper{
cacheDir: cacheDir,
sdkVersion: sdkVersion,
noAutosync: noAutosync,
noDefaultRegistry: noDefaultRegistry,
}
}
const packageInstallPathConfigEnv = "TOIT_PACKAGE_INSTALL_PATH"
const configKeyRegistries = "pkg.registries"
const configKeyAutosync = "pkg.autosync"
func (vc *Viper) Init(cfgFile string) error {
viper.SetConfigFile(cfgFile)
return viper.ReadInConfig()
}
func (vc *Viper) Load(ctx context.Context) (*commands.Config, error) {
result := commands.Config{}
if vc.cacheDir == "" {
var err error
result.PackageCachePaths, err = config.PackageCachePaths()
if err != nil {
return nil, err
}
result.RegistryCachePaths, err = config.RegistryCachePaths()
if err != nil {
return nil, err
}
} else {
result.PackageCachePaths = []string{filepath.Join(vc.cacheDir, "tpkg")}
result.RegistryCachePaths = []string{filepath.Join(vc.cacheDir, "tpkg-registries")}
}
if p, ok := os.LookupEnv(packageInstallPathConfigEnv); ok {
result.PackageInstallPath = &p
}
if vc.sdkVersion != "" {
v, err := version.NewVersion(vc.sdkVersion)
if err != nil {
return nil, err
}
result.SDKVersion = v
}
if viper.IsSet(configKeyRegistries) {
err := viper.UnmarshalKey(configKeyRegistries, &result.RegistryConfigs)
if err != nil {
return nil, err
}
if result.RegistryConfigs == nil {
// Viper seems to just ignore empty lists.
result.RegistryConfigs = tpkg.RegistryConfigs{}
}
} else if vc.noDefaultRegistry {
result.RegistryConfigs = tpkg.RegistryConfigs{}
}
return &result, nil
}
func (vc *Viper) Store(ctx context.Context, cfg *commands.Config) error {
if cfg.RegistryConfigs != nil {
viper.Set(configKeyRegistries, cfg.RegistryConfigs)
}
return viper.WriteConfig()
}