cmd/coordinator: apply minor improvements

These are the changes that have been pulled out of the previous CL to
keep it a more pure refactor.

The check for "same repo" is improved to handle the case of two repos
sharing a prefix (e.g., "golang.org/x/foo" and "golang.org/x/foobar").

The Dir field is set to repo root when invoking go list (it shouldn't
have an effect because it's currently done only in GOPATH mode). This
should make it more consistent with a future change that starts calling
go list in module mode for another purpose.

Create new repo variable instead of reusing repo parameter in findDeps.

Change-Id: Iba09fd2c4e9345e58ef885ce8ed4ba2acdfa3df7
Reviewed-on: https://go-review.googlesource.com/c/build/+/194359
Run-TryBot: Dmitri Shuralyov <dmitshur@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Brad Fitzpatrick <bradfitz@golang.org>
diff --git a/cmd/coordinator/coordinator.go b/cmd/coordinator/coordinator.go
index e0f1512..33c8966 100644
--- a/cmd/coordinator/coordinator.go
+++ b/cmd/coordinator/coordinator.go
@@ -2404,12 +2404,13 @@
 		}
 
 		// findDeps uses 'go list' on the checked out repo to find its
-		// dependencies, and adds any not-yet-fetched deps to toFetched.
+		// dependencies, and adds any not-yet-fetched deps to toFetch.
 		findDeps := func(repo string) (rErr, err error) {
 			repoPath := importPathOfRepo(repo)
 			var buf bytes.Buffer
 			rErr, err = st.bc.Exec(path.Join("go", "bin", "go"), buildlet.ExecOpts{
 				Output:   &buf,
+				Dir:      "gopath/src/" + repoPath,
 				ExtraEnv: append(st.conf.Env(), "GOROOT="+goroot, "GOPATH="+gopath),
 				Path:     []string{"$WORKDIR/go/bin", "$PATH"},
 				Args:     []string{"list", "-f", `{{range .Deps}}{{printf "%v\n" .}}{{end}}`, repoPath + "/..."},
@@ -2422,10 +2423,11 @@
 				return rErr, nil
 			}
 			for _, p := range strings.Fields(buf.String()) {
-				if !strings.HasPrefix(p, "golang.org/x/") || strings.HasPrefix(p, repoPath) {
+				if !strings.HasPrefix(p, "golang.org/x/") ||
+					p == repoPath || strings.HasPrefix(p, repoPath+"/") {
 					continue
 				}
-				repo = strings.TrimPrefix(p, "golang.org/x/")
+				repo := strings.TrimPrefix(p, "golang.org/x/")
 				if i := strings.Index(repo, "/"); i >= 0 {
 					repo = repo[:i]
 				}
@@ -2494,7 +2496,7 @@
 	return st.bc.Exec(path.Join("go", "bin", "go"), buildlet.ExecOpts{
 		Debug:    true, // make buildlet print extra debug in output for failures
 		Output:   st,
-		Dir:      "gopath/src/golang.org/x/" + st.SubName,
+		Dir:      "gopath/src/" + importPathOfRepo(st.SubName),
 		ExtraEnv: env,
 		Path:     []string{"$WORKDIR/go/bin", "$PATH"},
 		Args:     args,