diff --git a/config/configuration.go b/config/configuration.go index 5ab6071e2..39ed3593f 100644 --- a/config/configuration.go +++ b/config/configuration.go @@ -17,7 +17,6 @@ import ( "encoding/json" "fmt" "os" - "runtime" "github.com/aliyun/aliyun-cli/cli" "github.com/aliyun/aliyun-cli/util" @@ -206,14 +205,3 @@ func GetConfigPath() string { } return path } - -func GetHomePath() string { - if runtime.GOOS == "windows" { - home := os.Getenv("HOMEDRIVE") + os.Getenv("HOMEPATH") - if home == "" { - home = os.Getenv("USERPROFILE") - } - return home - } - return os.Getenv("HOME") -} diff --git a/config/configuration_test.go b/config/configuration_test.go index 97646fab6..f57cddbb7 100644 --- a/config/configuration_test.go +++ b/config/configuration_test.go @@ -18,7 +18,6 @@ import ( "encoding/json" "errors" "os" - "runtime" "testing" "github.com/aliyun/aliyun-cli/cli" @@ -146,14 +145,6 @@ func TestLoadProfile(t *testing.T) { assert.EqualError(t, err, "init config failed error") } -func TestHomePath(t *testing.T) { - if runtime.GOOS == "windows" { - assert.Equal(t, os.Getenv("USERPROFILE"), GetHomePath()) - } else { - assert.Equal(t, os.Getenv("HOME"), GetHomePath()) - } -} - func TestGetConfigPath(t *testing.T) { orighookGetHomePath := hookGetHomePath defer func() { diff --git a/config/path.go b/config/path.go new file mode 100644 index 000000000..ce47b939a --- /dev/null +++ b/config/path.go @@ -0,0 +1,39 @@ +package config + +import ( + "os" + "runtime" +) + +func GetXDGConfigHome() string { + if xgh := os.Getenv("XDG_CONFIG_HOME"); xgh != "" { + return xgh + } else { + return GetHomePath() + "/.config" + } +} + +func GetConfigDirPath() string { + // ~/.aliyun/ 存在则是老的配置路径 + // 否则:使用 XDG 规范 + home := GetHomePath() + path := home + "/.aliyun" + _, err := os.Stat(path) + // 目录存在 + if err != nil { + return path + } + + return GetXDGConfigHome() + "/aliyun" +} + +func GetHomePath() string { + if runtime.GOOS == "windows" { + home := os.Getenv("HOMEDRIVE") + os.Getenv("HOMEPATH") + if home == "" { + home = os.Getenv("USERPROFILE") + } + return home + } + return os.Getenv("HOME") +} diff --git a/config/path_test.go b/config/path_test.go new file mode 100644 index 000000000..5960a5240 --- /dev/null +++ b/config/path_test.go @@ -0,0 +1,29 @@ +package config + +import ( + "os" + "runtime" + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestHomePath(t *testing.T) { + if runtime.GOOS == "windows" { + assert.Equal(t, os.Getenv("USERPROFILE"), GetHomePath()) + } else { + assert.Equal(t, os.Getenv("HOME"), GetHomePath()) + } +} + +func TestGetXDGConfigHome(t *testing.T) { + if runtime.GOOS == "windows" { + return + } + + assert.Equal(t, os.Getenv("HOME")+"/.config", GetXDGConfigHome()) + os.Setenv("XDG_CONFIG_HOME", "/tmp/config") + assert.Equal(t, "/tmp/config", GetXDGConfigHome()) + os.Setenv("XDG_CONFIG_HOME", "") + assert.Equal(t, os.Getenv("HOME")+"/.config", GetXDGConfigHome()) +}