path: root/commit.c
diff options
authorJeff King <>2014-06-10 21:40:39 (GMT)
committerJunio C Hamano <>2014-06-13 19:08:17 (GMT)
commit152ff1ccebd822fd97f27d2a6c3fa2058f088fd8 (patch)
tree05c0d7681d2b3e76196d9ee05b94398d62dcf2ec /commit.c
parent66c2827ea4deb24ff541e30a5b6239ad5e9f6801 (diff)
provide helpers to access the commit buffer
Many sites look at commit->buffer to get more detailed information than what is in the parsed commit struct. However, we sometimes drop commit->buffer to save memory, in which case the caller would need to read the object afresh. Some callers do this (leading to duplicated code), and others do not (which opens the possibility of a segfault if somebody else frees the buffer). Let's provide a pair of helpers, "get" and "unuse", that let callers easily get the buffer. They will use the cached buffer when possible, and otherwise load from disk using read_sha1_file. Note that we also need to add a "get_cached" variant which returns NULL when we do not have a cached buffer. At first glance this seems to defeat the purpose of "get", which is to always provide a return value. However, some log code paths actually use the NULL-ness of commit->buffer as a boolean flag to decide whether to try printing the commit. At least for now, we want to continue supporting that use. Signed-off-by: Jeff King <> Signed-off-by: Junio C Hamano <>
Diffstat (limited to 'commit.c')
1 files changed, 28 insertions, 0 deletions
diff --git a/commit.c b/commit.c
index fc8b4e2..b6b0e0d 100644
--- a/commit.c
+++ b/commit.c
@@ -250,6 +250,34 @@ void set_commit_buffer(struct commit *commit, void *buffer)
commit->buffer = buffer;
+const void *get_cached_commit_buffer(const struct commit *commit)
+ return commit->buffer;
+const void *get_commit_buffer(const struct commit *commit)
+ const void *ret = get_cached_commit_buffer(commit);
+ if (!ret) {
+ enum object_type type;
+ unsigned long size;
+ ret = read_sha1_file(commit->object.sha1, &type, &size);
+ if (!ret)
+ die("cannot read commit object %s",
+ sha1_to_hex(commit->object.sha1));
+ if (type != OBJ_COMMIT)
+ die("expected commit for %s, got %s",
+ sha1_to_hex(commit->object.sha1), typename(type));
+ }
+ return ret;
+void unuse_commit_buffer(const struct commit *commit, const void *buffer)
+ if (commit->buffer != buffer)
+ free((void *)buffer);
void free_commit_buffer(struct commit *commit)