mirror of
https://github.com/cheat/cheat.git
synced 2024-11-21 21:41:35 +01:00
chore: refactors config.Paths
Refactors the reading of multiple envvars out of `config.Paths` in order to facilitate cleaner unit-testing.
This commit is contained in:
parent
d4c6200702
commit
6912771c39
@ -6,6 +6,7 @@ import (
|
||||
"fmt"
|
||||
"os"
|
||||
"runtime"
|
||||
"strings"
|
||||
|
||||
"github.com/docopt/docopt-go"
|
||||
|
||||
@ -31,8 +32,15 @@ func main() {
|
||||
os.Exit(0)
|
||||
}
|
||||
|
||||
// read the envvars into a map of strings
|
||||
envvars := map[string]string{}
|
||||
for _, e := range os.Environ() {
|
||||
pair := strings.SplitN(e, "=", 2)
|
||||
envvars[pair[0]] = pair[1]
|
||||
}
|
||||
|
||||
// load the os-specifc paths at which the config file may be located
|
||||
confpaths, err := config.Paths(runtime.GOOS)
|
||||
confpaths, err := config.Paths(runtime.GOOS, envvars)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "failed to load config: %v\n", err)
|
||||
os.Exit(1)
|
||||
|
@ -2,7 +2,6 @@ package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path"
|
||||
|
||||
"github.com/mitchellh/go-homedir"
|
||||
@ -10,13 +9,13 @@ import (
|
||||
|
||||
// Paths returns config file paths that are appropriate for the operating
|
||||
// system
|
||||
func Paths(sys string) ([]string, error) {
|
||||
func Paths(sys string, envvars map[string]string) ([]string, error) {
|
||||
|
||||
// if CHEAT_CONFIG_PATH is set, return it
|
||||
if os.Getenv("CHEAT_CONFIG_PATH") != "" {
|
||||
// if CHEAT_CONFIG_PATH is set, expand ~ and return it
|
||||
if confpath, ok := envvars["CHEAT_CONFIG_PATH"]; ok {
|
||||
|
||||
// expand ~
|
||||
expanded, err := homedir.Expand(os.Getenv("CHEAT_CONFIG_PATH"))
|
||||
expanded, err := homedir.Expand(confpath)
|
||||
if err != nil {
|
||||
return []string{}, fmt.Errorf("failed to expand ~: %v", err)
|
||||
}
|
||||
@ -27,14 +26,14 @@ func Paths(sys string) ([]string, error) {
|
||||
switch sys {
|
||||
case "darwin", "linux", "freebsd":
|
||||
return []string{
|
||||
path.Join(os.Getenv("XDG_CONFIG_HOME"), "/cheat/conf.yml"),
|
||||
path.Join(os.Getenv("HOME"), ".config/cheat/conf.yml"),
|
||||
path.Join(os.Getenv("HOME"), ".cheat/conf.yml"),
|
||||
path.Join(envvars["XDG_CONFIG_HOME"], "/cheat/conf.yml"),
|
||||
path.Join(envvars["HOME"], ".config/cheat/conf.yml"),
|
||||
path.Join(envvars["HOME"], ".cheat/conf.yml"),
|
||||
}, nil
|
||||
case "windows":
|
||||
return []string{
|
||||
fmt.Sprintf("%s/cheat/conf.yml", os.Getenv("APPDATA")),
|
||||
fmt.Sprintf("%s/cheat/conf.yml", os.Getenv("PROGRAMDATA")),
|
||||
fmt.Sprintf("%s/cheat/conf.yml", envvars["APPDATA"]),
|
||||
fmt.Sprintf("%s/cheat/conf.yml", envvars["PROGRAMDATA"]),
|
||||
}, nil
|
||||
default:
|
||||
return []string{}, fmt.Errorf("unsupported os: %s", sys)
|
||||
|
Loading…
Reference in New Issue
Block a user