diff --git a/cmd/go-contrib-init/contrib.go b/cmd/go-contrib-init/contrib.go index e9a2906d..112ecfe8 100644 --- a/cmd/go-contrib-init/contrib.go +++ b/cmd/go-contrib-init/contrib.go @@ -87,16 +87,30 @@ func expandUser(s string) string { } else if runtime.GOOS == "plan9" { env = "home" } - if home := os.Getenv(env); home != "" { - return strings.Replace(s, "~", home, 1) + home := os.Getenv(env) + 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 { out, _ := exec.Command("git", "config", "http.cookiefile").Output() if s := strings.TrimSpace(string(out)); s != "" { - if strings.Contains(s, "~") { + if strings.HasPrefix(s, "~") { s = expandUser(s) } return s diff --git a/cmd/go-contrib-init/contrib_test.go b/cmd/go-contrib-init/contrib_test.go new file mode 100644 index 00000000..c151f020 --- /dev/null +++ b/cmd/go-contrib-init/contrib_test.go @@ -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) + } + } +}