diff --git a/internal/config/paths.go b/internal/config/paths.go index 9a6fc2e..52a2d86 100644 --- a/internal/config/paths.go +++ b/internal/config/paths.go @@ -11,7 +11,7 @@ import ( // system func Paths(sys string, envvars map[string]string) ([]string, error) { - // if CHEAT_CONFIG_PATH is set, expand ~ and return it + // if `CHEAT_CONFIG_PATH` is set, expand ~ and return it if confpath, ok := envvars["CHEAT_CONFIG_PATH"]; ok { // expand ~ @@ -25,11 +25,20 @@ func Paths(sys string, envvars map[string]string) ([]string, error) { switch sys { case "darwin", "linux", "freebsd": - return []string{ - path.Join(envvars["XDG_CONFIG_HOME"], "/cheat/conf.yml"), + paths := []string{} + + // don't include the `XDG_CONFIG_HOME` path if that envvar is not set + if xdgpath, ok := envvars["XDG_CONFIG_HOME"]; ok { + paths = append(paths, path.Join(xdgpath, "/cheat/conf.yml")) + } + + // `HOME` will always be set on a POSIX-compliant system, though + paths = append(paths, []string{ path.Join(envvars["HOME"], ".config/cheat/conf.yml"), path.Join(envvars["HOME"], ".cheat/conf.yml"), - }, nil + }...) + + return paths, nil case "windows": return []string{ path.Join(envvars["APPDATA"], "/cheat/conf.yml"), diff --git a/internal/config/paths_test.go b/internal/config/paths_test.go index fd955b0..0838c3e 100644 --- a/internal/config/paths_test.go +++ b/internal/config/paths_test.go @@ -50,6 +50,47 @@ func TestValidatePathsNix(t *testing.T) { } } +// TestValidatePathsNixNoXDG asserts that the proper config paths are returned +// on *nix platforms when `XDG_CONFIG_HOME is not set +func TestValidatePathsNixNoXDG(t *testing.T) { + + // mock some envvars + envvars := map[string]string{ + "HOME": "/home/foo", + } + + // specify the platforms to test + oses := []string{ + "darwin", + "freebsd", + "linux", + } + + // test each *nix os + for _, os := range oses { + // get the paths for the platform + paths, err := Paths(os, envvars) + if err != nil { + t.Errorf("paths returned an error: %v", err) + } + + // specify the expected output + want := []string{ + "/home/foo/.config/cheat/conf.yml", + "/home/foo/.cheat/conf.yml", + } + + // assert that output matches expectations + if !reflect.DeepEqual(paths, want) { + t.Errorf( + "failed to return expected paths: want:\n%s, got:\n%s", + spew.Sdump(want), + spew.Sdump(paths), + ) + } + } +} + // TestValidatePathsWindows asserts that the proper config paths are returned // on Windows platforms func TestValidatePathsWindows(t *testing.T) {