Skip to content
Permalink
Browse files

expand: support ~ on Windows without $HOME

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 4a0ebd2f3c1b82ee08969e36423d78c8cbaffc3b
Showing with 37 additions and 4 deletions.
  1. +20 −1 expand/expand.go
  2. +2 −3 interp/interp.go
  3. +15 −0 shell/expand_test.go
@@ -11,6 +11,7 @@ import (
"os/user"
"path/filepath"
"regexp"
"runtime"
"strconv"
"strings"

@@ -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
}
@@ -11,7 +11,6 @@ import (
"io/ioutil"
"math"
"os"
"os/user"
"path/filepath"
"regexp"
"runtime"
@@ -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"}
@@ -7,6 +7,7 @@ import (
"fmt"
"os"
"reflect"
"runtime"
"strings"
"testing"
)
@@ -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) {

0 comments on commit 4a0ebd2

Please sign in to comment.
You can’t perform that action at this time.