/
config.go
87 lines (74 loc) · 1.81 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
package main
import (
"errors"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"github.com/BurntSushi/toml"
"github.com/mitchellh/go-homedir"
)
const configFileEnvVar = "JOT_CONFIG_FILE"
type config struct {
Profile []profile
}
type profile struct {
Name string `toml:"name"`
Endpoint string `toml:"endpoint"`
TLSSkipVerify bool `toml:"tls_skip_verify"`
}
// loadConfig loads a profile from a config file. Returns an error if the config file
// could not be found, or the file does not contain the given profile.
func loadConfig(cfgName string, profileName string) (profile, error) {
if cfgName == "" {
cfgName = getConfigFile()
}
if cfgName == "" {
return profile{}, errors.New("please specify the path to the config file")
}
b, err := ioutil.ReadFile(cfgName)
if err != nil {
return profile{}, fmt.Errorf("unable to read config: %v", err)
}
var cfg config
if _, err := toml.Decode(string(b), &cfg); err != nil {
return profile{}, fmt.Errorf("unable to parse config file %s: %v", cfgName, err)
}
for _, p := range cfg.Profile {
if p.Name == profileName {
return p, nil
}
}
return profile{}, fmt.Errorf("profile %q not found in %s", profileName, cfgName)
}
// getConfigFile returns the location of the CLI config file.
func getConfigFile() string {
if name := os.Getenv(configFileEnvVar); name != "" {
return name
}
home, err := homedir.Dir()
if err != nil {
return ""
}
name := filepath.Join(home, ".jot", "config.toml")
if checkFile(name) {
return name
}
return ""
}
// checkFile returns true if path name exists and is not a directory.
func checkFile(name string) bool {
info, err := os.Stat(name)
if err != nil {
return false
}
return !info.IsDir()
}
func isOneOf(s string, vals []string) bool {
for _, v := range vals {
if v == s {
return true
}
}
return false
}