Skip to content

Commit

Permalink
expand: support ~ on Windows without $HOME
Browse files Browse the repository at this point in the history
And add a test, which failed under Wine:

	--- FAIL: TestFields (0.00s)
	    --- FAIL: TestFields/10 (0.00s)
		expand_test.go:122:
		    want: ["/my/home"]
		    got:  [""]

While at it, rewrite interp.New's HOME fallback to use os.UserHomeDir,
since that doesn't rely on cgo.

Fixes #410.
  • Loading branch information
mvdan committed Sep 8, 2019
1 parent 473bdda commit 4a0ebd2
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 4 deletions.
21 changes: 20 additions & 1 deletion expand/expand.go
Expand Up @@ -11,6 +11,7 @@ import (
"os/user"
"path/filepath"
"regexp"
"runtime"
"strconv"
"strings"

Expand Down Expand Up @@ -619,8 +620,26 @@ func (cfg *Config) expandUser(field string) (prefix, rest string) {
name = name[:i]
}
if name == "" {
return cfg.Env.Get("HOME").String(), rest
// Current user; try via "HOME", otherwise fall back to the
// system's appropriate home dir env var. Don't use os/user, as
// that's overkill. We can't use os.UserHomeDir, because we want
// to use cfg.Env, and we always want to check "HOME" first.

if vr := cfg.Env.Get("HOME"); vr.IsSet() {
return vr.String(), rest
}

if runtime.GOOS == "windows" {
if vr := cfg.Env.Get("USERPROFILE"); vr.IsSet() {
return vr.String(), rest
}
}
return "", field
}

// Not the current user; try via "HOME <name>", otherwise fall back to
// os/user. There isn't a way to lookup user home dirs without cgo.

if vr := cfg.Env.Get("HOME " + name); vr.IsSet() {
return vr.String(), rest
}
Expand Down
5 changes: 2 additions & 3 deletions interp/interp.go
Expand Up @@ -11,7 +11,6 @@ import (
"io/ioutil"
"math"
"os"
"os/user"
"path/filepath"
"regexp"
"runtime"
Expand Down Expand Up @@ -568,8 +567,8 @@ func (r *Runner) Reset() {
}
}
if vr := r.Env.Get("HOME"); !vr.IsSet() {
u, _ := user.Current()
r.Vars["HOME"] = expand.Variable{Kind: expand.String, Str: u.HomeDir}
home, _ := os.UserHomeDir()
r.Vars["HOME"] = expand.Variable{Kind: expand.String, Str: home}
}
r.Vars["PWD"] = expand.Variable{Kind: expand.String, Str: r.Dir}
r.Vars["IFS"] = expand.Variable{Kind: expand.String, Str: " \t\n"}
Expand Down
15 changes: 15 additions & 0 deletions shell/expand_test.go
Expand Up @@ -7,6 +7,7 @@ import (
"fmt"
"os"
"reflect"
"runtime"
"strings"
"testing"
)
Expand Down Expand Up @@ -91,6 +92,20 @@ var fieldsTests = []struct {
{"~/foo/bar", strEnviron("HOME=/my/home"), []string{"/my/home/foo/bar"}},
{"~foo/file", strEnviron("HOME foo=/bar"), []string{"/bar/file"}},
{"*.go", nil, []string{"*.go"}},

{"~", func(name string) string {
switch runtime.GOOS {
case "windows":
if name == "USERPROFILE" {
return "/my/home"
}
default:
if name == "HOME" {
return "/my/home"
}
}
return ""
}, []string{"/my/home"}},
}

func TestFields(t *testing.T) {
Expand Down

0 comments on commit 4a0ebd2

Please sign in to comment.