Commit 5bd78c48e10a8a025b17a53ed700a42d1b594c08

Carlos Martín Nieto 2018-12-14T14:41:17

refs: constify git_reference_peel We have no need to take a non-const reference. This does involve some other work to make sure we don't mix const and non-const variables, but by splitting what we want each variable to do we can also simplify the logic for when we do want to free a new reference we might have allocated.

diff --git a/include/git2/refs.h b/include/git2/refs.h
index ec67a8f..5504c30 100644
--- a/include/git2/refs.h
+++ b/include/git2/refs.h
@@ -710,7 +710,7 @@ GIT_EXTERN(int) git_reference_normalize_name(
  */
 GIT_EXTERN(int) git_reference_peel(
 	git_object **out,
-	git_reference *ref,
+	const git_reference *ref,
 	git_object_t type);
 
 /**
diff --git a/src/refs.c b/src/refs.c
index ee2718d..50afb26 100644
--- a/src/refs.c
+++ b/src/refs.c
@@ -1337,7 +1337,7 @@ int git_reference_is_note(const git_reference *ref)
 	return git_reference__is_note(ref->name);
 }
 
-static int peel_error(int error, git_reference *ref, const char* msg)
+static int peel_error(int error, const git_reference *ref, const char* msg)
 {
 	giterr_set(
 		GITERR_INVALID,
@@ -1347,10 +1347,11 @@ static int peel_error(int error, git_reference *ref, const char* msg)
 
 int git_reference_peel(
 	git_object **peeled,
-	git_reference *ref,
+	const git_reference *ref,
 	git_object_t target_type)
 {
-	git_reference *resolved = NULL;
+	const git_reference *resolved = NULL;
+	git_reference *allocated = NULL;
 	git_object *target = NULL;
 	int error;
 
@@ -1359,8 +1360,10 @@ int git_reference_peel(
 	if (ref->type == GIT_REF_OID) {
 		resolved = ref;
 	} else {
-		if ((error = git_reference_resolve(&resolved, ref)) < 0)
+		if ((error = git_reference_resolve(&allocated, ref)) < 0)
 			return peel_error(error, ref, "Cannot resolve reference");
+
+		resolved = allocated;
 	}
 
 	/*
@@ -1389,9 +1392,7 @@ int git_reference_peel(
 
 cleanup:
 	git_object_free(target);
-
-	if (resolved != ref)
-		git_reference_free(resolved);
+	git_reference_free(allocated);
 
 	return error;
 }