Expose patch serialization to git_buf Returning library-allocated strings from libgit2 works fine on Linux, but may cause problems on Windows because there is no one C Runtime that everything links against. With libgit2 not exposing its own allocator, freeing the string is a gamble. git_patch_to_str already serializes to a buffer, then returns the underlying memory. Expose the functionality directly, so callers can use the git_buf_free function to free the memory later.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
diff --git a/include/git2/patch.h b/include/git2/patch.h
index e09f625..e5dd5d8 100644
--- a/include/git2/patch.h
+++ b/include/git2/patch.h
@@ -242,6 +242,16 @@ GIT_EXTERN(int) git_patch_to_str(
char **string,
git_patch *patch);
+/**
+ * Get the content of a patch as a single diff text.
+ *
+ * @param out The git_buf to be filled in
+ * @param patch A git_patch representing changes to one file
+ * @return 0 on success, <0 on failure.
+ */
+GIT_EXTERN(int) git_patch_to_buf(
+ git_buf *out,
+ git_patch *patch);
GIT_END_DECL
diff --git a/src/diff_print.c b/src/diff_print.c
index 7a70e2b..0ab21d0 100644
--- a/src/diff_print.c
+++ b/src/diff_print.c
@@ -452,7 +452,15 @@ static int diff_print_to_buffer_cb(
return git_buf_put(output, line->content, line->content_len);
}
-/* print a git_patch to a string buffer */
+/* print a git_patch to a git_buf */
+int git_patch_to_buf(
+ git_buf *out,
+ git_patch *patch)
+{
+ return git_patch_print(patch, diff_print_to_buffer_cb, out);
+}
+
+/* print a git_patch to a char* */
int git_patch_to_str(
char **string,
git_patch *patch)
@@ -460,7 +468,7 @@ int git_patch_to_str(
int error;
git_buf output = GIT_BUF_INIT;
- if (!(error = git_patch_print(patch, diff_print_to_buffer_cb, &output)))
+ if (!(error = git_patch_to_buf(&output, patch)))
*string = git_buf_detach(&output);
else {
git_buf_free(&output);