Skip to content

Commit 98e2092

Browse files
peffgitster
authored andcommitted
cat-file: teach --batch to stream blob objects
The regular "git cat-file -p" and "git cat-file blob" code paths already learned to stream large blobs. Let's do the same here. Note that this means we look up the type and size before making a decision of whether to load the object into memory or stream (just like the "-p" code path does). That can lead to extra work, but it should be dwarfed by the cost of actually accessing the object itself. In my measurements, there was a 1-2% slowdown when using "--batch" on a large number of objects. Signed-off-by: Jeff King <[email protected]> Signed-off-by: Junio C Hamano <[email protected]>
1 parent 03c893c commit 98e2092

File tree

1 file changed

+28
-13
lines changed

1 file changed

+28
-13
lines changed

builtin/cat-file.c

Lines changed: 28 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -117,12 +117,36 @@ static int cat_one_file(int opt, const char *exp_type, const char *obj_name)
117117
return 0;
118118
}
119119

120+
static void print_object_or_die(int fd, const unsigned char *sha1,
121+
enum object_type type, unsigned long size)
122+
{
123+
if (type == OBJ_BLOB) {
124+
if (stream_blob_to_fd(fd, sha1, NULL, 0) < 0)
125+
die("unable to stream %s to stdout", sha1_to_hex(sha1));
126+
}
127+
else {
128+
enum object_type rtype;
129+
unsigned long rsize;
130+
void *contents;
131+
132+
contents = read_sha1_file(sha1, &rtype, &rsize);
133+
if (!contents)
134+
die("object %s disappeared", sha1_to_hex(sha1));
135+
if (rtype != type)
136+
die("object %s changed type!?", sha1_to_hex(sha1));
137+
if (rsize != size)
138+
die("object %s change size!?", sha1_to_hex(sha1));
139+
140+
write_or_die(fd, contents, size);
141+
free(contents);
142+
}
143+
}
144+
120145
static int batch_one_object(const char *obj_name, int print_contents)
121146
{
122147
unsigned char sha1[20];
123148
enum object_type type = 0;
124149
unsigned long size;
125-
void *contents = NULL;
126150

127151
if (!obj_name)
128152
return 1;
@@ -133,29 +157,20 @@ static int batch_one_object(const char *obj_name, int print_contents)
133157
return 0;
134158
}
135159

136-
if (print_contents == BATCH)
137-
contents = read_sha1_file(sha1, &type, &size);
138-
else
139-
type = sha1_object_info(sha1, &size);
140-
160+
type = sha1_object_info(sha1, &size);
141161
if (type <= 0) {
142162
printf("%s missing\n", obj_name);
143163
fflush(stdout);
144-
if (print_contents == BATCH)
145-
free(contents);
146164
return 0;
147165
}
148166

149167
printf("%s %s %lu\n", sha1_to_hex(sha1), typename(type), size);
150168
fflush(stdout);
151169

152170
if (print_contents == BATCH) {
153-
write_or_die(1, contents, size);
154-
printf("\n");
155-
fflush(stdout);
156-
free(contents);
171+
print_object_or_die(1, sha1, type, size);
172+
write_or_die(1, "\n", 1);
157173
}
158-
159174
return 0;
160175
}
161176

0 commit comments

Comments
 (0)