review: look in correct location for netrc on Windows.

Change-Id: I38a58a2fb1bf6f4840cca8fe24aaa85ad3d6289e
Reviewed-on: https://go-review.googlesource.com/21252
Run-TryBot: Andrew Gerrand <adg@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Andrew Gerrand <adg@golang.org>
diff --git a/git-codereview/api.go b/git-codereview/api.go
index 786ac60..910900f 100644
--- a/git-codereview/api.go
+++ b/git-codereview/api.go
@@ -12,7 +12,9 @@
 	"io/ioutil"
 	"net/http"
 	"net/url"
-	"os"
+	"os/user"
+	"path/filepath"
+	"runtime"
 	"sort"
 	"strings"
 )
@@ -120,6 +122,19 @@
 	return nil
 }
 
+// testHomeDir is empty for normal use. During tests it may be set and used
+// in place of the actual home directory. Tests may still need to
+// set the HOME var for sub-processes such as git.
+var testHomeDir = ""
+
+func netrcName() string {
+	// Git on Windows will look in $HOME\_netrc.
+	if runtime.GOOS == "windows" {
+		return "_netrc"
+	}
+	return ".netrc"
+}
+
 // loadAuth loads the authentication tokens for making API calls to
 // the Gerrit origin host.
 func loadAuth() {
@@ -152,7 +167,16 @@
 	// If not there, then look in $HOME/.netrc, which is where Gerrit
 	// used to tell users to store the information, until the passwords
 	// got so long that old versions of curl couldn't handle them.
-	data, _ := ioutil.ReadFile(os.Getenv("HOME") + "/.netrc")
+	netrc := netrcName()
+	homeDir := testHomeDir
+	if homeDir == "" {
+		usr, err := user.Current()
+		if err != nil {
+			dief("failed to get current user home directory to look for %q: %v", netrc, err)
+		}
+		homeDir = usr.HomeDir
+	}
+	data, _ := ioutil.ReadFile(filepath.Join(homeDir, netrc))
 	for _, line := range lines(string(data)) {
 		if i := strings.Index(line, "#"); i >= 0 {
 			line = line[:i]
diff --git a/git-codereview/api_test.go b/git-codereview/api_test.go
index 279a76f..41c599f 100644
--- a/git-codereview/api_test.go
+++ b/git-codereview/api_test.go
@@ -6,6 +6,7 @@
 
 import (
 	"os"
+	"path/filepath"
 	"testing"
 )
 
@@ -75,6 +76,12 @@
 
 	defer os.Setenv("HOME", os.Getenv("HOME"))
 	os.Setenv("HOME", gt.client)
+
+	testHomeDir = gt.client
+	netrc := filepath.Join(gt.client, netrcName())
+	defer func() {
+		testHomeDir = ""
+	}()
 	trun(t, gt.client, "git", "config", "remote.origin.url", "https://go.googlesource.com/go")
 
 	for i, tt := range authTests {
@@ -86,10 +93,10 @@
 		trun(t, gt.client, "git", "config", "http.cookiefile", "XXX")
 		trun(t, gt.client, "git", "config", "--unset", "http.cookiefile")
 
-		remove(t, gt.client+"/.netrc")
+		remove(t, netrc)
 		remove(t, gt.client+"/.cookies")
 		if tt.netrc != "" {
-			write(t, gt.client+"/.netrc", tt.netrc)
+			write(t, netrc, tt.netrc)
 		}
 		if tt.cookiefile != "" {
 			if tt.cookiefile != "MISSING" {
@@ -99,7 +106,6 @@
 		}
 
 		// Run command via testMain to trap stdout, stderr, death.
-		// mail -n will load auth info for us.
 		if tt.died {
 			testMainDied(t, "test-loadAuth")
 		} else {