git-codereview: fix buglet in 'reword' related to work trees

The reword command was trying to store a saved messages file in the
subdirectory .git in the repo root; this doesn't work well if multiple
work trees are in use and the user is working in a non-main work tree.
Use "git rev-parse --git-path ." instead of "git rev-parse
--show-top-level" to find the location for the saved messages file.

Fixes golang/go#43695.

Change-Id: Ie0b3e810ad585fe1c18805f4070736335a2ef2b5
Run-TryBot: Than McIntosh <>
TryBot-Result: Go Bot <>
Reviewed-by: Russ Cox <>
Trust: Than McIntosh <>
diff --git a/git-codereview/hook.go b/git-codereview/hook.go
index 1913666..8bf2a51 100644
--- a/git-codereview/hook.go
+++ b/git-codereview/hook.go
@@ -76,10 +76,26 @@
+// repoRoot returns the root of the currently selected git repo, or
+// worktree root if this is an alternate worktree of a repo.
 func repoRoot() string {
 	return filepath.Clean(trim(cmdOutput("git", "rev-parse", "--show-toplevel")))
+// gitPathDir returns the directory used by git to store temporary
+// files such as COMMIT_EDITMSG, FETCH_HEAD, and such for the repo.
+// For a simple git repo, this will be <root>/.git, and for an
+// alternate worktree of a repo it will be in
+// <root>/.git/worktrees/<worktreename>.
+func gitPathDir() string {
+	gcd := trim(cmdOutput("git", "rev-parse", "--git-path", "."))
+	result, err := filepath.Abs(gcd)
+	if err != nil {
+		dief("%v", err)
+	}
+	return result
 // gitPath resolve the $GIT_DIR/path, taking in consideration
 // all other path relocations, e.g. hooks for linked worktrees
 // are not kept in their gitdir, but shared in the main one.
diff --git a/git-codereview/reword.go b/git-codereview/reword.go
index b2ad0de..9083cde 100644
--- a/git-codereview/reword.go
+++ b/git-codereview/reword.go
@@ -88,7 +88,7 @@
 	// (perhaps the user has forgotten about one in another window),
 	// we don't want them to step on each other during editing.
 	var buf bytes.Buffer
-	saveFile := filepath.Join(repoRoot(), ".git/REWORD_MSGS")
+	saveFile := filepath.Join(gitPathDir(), "REWORD_MSGS")
 	saveBuf := func() {
 		if err := ioutil.WriteFile(saveFile, buf.Bytes(), 0666); err != nil {
 			dief("cannot save messages: %v", err)