Merge pull request #2740 from Matt-Gleich/homedir

Refactor to use os.UserHomeDir()
This commit is contained in:
Mislav Marohnić 2021-01-22 20:29:39 +01:00 committed by GitHub
commit 7fecaaa8e2
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 63 additions and 6 deletions

View file

@ -9,7 +9,7 @@ import (
"regexp"
"strings"
"github.com/mitchellh/go-homedir"
"github.com/cli/cli/internal/config"
)
var (
@ -147,10 +147,10 @@ func ParseSSHConfig() SSHAliasMap {
p := sshParser{}
if homedir, err := homedir.Dir(); err == nil {
userConfig := filepath.Join(homedir, ".ssh", "config")
if sshDir, err := config.HomeDirPath(".ssh"); err == nil {
userConfig := filepath.Join(sshDir, "config")
configFiles = append([]string{userConfig}, configFiles...)
p.homeDir = homedir
p.homeDir = filepath.Dir(sshDir)
}
for _, file := range configFiles {

View file

@ -7,6 +7,7 @@ import (
"io/ioutil"
"os"
"path"
"path/filepath"
"syscall"
"github.com/mitchellh/go-homedir"
@ -14,8 +15,8 @@ import (
)
func ConfigDir() string {
dir, _ := homedir.Expand("~/.config/gh")
return dir
homeDir, _ := homeDirAutoMigrate()
return homeDir
}
func ConfigFile() string {
@ -30,6 +31,62 @@ func ParseDefaultConfig() (Config, error) {
return ParseConfig(ConfigFile())
}
func HomeDirPath(subdir string) (string, error) {
homeDir, err := os.UserHomeDir()
if err != nil {
// TODO: remove go-homedir fallback in GitHub CLI v2
if legacyDir, err := homedir.Dir(); err == nil {
return filepath.Join(legacyDir, subdir), nil
}
return "", err
}
newPath := filepath.Join(homeDir, subdir)
if s, err := os.Stat(newPath); err == nil && s.IsDir() {
return newPath, nil
}
// TODO: remove go-homedir fallback in GitHub CLI v2
if legacyDir, err := homedir.Dir(); err == nil {
legacyPath := filepath.Join(legacyDir, subdir)
if s, err := os.Stat(legacyPath); err == nil && s.IsDir() {
return legacyPath, nil
}
}
return newPath, nil
}
// Looks up the `~/.config/gh` directory with backwards-compatibility with go-homedir and auto-migration
// when an old homedir location was found.
func homeDirAutoMigrate() (string, error) {
homeDir, err := os.UserHomeDir()
if err != nil {
// TODO: remove go-homedir fallback in GitHub CLI v2
if legacyDir, err := homedir.Dir(); err == nil {
return filepath.Join(legacyDir, ".config", "gh"), nil
}
return "", err
}
newPath := filepath.Join(homeDir, ".config", "gh")
_, newPathErr := os.Stat(newPath)
if newPathErr == nil || !os.IsNotExist(err) {
return newPath, newPathErr
}
// TODO: remove go-homedir fallback in GitHub CLI v2
if legacyDir, err := homedir.Dir(); err == nil {
legacyPath := filepath.Join(legacyDir, ".config", "gh")
if s, err := os.Stat(legacyPath); err == nil && s.IsDir() {
_ = os.MkdirAll(filepath.Dir(newPath), 0755)
return newPath, os.Rename(legacyPath, newPath)
}
}
return newPath, nil
}
var ReadConfigFile = func(filename string) ([]byte, error) {
f, err := os.Open(filename)
if err != nil {