tools: handle paths like ~/ or $HOME/.
tilde should be located at the beginning of line. Change-Id: I271ba5220da3c483838d1741d908755aee8e081e Reviewed-on: https://go-review.googlesource.com/46430 Reviewed-by: Brad Fitzpatrick <bradfitz@golang.org>
This commit is contained in:
parent
cd6e398dae
commit
545ce0dcdd
|
@ -87,16 +87,30 @@ func expandUser(s string) string {
|
||||||
} else if runtime.GOOS == "plan9" {
|
} else if runtime.GOOS == "plan9" {
|
||||||
env = "home"
|
env = "home"
|
||||||
}
|
}
|
||||||
if home := os.Getenv(env); home != "" {
|
home := os.Getenv(env)
|
||||||
return strings.Replace(s, "~", home, 1)
|
if home == "" {
|
||||||
}
|
|
||||||
return s
|
return s
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(s) >= 2 && s[0] == '~' && os.IsPathSeparator(s[1]) {
|
||||||
|
if runtime.GOOS == "windows" {
|
||||||
|
s = filepath.ToSlash(filepath.Join(home, s[2:]))
|
||||||
|
} else {
|
||||||
|
s = filepath.Join(home, s[2:])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return os.Expand(s, func(env string) string {
|
||||||
|
if env == "HOME" {
|
||||||
|
return home
|
||||||
|
}
|
||||||
|
return os.Getenv(env)
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func cookiesFile() string {
|
func cookiesFile() string {
|
||||||
out, _ := exec.Command("git", "config", "http.cookiefile").Output()
|
out, _ := exec.Command("git", "config", "http.cookiefile").Output()
|
||||||
if s := strings.TrimSpace(string(out)); s != "" {
|
if s := strings.TrimSpace(string(out)); s != "" {
|
||||||
if strings.Contains(s, "~") {
|
if strings.HasPrefix(s, "~") {
|
||||||
s = expandUser(s)
|
s = expandUser(s)
|
||||||
}
|
}
|
||||||
return s
|
return s
|
||||||
|
|
|
@ -0,0 +1,35 @@
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"runtime"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestExpandUser(t *testing.T) {
|
||||||
|
env := "HOME"
|
||||||
|
if runtime.GOOS == "windows" {
|
||||||
|
env = "USERPROFILE"
|
||||||
|
} else if runtime.GOOS == "plan9" {
|
||||||
|
env = "home"
|
||||||
|
}
|
||||||
|
|
||||||
|
oldenv := os.Getenv(env)
|
||||||
|
os.Setenv(env, "/home/gopher")
|
||||||
|
defer os.Setenv(env, oldenv)
|
||||||
|
|
||||||
|
tests := []struct {
|
||||||
|
input string
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{input: "~/foo", want: "/home/gopher/foo"},
|
||||||
|
{input: "${HOME}/foo", want: "/home/gopher/foo"},
|
||||||
|
{input: "/~/foo", want: "/~/foo"},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
got := expandUser(tt.input)
|
||||||
|
if got != tt.want {
|
||||||
|
t.Fatalf("want %q, but %q", tt.want, got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in New Issue