git-codereview: create hooks directory if it doesn't exist

Fixes golang/go#21028

On some versions of Git, "git init" will not create ".git/hooks
directory", causing "git change" to fail. This fix will check if the hooks
directory exists, and if not, create it.

Change-Id: I6a9e688740fde8701e5d48630686039c8ebf4172
Reviewed-on: https://go-review.googlesource.com/49070
Reviewed-by: Kevin Burke <kev@inburke.com>
diff --git a/git-codereview/hook.go b/git-codereview/hook.go
index f953478..b80c567 100644
--- a/git-codereview/hook.go
+++ b/git-codereview/hook.go
@@ -62,7 +62,14 @@
 		if !os.IsNotExist(err) {
 			dief("checking hook: %v", err)
 		}
+
 		verbosef("installing %s hook", hookFile)
+		if _, err := os.Stat(hooksDir); os.IsNotExist(err) {
+			verbosef("creating hooks directory %s", hooksDir)
+			if err := os.Mkdir(hooksDir, 0777); err != nil {
+				dief("creating hooks directory: %v", err)
+			}
+		}
 		if err := ioutil.WriteFile(filename, []byte(hookContent), 0700); err != nil {
 			dief("writing hook: %v", err)
 		}
diff --git a/git-codereview/util_test.go b/git-codereview/util_test.go
index f3d06df..7f088e8 100644
--- a/git-codereview/util_test.go
+++ b/git-codereview/util_test.go
@@ -159,6 +159,9 @@
 	// In any event, we wouldn't be testing what we want to test.
 	// Tests that want to exercise hooks need to arrange for a git-codereview
 	// in the path and replace these with the real ones.
+	if _, err := os.Stat(client + "/.git/hooks"); os.IsNotExist(err) {
+		mkdir(t, client+"/.git/hooks")
+	}
 	for _, h := range hookFiles {
 		write(t, client+"/.git/hooks/"+h, "#!/bin/bash\nexit 0\n")
 	}
@@ -189,9 +192,7 @@
 }
 
 func (gt *gitTest) removeStubHooks() {
-	for _, h := range hookFiles {
-		os.RemoveAll(gt.client + "/.git/hooks/" + h)
-	}
+	os.RemoveAll(gt.client + "/.git/hooks/")
 }
 
 func mkdir(t *testing.T, dir string) {