-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.go
103 lines (89 loc) · 2.52 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
// Copyright Datajin Technologies, Inc. 2015,2016. All rights reserved.
// Use of this source code is governed by an Artistic-2
// license that can be found in the LICENSE file.
package mktmpio
import (
"io/ioutil"
"os"
"github.com/mitchellh/go-homedir"
"gopkg.in/yaml.v2"
)
// MktmpioURL is the root of the current version of the mktmpio HTTP API
const MktmpioURL = "https://mktmp.io/api/v1"
// MKtmpioCfgFile is the path to the user's config
const MKtmpioCfgFile = "~/.mktmpio.yml"
// Config contains the user config options used for accessing the mktmpio API.
type Config struct {
Token string
URL string `yaml:",omitempty"`
err error
}
func (c Config) String() string {
bytes, _ := yaml.Marshal(c)
return string(bytes)
}
// LoadConfig loads the configuration stored in `~/.mktmpio.yml`, returning it
// as a Config type instance.
func LoadConfig() *Config {
config := Config{}
defConf := DefaultConfig()
file := FileConfig(ConfigPath())
env := EnvConfig()
return config.Apply(defConf).Apply(file).Apply(env)
}
// DefaultConfig returns a configuration with only the default values set
func DefaultConfig() *Config {
config := new(Config)
config.URL = MktmpioURL
return config
}
// EnvConfig returns a configuration with only values provided by environment variables
func EnvConfig() *Config {
config := new(Config)
config.Token = os.Getenv("MKTMPIO_TOKEN")
config.URL = os.Getenv("MKTMPIO_URL")
return config
}
// FileConfig returns a configuration with any values provided by the given YAML config file
func FileConfig(cfgPath string) *Config {
config := new(Config)
cfgFile, err := ioutil.ReadFile(cfgPath)
if err != nil {
config.err = err
} else {
config.err = yaml.Unmarshal(cfgFile, config)
}
return config
}
// Apply creates a new Config with non-empty values from the provided Config
// overriding the options of the base Config
func (c *Config) Apply(b *Config) *Config {
newCfg := new(Config)
if b.Token == "" {
newCfg.Token = c.Token
} else {
newCfg.Token = b.Token
}
if b.URL == "" {
newCfg.URL = c.URL
} else {
newCfg.URL = b.URL
}
return newCfg
}
// ConfigPath returns the path to the user config file
func ConfigPath() string {
if path, err := homedir.Expand(MKtmpioCfgFile); err == nil {
return path
}
return ""
}
// Save stores the given configuration in ~/.mktmpio.yml, overwriting the
// current contents if the file exists.
func (c *Config) Save(cfgPath string) error {
cfgFile, err := yaml.Marshal(c)
if err == nil {
err = ioutil.WriteFile(cfgPath, cfgFile, 0600)
}
return err
}