From e6ad8a10d0bd576d105f99fab318dbd382d7a03a Mon Sep 17 00:00:00 2001 From: Sam Coe Date: Wed, 2 Jun 2021 09:46:14 -0400 Subject: [PATCH] Add support for XDG_DATA_HOME --- internal/config/config_file.go | 19 +++++++++ internal/config/config_file_test.go | 65 +++++++++++++++++++++++++++++ 2 files changed, 84 insertions(+) diff --git a/internal/config/config_file.go b/internal/config/config_file.go index e90d40ab0..304ea3327 100644 --- a/internal/config/config_file.go +++ b/internal/config/config_file.go @@ -17,6 +17,7 @@ const ( GH_CONFIG_DIR = "GH_CONFIG_DIR" XDG_CONFIG_HOME = "XDG_CONFIG_HOME" XDG_STATE_HOME = "XDG_STATE_HOME" + XDG_DATA_HOME = "XDG_DATA_HOME" APP_DATA = "AppData" LOCAL_APP_DATA = "LocalAppData" ) @@ -70,6 +71,24 @@ func StateDir() string { return path } +// Data path precedence +// 1. XDG_DATA_HOME +// 2. LocalAppData (windows only) +// 3. HOME +func DataDir() string { + var path string + if a := os.Getenv(XDG_DATA_HOME); a != "" { + path = filepath.Join(a, "gh") + } else if b := os.Getenv(LOCAL_APP_DATA); runtime.GOOS == "windows" && b != "" { + path = filepath.Join(b, "GitHub CLI") + } else { + c, _ := os.UserHomeDir() + path = filepath.Join(c, ".local", "share", "gh") + } + + return path +} + var errSamePath = errors.New("same path") var errNotExist = errors.New("not exist") diff --git a/internal/config/config_file_test.go b/internal/config/config_file_test.go index e6150aae3..4c35f24f9 100644 --- a/internal/config/config_file_test.go +++ b/internal/config/config_file_test.go @@ -484,3 +484,68 @@ func Test_autoMigrateStateDir_migration(t *testing.T) { assert.Equal(t, 1, len(files)) assert.Equal(t, "state.yml", files[0].Name()) } + +func Test_DataDir(t *testing.T) { + tempDir := t.TempDir() + + tests := []struct { + name string + onlyWindows bool + env map[string]string + output string + }{ + { + name: "HOME/USERPROFILE specified", + env: map[string]string{ + "XDG_DATA_HOME": "", + "GH_CONFIG_DIR": "", + "XDG_CONFIG_HOME": "", + "LocalAppData": "", + "USERPROFILE": tempDir, + "HOME": tempDir, + }, + output: filepath.Join(tempDir, ".local", "share", "gh"), + }, + { + name: "XDG_DATA_HOME specified", + env: map[string]string{ + "XDG_DATA_HOME": tempDir, + }, + output: filepath.Join(tempDir, "gh"), + }, + { + name: "LocalAppData specified", + onlyWindows: true, + env: map[string]string{ + "LocalAppData": tempDir, + }, + output: filepath.Join(tempDir, "GitHub CLI"), + }, + { + name: "XDG_DATA_HOME and LocalAppData specified", + onlyWindows: true, + env: map[string]string{ + "XDG_DATA_HOME": tempDir, + "LocalAppData": tempDir, + }, + output: filepath.Join(tempDir, "gh"), + }, + } + + for _, tt := range tests { + if tt.onlyWindows && runtime.GOOS != "windows" { + continue + } + t.Run(tt.name, func(t *testing.T) { + if tt.env != nil { + for k, v := range tt.env { + old := os.Getenv(k) + os.Setenv(k, v) + defer os.Setenv(k, old) + } + } + + assert.Equal(t, tt.output, DataDir()) + }) + } +}