object-file: refactor map_loose_object_1()

This function can do 3 things: 1. Gets an fd given a path 2. Simultaneously gets a path and fd given an OID 3. Memory maps an fd Keep 3 (renaming the function accordingly) and inline 1 and 2 into their respective callers. Signed-off-by: Jonathan Tan <jonathantanmy@google.com> Signed-off-by: Junio C Hamano <gitster@pobox.com>

Jonathan Tan committed Dec 14, 2022 at 11:17 UTC ae285ac4492d73f83a45850267947e29a48e1469
1 file changed +24 -26
object-file.c
+24 -26
@@ -1211,35 +1211,25 @@ static int quick_has_loose(struct repository *r,
1211 }
1212
1213 /*
1214 - * Map the loose object at "path" if it is not NULL, or the path found by
1215 - * searching for a loose object named "oid".
1214 + * Map and close the given loose object fd. The path argument is used for
1215 + * error reporting.
1216 */
1217 -static void *map_loose_object_1(struct repository *r, const char *path,
1218 - const struct object_id *oid, unsigned long *size)
1217 +static void *map_fd(int fd, const char *path, unsigned long *size)
1218 {
1220 - void *map;
1221 - int fd;
1222 -
1223 - if (path)
1224 - fd = git_open(path);
1225 - else
1226 - fd = open_loose_object(r, oid, &path);
1227 - map = NULL;
1228 - if (fd >= 0) {
1229 - struct stat st;
1219 + void *map = NULL;
1220 + struct stat st;
1221
1231 - if (!fstat(fd, &st)) {
1232 - *size = xsize_t(st.st_size);
1233 - if (!*size) {
1234 - /* mmap() is forbidden on empty files */
1235 - error(_("object file %s is empty"), path);
1236 - close(fd);
1237 - return NULL;
1238 - }
1239 - map = xmmap(NULL, *size, PROT_READ, MAP_PRIVATE, fd, 0);
1222 + if (!fstat(fd, &st)) {
1223 + *size = xsize_t(st.st_size);
1224 + if (!*size) {
1225 + /* mmap() is forbidden on empty files */
1226 + error(_("object file %s is empty"), path);
1227 + close(fd);
1228 + return NULL;
1229 }
1241 - close(fd);
1230 + map = xmmap(NULL, *size, PROT_READ, MAP_PRIVATE, fd, 0);
1231 }
1232 + close(fd);
1233 return map;
1234 }
1235
@@ -1247,7 +1237,12 @@ void *map_loose_object(struct repository *r,
1237 const struct object_id *oid,
1238 unsigned long *size)
1239 {
1250 - return map_loose_object_1(r, NULL, oid, size);
1240 + const char *p;
1241 + int fd = open_loose_object(r, oid, &p);
1242 +
1243 + if (fd < 0)
1244 + return NULL;
1245 + return map_fd(fd, p, size);
1246 }
1247
1248 enum unpack_loose_header_result unpack_loose_header(git_zstream *stream,
@@ -2789,13 +2784,16 @@ int read_loose_object(const char *path,
2784 struct object_info *oi)
2785 {
2786 int ret = -1;
2787 + int fd;
2788 void *map = NULL;
2789 unsigned long mapsize;
2790 git_zstream stream;
2791 char hdr[MAX_HEADER_LEN];
2792 unsigned long *size = oi->sizep;
2793
2798 - map = map_loose_object_1(the_repository, path, NULL, &mapsize);
2794 + fd = git_open(path);
2795 + if (fd >= 0)
2796 + map = map_fd(fd, path, &mapsize);
2797 if (!map) {
2798 error_errno(_("unable to mmap %s"), path);
2799 goto out;