Commit 776a6a8e5f8e258d31aded73c0ce38df6ac7bdc4

Yoichi Nakayama 2021-10-22T00:09:39

Return the oldest reflog entry on revparse when older time is given For better compatibility with git command which returns the oldest log entry with a warning message.

diff --git a/src/revparse.c b/src/revparse.c
index cf39936..8be22d6 100644
--- a/src/revparse.c
+++ b/src/revparse.c
@@ -207,7 +207,7 @@ static int retrieve_oid_from_reflog(git_oid *oid, git_reference *ref, size_t ide
 {
 	git_reflog *reflog;
 	size_t numentries;
-	const git_reflog_entry *entry;
+	const git_reflog_entry *entry = NULL;
 	bool search_by_pos = (identifier <= 100000000);
 
 	if (git_reflog_read(&reflog, git_reference_owner(ref), git_reference_name(ref)) < 0)
@@ -236,8 +236,12 @@ static int retrieve_oid_from_reflog(git_oid *oid, git_reference *ref, size_t ide
 			break;
 		}
 
-		if (i == numentries)
-			goto notfound;
+		if (i == numentries) {
+			if (entry == NULL)
+				goto notfound;
+
+			git_oid_cpy(oid, git_reflog_entry_id_new(entry));
+		}
 	}
 
 	git_reflog_free(reflog);
diff --git a/tests/refs/revparse.c b/tests/refs/revparse.c
index 9c96070..d6ec802 100644
--- a/tests/refs/revparse.c
+++ b/tests/refs/revparse.c
@@ -399,7 +399,7 @@ void test_refs_revparse__date(void)
 	 * a65fedf HEAD@{1335806603 -0900}: commit:
 	 * be3563a HEAD@{1335806563 -0700}: clone: from /Users/ben/src/libgit2/tests/resour
 	 */
-	test_object("HEAD@{10 years ago}", NULL);
+	test_object("HEAD@{10 years ago}", "be3563ae3f795b2b4353bcce3a527ad0a4f7f644");
 
 	test_object("HEAD@{1 second}", "a65fedf39aefe402d3bb6e24df4d4f5fe4547750");
 	test_object("HEAD@{1 second ago}", "a65fedf39aefe402d3bb6e24df4d4f5fe4547750");
@@ -417,11 +417,12 @@ void test_refs_revparse__date(void)
 
 
 	/*
-	 * $ git reflog -1 "master@{2012-04-30 17:22:42 +0000}"
-	 * warning: Log for 'master' only goes back to Mon, 30 Apr 2012 09:22:43 -0800.
+	 * $ git rev-parse "master@{2012-04-30 17:22:42 +0000}"
+	 * warning: log for 'master' only goes back to Mon, 30 Apr 2012 09:22:43 -0800
+	 * be3563ae3f795b2b4353bcce3a527ad0a4f7f644
 	 */
-	test_object("master@{2012-04-30 17:22:42 +0000}", NULL);
-	test_object("master@{2012-04-30 09:22:42 -0800}", NULL);
+	test_object("master@{2012-04-30 17:22:42 +0000}", "be3563ae3f795b2b4353bcce3a527ad0a4f7f644");
+	test_object("master@{2012-04-30 09:22:42 -0800}", "be3563ae3f795b2b4353bcce3a527ad0a4f7f644");
 
 	/*
 	 * $ git reflog -1 "master@{2012-04-30 17:22:43 +0000}"
@@ -451,6 +452,12 @@ void test_refs_revparse__date(void)
 	 */
 	test_object("master@{1335806603}", "a65fedf39aefe402d3bb6e24df4d4f5fe4547750");
 	test_object("master@{1335806602}", "be3563ae3f795b2b4353bcce3a527ad0a4f7f644");
+
+	/*
+	 * $ git rev-parse "with-empty-log@{2 days ago}" --
+	 * fatal: log for refs/heads/with-empty-log is empty
+	 */
+	test_object("with-empty-log@{2 days ago}", NULL);
 }
 
 void test_refs_revparse__colon(void)