Query HOME consistently.

A bug with osutil.Getcwd was also fixed. This fixes #91.
This commit is contained in:
Qi Xiao 2016-02-11 23:43:48 +01:00
parent 7f5f96ca0f
commit 34c0d96830
4 changed files with 27 additions and 11 deletions

View File

@ -2,7 +2,9 @@ package osutil
import (
"fmt"
"os"
"os/user"
"strings"
)
func GetHome(uname string) (string, error) {
@ -14,7 +16,14 @@ func GetHome(uname string) (string, error) {
u, err = user.Lookup(uname)
}
if err != nil {
if uname == "" {
// Use $HOME as fallback
home := os.Getenv("HOME")
if home != "" {
return strings.TrimRight(home, "/"), nil
}
}
return "", fmt.Errorf("can't resolve ~%s: %s", uname, err.Error())
}
return u.HomeDir, nil
return strings.TrimRight(u.HomeDir, "/"), nil
}

View File

@ -12,10 +12,13 @@ func Getwd() string {
if err != nil {
return "?"
}
home := os.Getenv("HOME")
home = strings.TrimRight(home, "/")
if len(pwd) >= len(home) && pwd[:len(home)] == home {
return "~" + pwd[len(home):]
home, err := GetHome("")
if err == nil {
if pwd == home {
return "~"
} else if strings.HasPrefix(pwd, home+"/") {
return "~" + pwd[len(home):]
}
}
return pwd
}

View File

@ -20,7 +20,11 @@ func TestGetwd(t *testing.T) {
os.Remove(dir)
}
os.Chdir(os.Getenv("HOME"))
home, err := GetHome("")
if err != nil {
panic(err)
}
os.Chdir(home)
if gotwd := Getwd(); gotwd != "~" {
t.Errorf("Getwd() -> %v, want ~", gotwd)
}

View File

@ -3,7 +3,8 @@ package store
import (
"errors"
"os"
"strings"
"github.com/elves/elvish/osutil"
)
// ErrEmptyHOME is the error returned by EnsureDataDir when the environmental
@ -14,11 +15,10 @@ var ErrEmptyHOME = errors.New("environment variable HOME is empty")
// necessary. It returns the path to the data directory (never with a
// trailing slash) and possible error.
func EnsureDataDir() (string, error) {
home := os.Getenv("HOME")
if home == "" {
return "", ErrEmptyHOME
home, err := osutil.GetHome("")
if err != nil {
return "", err
}
home = strings.TrimRight(home, "/")
ddir := home + "/.elvish"
return ddir, os.MkdirAll(ddir, 0700)
}