format-patch: pick up branch description when no ref is specified

We only try to get branch name in "format-patch origin" case or
similar and not "format-patch -22" where HEAD is automatically
added. Without correct branch name, branch description cannot be
added. Make sure we always get branch name.

Signed-off-by: Nguyễn Thái Ngọc Duy <pclouds@gmail.com>
Signed-off-by: Junio C Hamano <gitster@pobox.com>
diff --git a/builtin/log.c b/builtin/log.c
index a293a3f..8f48885 100644
--- a/builtin/log.c
+++ b/builtin/log.c
@@ -1014,6 +1014,7 @@
 {
 	int i, positive = -1;
 	unsigned char branch_sha1[20];
+	const unsigned char *tip_sha1;
 	const char *ref;
 	char *full_ref, *branch = NULL;
 
@@ -1025,12 +1026,24 @@
 		else
 			return NULL;
 	}
-	if (positive < 0)
+	if (0 <= positive) {
+		ref = rev->cmdline.rev[positive].name;
+		tip_sha1 = rev->cmdline.rev[positive].item->sha1;
+	} else if (!rev->cmdline.nr && rev->pending.nr == 1 &&
+		   !strcmp(rev->pending.objects[0].name, "HEAD")) {
+		/*
+		 * No actual ref from command line, but "HEAD" from
+		 * rev->def was added in setup_revisions()
+		 * e.g. format-patch --cover-letter -12
+		 */
+		ref = "HEAD";
+		tip_sha1 = rev->pending.objects[0].item->sha1;
+	} else {
 		return NULL;
-	ref = rev->cmdline.rev[positive].name;
+	}
 	if (dwim_ref(ref, strlen(ref), branch_sha1, &full_ref) &&
 	    !prefixcmp(full_ref, "refs/heads/") &&
-	    !hashcmp(rev->cmdline.rev[positive].item->sha1, branch_sha1))
+	    !hashcmp(tip_sha1, branch_sha1))
 		branch = xstrdup(full_ref + strlen("refs/heads/"));
 	free(full_ref);
 	return branch;
diff --git a/t/t4014-format-patch.sh b/t/t4014-format-patch.sh
index 7b536e0..8197c74 100755
--- a/t/t4014-format-patch.sh
+++ b/t/t4014-format-patch.sh
@@ -926,4 +926,11 @@
 	grep hello actual >/dev/null
 '
 
+test_expect_success 'cover letter using branch description (6)' '
+	git checkout rebuild-1 &&
+	test_config branch.rebuild-1.description hello &&
+	git format-patch --stdout --cover-letter -2 >actual &&
+	grep hello actual >/dev/null
+'
+
 test_done