Raw
1 /*
2 * GIT - The information manager from hell
3 *
4 * Copyright (C) Linus Torvalds, 2005
5 */
6
7 #define USE_THE_REPOSITORY_VARIABLE
8 #define DISABLE_SIGN_COMPARE_WARNINGS
9
10 #include "builtin.h"
11 #include "config.h"
12 #include "convert.h"
13 #include "diff.h"
14 #include "environment.h"
15 #include "gettext.h"
16 #include "hex.h"
17 #include "ident.h"
18 #include "list-objects-filter-options.h"
19 #include "parse-options.h"
20 #include "userdiff.h"
21 #include "oid-array.h"
22 #include "packfile.h"
23 #include "object-file.h"
24 #include "object-name.h"
25 #include "odb.h"
26 #include "odb/streaming.h"
27 #include "replace-object.h"
28 #include "promisor-remote.h"
29 #include "mailmap.h"
30 #include "write-or-die.h"
31 #include "alias.h"
32 #include "remote.h"
33 #include "transport.h"
34
35 /*
36 * Maximum length for a remote URL. While no universal standard exists,
37 * 8K is assumed to be a reasonable limit.
38 */
39 #define MAX_REMOTE_URL_LEN (8 * 1024)
40
41 /* Maximum number of objects allowed in a single remote-object-info request. */
42 #define MAX_ALLOWED_OBJ_LIMIT 10000
43
44 /* Maximum input size permitted for the remote-object-info command. */
45 #define MAX_REMOTE_OBJ_INFO_LINE \
46 (MAX_REMOTE_URL_LEN + MAX_ALLOWED_OBJ_LIMIT * (GIT_MAX_HEXSZ + 1))
47
48 enum batch_mode {
49 BATCH_MODE_CONTENTS,
50 BATCH_MODE_INFO,
51 BATCH_MODE_QUEUE_AND_DISPATCH,
52 };
53
54 struct batch_options {
55 struct list_objects_filter_options objects_filter;
56 int enabled;
57 int follow_symlinks;
58 enum batch_mode batch_mode;
59 int buffer_output;
60 int all_objects;
61 int unordered;
62 int transform_mode; /* may be 'w' or 'c' for --filters or --textconv */
63 char input_delim;
64 char output_delim;
65 const char *format;
66 };
67
68 static const char *force_path;
69
70 static struct string_list mailmap = STRING_LIST_INIT_NODUP;
71 static int use_mailmap;
72
73 static char *replace_idents_using_mailmap(char *, size_t *);
74
75 /*
76 * The mailmap is initialized with .strdup_strings set to 0,
77 * but read_mailmap() sets the bit to 1 (this is true even when
78 * not a single mailmap entry is read), so it can be used for
79 * lazy loading.
80 */
81 static void load_mailmap(void)
82 {
83 if (mailmap.strdup_strings)
84 return;
85
86 read_mailmap(the_repository, &mailmap);
87 }
88
89 static char *replace_idents_using_mailmap(char *object_buf, size_t *size)
90 {
91 struct strbuf sb = STRBUF_INIT;
92 const char *headers[] = { "author ", "committer ", "tagger ", NULL };
93
94 strbuf_attach(&sb, object_buf, *size, *size + 1);
95 apply_mailmap_to_header(&sb, headers, &mailmap);
96 *size = sb.len;
97 return strbuf_detach(&sb, NULL);
98 }
99
100 static int filter_object(const char *path, unsigned mode,
101 const struct object_id *oid,
102 char **buf, size_t *size)
103 {
104 enum object_type type;
105
106 *buf = odb_read_object(the_repository->objects, oid, &type, size);
107 if (!*buf)
108 return error(_("cannot read object %s '%s'"),
109 oid_to_hex(oid), path);
110 if ((type == OBJ_BLOB) && S_ISREG(mode)) {
111 struct strbuf strbuf = STRBUF_INIT;
112 struct checkout_metadata meta;
113
114 init_checkout_metadata(&meta, NULL, NULL, oid);
115 if (convert_to_working_tree(the_repository->index, path, *buf, *size, &strbuf, &meta)) {
116 free(*buf);
117 *size = strbuf.len;
118 *buf = strbuf_detach(&strbuf, NULL);
119 }
120 }
121
122 return 0;
123 }
124
125 static int stream_blob(const struct object_id *oid)
126 {
127 if (odb_stream_blob_to_fd(the_repository->objects, 1, oid, NULL, 0))
128 die("unable to stream %s to stdout", oid_to_hex(oid));
129 return 0;
130 }
131
132 static int cat_one_file(int opt, const char *exp_type, const char *obj_name)
133 {
134 int ret;
135 struct object_id oid;
136 enum object_type type;
137 char *buf;
138 size_t size;
139 struct object_context obj_context = {0};
140 struct object_info oi = OBJECT_INFO_INIT;
141 unsigned flags = OBJECT_INFO_LOOKUP_REPLACE;
142 unsigned get_oid_flags =
143 GET_OID_RECORD_PATH |
144 GET_OID_ONLY_TO_DIE |
145 GET_OID_HASH_ANY;
146 const char *path = force_path;
147 const int opt_cw = (opt == 'c' || opt == 'w');
148 if (!path && opt_cw)
149 get_oid_flags |= GET_OID_REQUIRE_PATH;
150
151 if (get_oid_with_context(the_repository, obj_name, get_oid_flags, &oid,
152 &obj_context))
153 die("Not a valid object name %s", obj_name);
154
155 if (!path)
156 path = obj_context.path;
157 if (obj_context.mode == S_IFINVALID)
158 obj_context.mode = 0100644;
159
160 buf = NULL;
161 switch (opt) {
162 case 't':
163 oi.typep = &type;
164 if (odb_read_object_info_extended(the_repository->objects, &oid, &oi, flags) < 0)
165 die("git cat-file: could not get object info");
166 printf("%s\n", type_name(type));
167 ret = 0;
168 goto cleanup;
169
170 case 's':
171 oi.sizep = &size;
172
173 if (use_mailmap) {
174 oi.typep = &type;
175 oi.contentp = (void**)&buf;
176 }
177
178 if (odb_read_object_info_extended(the_repository->objects, &oid, &oi, flags) < 0)
179 die("git cat-file: could not get object info");
180
181 if (use_mailmap && (type == OBJ_COMMIT || type == OBJ_TAG))
182 buf = replace_idents_using_mailmap(buf, &size);
183
184 printf("%"PRIuMAX"\n", (uintmax_t)size);
185 ret = 0;
186 goto cleanup;
187
188 case 'e':
189 ret = !odb_has_object(the_repository->objects, &oid,
190 ODB_HAS_OBJECT_RECHECK_PACKED | ODB_HAS_OBJECT_FETCH_PROMISOR);
191 goto cleanup;
192
193 case 'w':
194
195 if (filter_object(path, obj_context.mode,
196 &oid, &buf, &size)) {
197 ret = -1;
198 goto cleanup;
199 }
200 break;
201
202 case 'c':
203 {
204 unsigned long size_ul = 0;
205 int textconv_ret = textconv_object(the_repository, path,
206 obj_context.mode, &oid, 1,
207 &buf, &size_ul);
208 size = size_ul;
209 if (textconv_ret)
210 break;
211 }
212 /* else fallthrough */
213
214 case 'p':
215 type = odb_read_object_info(the_repository->objects, &oid, NULL);
216 if (type < 0)
217 die("Not a valid object name %s", obj_name);
218
219 /* custom pretty-print here */
220 if (type == OBJ_TREE) {
221 const char *ls_args[3] = { NULL };
222 ls_args[0] = "ls-tree";
223 ls_args[1] = obj_name;
224 ret = cmd_ls_tree(2, ls_args, NULL, the_repository);
225 goto cleanup;
226 }
227
228 if (type == OBJ_BLOB) {
229 ret = stream_blob(&oid);
230 goto cleanup;
231 }
232 buf = odb_read_object(the_repository->objects, &oid,
233 &type, &size);
234 if (!buf)
235 die("Cannot read object %s", obj_name);
236
237 if (use_mailmap)
238 buf = replace_idents_using_mailmap(buf, &size);
239
240 /* otherwise just spit out the data */
241 break;
242
243 case 0:
244 {
245 enum object_type exp_type_id = type_from_string(exp_type);
246
247 if (exp_type_id == OBJ_BLOB) {
248 struct object_id blob_oid;
249 if (odb_read_object_info(the_repository->objects,
250 &oid, NULL) == OBJ_TAG) {
251 char *buffer = odb_read_object(the_repository->objects,
252 &oid, &type, &size);
253 const char *target;
254
255 if (!buffer)
256 die(_("unable to read %s"), oid_to_hex(&oid));
257
258 if (!skip_prefix(buffer, "object ", &target) ||
259 get_oid_hex_algop(target, &blob_oid,
260 &hash_algos[oid.algo]))
261 die("%s not a valid tag", oid_to_hex(&oid));
262 free(buffer);
263 } else
264 oidcpy(&blob_oid, &oid);
265
266 if (odb_read_object_info(the_repository->objects,
267 &blob_oid, NULL) == OBJ_BLOB) {
268 ret = stream_blob(&blob_oid);
269 goto cleanup;
270 }
271 /*
272 * we attempted to dereference a tag to a blob
273 * and failed; there may be new dereference
274 * mechanisms this code is not aware of.
275 * fall-back to the usual case.
276 */
277 }
278 buf = odb_read_object_peeled(the_repository->objects, &oid,
279 exp_type_id, &size, NULL);
280
281 if (use_mailmap)
282 buf = replace_idents_using_mailmap(buf, &size);
283 break;
284 }
285 default:
286 die("git cat-file: unknown option: %s", exp_type);
287 }
288
289 if (!buf)
290 die("git cat-file %s: bad file", obj_name);
291
292 write_or_die(1, buf, size);
293 ret = 0;
294 cleanup:
295 free(buf);
296 object_context_release(&obj_context);
297 return ret;
298 }
299
300 struct expand_data {
301 struct object_id oid;
302 enum object_type type;
303 size_t size;
304 unsigned short mode;
305 off_t disk_size;
306 const char *rest;
307 struct object_id delta_base_oid;
308
309 /*
310 * If mark_query is true, we do not expand anything, but rather
311 * just mark the object_info with items we wish to query.
312 */
313 int mark_query;
314
315 /*
316 * Whether to split the input on whitespace before feeding it to
317 * get_sha1; this is decided during the mark_query phase based on
318 * whether we have a %(rest) token in our format.
319 */
320 int split_on_whitespace;
321
322 /*
323 * After a mark_query run, this object_info is set up to be
324 * passed to odb_read_object_info_extended. It will point to the data
325 * elements above, so you can retrieve the response from there.
326 */
327 struct object_info info;
328
329 /*
330 * This flag will be true if the requested batch format and options
331 * don't require us to call oid_object_info, which can then be
332 * optimized out.
333 */
334 unsigned skip_object_info : 1;
335
336 /*
337 * Flags about when an object info is being fetched from remote.
338 */
339 unsigned is_remote:1;
340
341 /*
342 * List of atoms (i.e. "objectsize") that the server supports. Built
343 * from the server's object-info advertised capabilities.
344 */
345 struct string_list remote_allowed_atoms;
346 };
347
348 #define EXPAND_DATA_INIT { \
349 .mode = S_IFINVALID, \
350 .type = OBJ_BAD, \
351 .remote_allowed_atoms = STRING_LIST_INIT_NODUP, \
352 }
353
354 static int is_atom(const char *atom, const char *s, int slen)
355 {
356 int alen = strlen(atom);
357 return alen == slen && !memcmp(atom, s, alen);
358 }
359
360 static int expand_atom(struct strbuf *sb, const char *atom, int len,
361 struct expand_data *data)
362 {
363 if (data->is_remote) {
364 size_t i;
365 for (i = 0; i < data->remote_allowed_atoms.nr; i++)
366 if (is_atom(data->remote_allowed_atoms.items[i].string,
367 atom, len))
368 break;
369 if (i == data->remote_allowed_atoms.nr)
370 return 1;
371 }
372
373 if (is_atom("objectname", atom, len)) {
374 if (!data->mark_query)
375 strbuf_add_oid_hex(sb, &data->oid);
376 } else if (is_atom("objecttype", atom, len)) {
377 if (data->mark_query) {
378 data->info.typep = &data->type;
379 } else {
380 const char *t = type_name(data->type);
381 strbuf_addstr(sb, t ? t : "");
382 }
383 } else if (is_atom("objectsize", atom, len)) {
384 if (data->mark_query)
385 data->info.sizep = &data->size;
386 else
387 strbuf_add_uint(sb, data->size);
388 } else if (is_atom("objectsize:disk", atom, len)) {
389 if (data->mark_query)
390 data->info.disk_sizep = &data->disk_size;
391 else
392 strbuf_add_uint(sb, data->disk_size);
393 } else if (is_atom("rest", atom, len)) {
394 if (data->mark_query)
395 data->split_on_whitespace = 1;
396 else if (data->rest)
397 strbuf_addstr(sb, data->rest);
398 } else if (is_atom("deltabase", atom, len)) {
399 if (data->mark_query)
400 data->info.delta_base_oid = &data->delta_base_oid;
401 else
402 strbuf_add_oid_hex(sb, &data->delta_base_oid);
403 } else if (is_atom("objectmode", atom, len)) {
404 if (!data->mark_query && !(S_IFINVALID == data->mode))
405 strbuf_addf(sb, "%06o", data->mode);
406 } else
407 return 0;
408 return 1;
409 }
410
411 static void expand_format(struct strbuf *sb, const char *start,
412 struct expand_data *data)
413 {
414 while (strbuf_expand_step(sb, &start)) {
415 const char *end;
416
417 if (skip_prefix(start, "%", &start) || *start != '(')
418 strbuf_addch(sb, '%');
419 else if ((end = strchr(start + 1, ')')) &&
420 expand_atom(sb, start + 1, end - start - 1, data))
421 start = end + 1;
422 else
423 strbuf_expand_bad_format(start, "cat-file");
424 }
425 }
426
427 static void batch_write(struct batch_options *opt, const void *data, int len)
428 {
429 if (opt->buffer_output) {
430 if (fwrite(data, 1, len, stdout) != len)
431 die_errno("unable to write to stdout");
432 } else
433 write_or_die(1, data, len);
434 }
435
436 static void print_object_or_die(struct batch_options *opt, struct expand_data *data)
437 {
438 const struct object_id *oid = &data->oid;
439
440 assert(data->info.typep);
441
442 if (data->type == OBJ_BLOB) {
443 if (opt->buffer_output)
444 fflush(stdout);
445 if (opt->transform_mode) {
446 char *contents;
447 size_t size;
448
449 if (!data->rest)
450 die("missing path for '%s'", oid_to_hex(oid));
451
452 if (opt->transform_mode == 'w') {
453 if (filter_object(data->rest, 0100644, oid,
454 &contents, &size))
455 die("could not convert '%s' %s",
456 oid_to_hex(oid), data->rest);
457 } else if (opt->transform_mode == 'c') {
458 enum object_type type;
459 unsigned long size_ul = 0;
460 if (textconv_object(the_repository,
461 data->rest, 0100644, oid,
462 1, &contents, &size_ul))
463 size = size_ul;
464 else
465 contents = odb_read_object(the_repository->objects,
466 oid, &type, &size);
467 if (!contents)
468 die("could not convert '%s' %s",
469 oid_to_hex(oid), data->rest);
470 } else
471 BUG("invalid transform_mode: %c", opt->transform_mode);
472 batch_write(opt, contents, size);
473 free(contents);
474 } else {
475 stream_blob(oid);
476 }
477 }
478 else {
479 enum object_type type;
480 size_t size;
481 void *contents;
482
483 contents = odb_read_object(the_repository->objects, oid,
484 &type, &size);
485 if (!contents)
486 die("object %s disappeared", oid_to_hex(oid));
487
488 if (use_mailmap)
489 contents = replace_idents_using_mailmap(contents, &size);
490
491 if (type != data->type)
492 die("object %s changed type!?", oid_to_hex(oid));
493 if (data->info.sizep && size != data->size && !use_mailmap)
494 die("object %s changed size!?", oid_to_hex(oid));
495
496 batch_write(opt, contents, size);
497 free(contents);
498 }
499 }
500
501 static void print_default_format(struct strbuf *scratch, struct expand_data *data,
502 struct batch_options *opt)
503 {
504 strbuf_add_oid_hex(scratch, &data->oid);
505 strbuf_addch(scratch, ' ');
506 strbuf_addstr(scratch, type_name(data->type));
507 strbuf_addch(scratch, ' ');
508 strbuf_add_uint(scratch, data->size);
509 strbuf_addch(scratch, opt->output_delim);
510 }
511
512 static void report_object_status(struct batch_options *opt,
513 const char *obj_name,
514 const struct object_id *oid,
515 const char *status)
516 {
517 printf("%s %s%c", obj_name ? obj_name : oid_to_hex(oid),
518 status, opt->output_delim);
519 fflush(stdout);
520 }
521
522 /*
523 * If "pack" is non-NULL, then "offset" is the byte offset within the pack from
524 * which the object may be accessed (though note that we may also rely on
525 * data->oid, too). If "pack" is NULL, then offset is ignored.
526 */
527 static void batch_object_write(const char *obj_name,
528 struct strbuf *scratch,
529 struct batch_options *opt,
530 struct expand_data *data,
531 struct packed_git *pack,
532 off_t offset)
533 {
534 if (!data->skip_object_info) {
535 int ret;
536
537 if (use_mailmap ||
538 opt->objects_filter.choice == LOFC_BLOB_NONE ||
539 opt->objects_filter.choice == LOFC_BLOB_LIMIT ||
540 opt->objects_filter.choice == LOFC_OBJECT_TYPE)
541 data->info.typep = &data->type;
542 if (opt->objects_filter.choice == LOFC_BLOB_LIMIT)
543 data->info.sizep = &data->size;
544
545 if (pack)
546 ret = packed_object_info(NULL, pack, offset, &data->info);
547 else
548 ret = odb_read_object_info_extended(the_repository->objects,
549 &data->oid, &data->info,
550 OBJECT_INFO_LOOKUP_REPLACE);
551 if (ret < 0) {
552 if (data->mode == S_IFGITLINK)
553 report_object_status(opt, NULL, &data->oid, "submodule");
554 else
555 report_object_status(opt, obj_name, &data->oid, "missing");
556 return;
557 }
558
559 switch (opt->objects_filter.choice) {
560 case LOFC_DISABLED:
561 break;
562 case LOFC_BLOB_NONE:
563 if (data->type == OBJ_BLOB) {
564 if (!opt->all_objects)
565 report_object_status(opt, obj_name,
566 &data->oid, "excluded");
567 return;
568 }
569 break;
570 case LOFC_BLOB_LIMIT:
571 if (data->type == OBJ_BLOB &&
572 data->size >= opt->objects_filter.blob_limit_value) {
573 if (!opt->all_objects)
574 report_object_status(opt, obj_name,
575 &data->oid, "excluded");
576 return;
577 }
578 break;
579 case LOFC_OBJECT_TYPE:
580 if (data->type != opt->objects_filter.object_type) {
581 if (!opt->all_objects)
582 report_object_status(opt, obj_name,
583 &data->oid, "excluded");
584 return;
585 }
586 break;
587 default:
588 BUG("unsupported objects filter");
589 }
590
591 if (use_mailmap && (data->type == OBJ_COMMIT || data->type == OBJ_TAG)) {
592 char *buf = NULL;
593
594 buf = odb_read_object(the_repository->objects, &data->oid,
595 &data->type, &data->size);
596 if (!buf)
597 die(_("unable to read %s"), oid_to_hex(&data->oid));
598 buf = replace_idents_using_mailmap(buf, &data->size);
599
600 free(buf);
601 }
602 }
603
604 strbuf_reset(scratch);
605
606 if (!opt->format) {
607 print_default_format(scratch, data, opt);
608 } else {
609 expand_format(scratch, opt->format, data);
610 strbuf_addch(scratch, opt->output_delim);
611 }
612
613 batch_write(opt, scratch->buf, scratch->len);
614
615 if (opt->batch_mode == BATCH_MODE_CONTENTS) {
616 print_object_or_die(opt, data);
617 batch_write(opt, &opt->output_delim, 1);
618 }
619 }
620
621 static void batch_one_object(const char *obj_name,
622 struct strbuf *scratch,
623 struct batch_options *opt,
624 struct expand_data *data)
625 {
626 struct object_context ctx = {0};
627 int flags =
628 GET_OID_HASH_ANY |
629 (opt->follow_symlinks ? GET_OID_FOLLOW_SYMLINKS : 0);
630 enum get_oid_result result;
631
632 result = get_oid_with_context(the_repository, obj_name,
633 flags, &data->oid, &ctx);
634 if (result != FOUND) {
635 switch (result) {
636 case MISSING_OBJECT:
637 report_object_status(opt, obj_name, &data->oid, "missing");
638 break;
639 case SHORT_NAME_AMBIGUOUS:
640 report_object_status(opt, obj_name, &data->oid, "ambiguous");
641 break;
642 case DANGLING_SYMLINK:
643 printf("dangling %"PRIuMAX"%c%s%c",
644 (uintmax_t)strlen(obj_name),
645 opt->output_delim, obj_name, opt->output_delim);
646 break;
647 case SYMLINK_LOOP:
648 printf("loop %"PRIuMAX"%c%s%c",
649 (uintmax_t)strlen(obj_name),
650 opt->output_delim, obj_name, opt->output_delim);
651 break;
652 case NOT_DIR:
653 printf("notdir %"PRIuMAX"%c%s%c",
654 (uintmax_t)strlen(obj_name),
655 opt->output_delim, obj_name, opt->output_delim);
656 break;
657 default:
658 BUG("unknown get_sha1_with_context result %d\n",
659 result);
660 break;
661 }
662 fflush(stdout);
663
664 goto out;
665 }
666
667 if (ctx.mode == 0) {
668 printf("symlink %"PRIuMAX"%c%s%c",
669 (uintmax_t)ctx.symlink_path.len,
670 opt->output_delim, ctx.symlink_path.buf, opt->output_delim);
671 fflush(stdout);
672 goto out;
673 }
674
675 data->mode = ctx.mode;
676 batch_object_write(obj_name, scratch, opt, data, NULL, 0);
677
678 out:
679 object_context_release(&ctx);
680 }
681
682 static int get_remote_info(int argc,
683 const char **argv,
684 struct object_info **remote_object_info,
685 struct oid_array *object_info_oids,
686 struct string_list *object_info_options)
687 {
688 int retval = 0;
689 struct remote *remote = NULL;
690 struct object_id oid;
691 struct transport *gtransport;
692
693 remote = remote_get(argv[0]);
694 if (!remote)
695 die(_("must supply valid remote when using remote-object-info"));
696
697 oid_array_clear(object_info_oids);
698 for (size_t i = 1; i < argc; i++) {
699 if (get_oid_hex(argv[i], &oid)) {
700 size_t len = strlen(argv[i]);
701
702 if (len < the_hash_algo->hexsz && len >= 4) {
703 size_t j;
704 for (j = 0; j < len; j++)
705 if (!isxdigit(argv[i][j]))
706 break;
707 if (j == len)
708 die(_("remote-object-info does not support "
709 "short oids, %d characters required"),
710 (int)the_hash_algo->hexsz);
711 }
712 die(_("not a valid object name '%s'"), argv[i]);
713 }
714 oid_array_append(object_info_oids, &oid);
715 }
716
717 if (!object_info_oids->nr)
718 die(_("remote-object-info requires objects"));
719
720 gtransport = transport_get(remote, NULL);
721
722 if (!gtransport->smart_options) {
723 retval = -1;
724 goto cleanup;
725 }
726
727 CALLOC_ARRAY(*remote_object_info, object_info_oids->nr);
728 gtransport->smart_options->object_info_oids = object_info_oids;
729
730 gtransport->smart_options->object_info_options = object_info_options;
731 gtransport->smart_options->object_info_data = *remote_object_info;
732 retval = transport_fetch_object_info(gtransport);
733 cleanup:
734 transport_disconnect(gtransport);
735 return retval;
736 }
737
738 struct object_cb_data {
739 struct batch_options *opt;
740 struct expand_data *expand;
741 struct oidset *seen;
742 struct strbuf *scratch;
743 };
744
745 static int batch_object_cb(const struct object_id *oid, void *vdata)
746 {
747 struct object_cb_data *data = vdata;
748 oidcpy(&data->expand->oid, oid);
749 batch_object_write(NULL, data->scratch, data->opt, data->expand,
750 NULL, 0);
751 return 0;
752 }
753
754 static int collect_object(const struct object_id *oid,
755 struct packed_git *pack UNUSED,
756 off_t offset UNUSED,
757 void *data)
758 {
759 oid_array_append(data, oid);
760 return 0;
761 }
762
763 static int batch_unordered_object(const struct object_id *oid,
764 struct packed_git *pack,
765 off_t offset,
766 void *vdata)
767 {
768 struct object_cb_data *data = vdata;
769
770 if (oidset_insert(data->seen, oid))
771 return 0;
772
773 oidcpy(&data->expand->oid, oid);
774 batch_object_write(NULL, data->scratch, data->opt, data->expand,
775 pack, offset);
776 return 0;
777 }
778
779 typedef void (*parse_cmd_fn_t)(struct batch_options *, const char *,
780 struct strbuf *, struct expand_data *);
781
782 struct queued_cmd {
783 parse_cmd_fn_t fn;
784 char *line;
785 };
786
787 static void parse_cmd_contents(struct batch_options *opt,
788 const char *line,
789 struct strbuf *output,
790 struct expand_data *data)
791 {
792 opt->batch_mode = BATCH_MODE_CONTENTS;
793 batch_one_object(line, output, opt, data);
794 }
795
796 static void parse_cmd_info(struct batch_options *opt,
797 const char *line,
798 struct strbuf *output,
799 struct expand_data *data)
800 {
801 opt->batch_mode = BATCH_MODE_INFO;
802 batch_one_object(line, output, opt, data);
803 }
804
805 static void parse_cmd_mailmap(struct batch_options *opt UNUSED,
806 const char *line,
807 struct strbuf *output UNUSED,
808 struct expand_data *data UNUSED)
809 {
810 use_mailmap = git_parse_maybe_bool(line);
811
812 if (use_mailmap < 0)
813 die(_("mailmap: invalid boolean '%s'"), line);
814
815 if (use_mailmap)
816 load_mailmap();
817 }
818
819 struct protocol_placeholder_entry {
820 const char *option;
821 const char *atom;
822 };
823
824 static const struct protocol_placeholder_entry remote_atom_map[] = {
825 {"size", "objectsize"},
826 {"type", "objecttype"},
827 /*
828 * Add new protocol options here. Even if the server doesn't support
829 * them the allow_list will drop them if the server doesn't advertise
830 * them.
831 */
832 };
833
834 static void parse_cmd_remote_object_info(struct batch_options *opt,
835 const char *line, struct strbuf *output,
836 struct expand_data *data)
837 {
838 int count;
839 const char **argv;
840 char *line_to_split;
841 struct object_info *remote_object_info = NULL;
842 struct oid_array object_info_oids = OID_ARRAY_INIT;
843 struct string_list object_info_options = STRING_LIST_INIT_NODUP;
844 const char *saved_format = opt->format;
845
846 if (strlen(line) >= MAX_REMOTE_OBJ_INFO_LINE)
847 die(_("remote-object-info command too long"));
848 /*
849 * TODO: Use the default format once %(objecttype) is supported.
850 */
851 if (!opt->format)
852 opt->format = "%(objectname) %(objectsize)";
853
854 line_to_split = xstrdup(line);
855 count = split_cmdline(line_to_split, &argv);
856 if (count < 0)
857 die(_("remote-object-info: failed to parse command line: %s"),
858 split_cmdline_strerror(count));
859 if (count - 1 > MAX_ALLOWED_OBJ_LIMIT)
860 die(_("remote-object-info supports at most %d objects"),
861 MAX_ALLOWED_OBJ_LIMIT);
862
863 if (data->info.sizep)
864 string_list_append(&object_info_options, "size");
865 if (data->info.typep)
866 string_list_append(&object_info_options, "type");
867
868 if (get_remote_info(count, argv, &remote_object_info,
869 &object_info_oids, &object_info_options))
870 die(_("failed to get object info from the remote: %s"), argv[0]);
871
872 string_list_clear(&data->remote_allowed_atoms, 0);
873 string_list_append(&data->remote_allowed_atoms, "objectname");
874 for (size_t i = 0; i < ARRAY_SIZE(remote_atom_map); i++)
875 if (unsorted_string_list_has_string(&object_info_options, remote_atom_map[i].option))
876 string_list_append(&data->remote_allowed_atoms,
877 remote_atom_map[i].atom);
878
879 data->skip_object_info = 1;
880 for (size_t i = 0; i < object_info_oids.nr; i++) {
881 data->oid = object_info_oids.oid[i];
882
883 if (remote_object_info[i].unrecognized) {
884 report_object_status(opt, oid_to_hex(&data->oid),
885 &data->oid, "missing");
886 continue;
887 }
888
889 /*
890 * When reaching here, it means remote-object-info can retrieve
891 * information from server without downloading them.
892 */
893 if (remote_object_info[i].sizep) {
894 data->size = *remote_object_info[i].sizep;
895 }
896
897 if (remote_object_info[i].typep) {
898 data->type = *remote_object_info[i].typep;
899 }
900
901 opt->batch_mode = BATCH_MODE_INFO;
902 data->is_remote = 1;
903 batch_object_write(argv[i + 1], output, opt, data, NULL, 0);
904 data->is_remote = 0;
905 }
906 data->skip_object_info = 0;
907 opt->format = saved_format;
908
909 for (size_t i = 0; i < object_info_oids.nr; i++)
910 free_object_info_contents(&remote_object_info[i]);
911 string_list_clear(&object_info_options, 0);
912 free(line_to_split);
913 free(argv);
914 free(remote_object_info);
915 oid_array_clear(&object_info_oids);
916 }
917
918 static void dispatch_calls(struct batch_options *opt,
919 struct strbuf *output,
920 struct expand_data *data,
921 struct queued_cmd *cmd,
922 size_t nr)
923 {
924 if (!opt->buffer_output)
925 die(_("flush is only for --buffer mode"));
926
927 for (size_t i = 0; i < nr; i++)
928 cmd[i].fn(opt, cmd[i].line, output, data);
929
930 fflush(stdout);
931 }
932
933 static void free_cmds(struct queued_cmd *cmd, size_t *nr)
934 {
935 for (size_t i = 0; i < *nr; i++)
936 FREE_AND_NULL(cmd[i].line);
937
938 *nr = 0;
939 }
940
941
942 static const struct parse_cmd {
943 const char *name;
944 parse_cmd_fn_t fn;
945 unsigned takes_args;
946 } commands[] = {
947 { "contents", parse_cmd_contents, 1 },
948 { "flush", NULL, 0 },
949 { "info", parse_cmd_info, 1 },
950 { "mailmap", parse_cmd_mailmap, 1 },
951 { "remote-object-info", parse_cmd_remote_object_info, 1 },
952 };
953
954 static void batch_objects_command(struct batch_options *opt,
955 struct strbuf *output,
956 struct expand_data *data)
957 {
958 struct strbuf input = STRBUF_INIT;
959 struct queued_cmd *queued_cmd = NULL;
960 size_t alloc = 0, nr = 0;
961
962 while (strbuf_getdelim_strip_crlf(&input, stdin, opt->input_delim) != EOF) {
963 const struct parse_cmd *cmd = NULL;
964 const char *p = NULL, *cmd_end;
965 struct queued_cmd call = {0};
966
967 if (!input.len)
968 die(_("empty command in input"));
969 if (isspace(*input.buf))
970 die(_("whitespace before command: '%s'"), input.buf);
971
972 for (size_t i = 0; i < ARRAY_SIZE(commands); i++) {
973 if (!skip_prefix(input.buf, commands[i].name, &cmd_end))
974 continue;
975
976 cmd = &commands[i];
977 if (cmd->takes_args) {
978 if (*cmd_end != ' ')
979 die(_("%s requires arguments"),
980 commands[i].name);
981
982 p = cmd_end + 1;
983 } else if (*cmd_end) {
984 die(_("%s takes no arguments"),
985 commands[i].name);
986 }
987
988 break;
989 }
990
991 if (!cmd)
992 die(_("unknown command: '%s'"), input.buf);
993
994 if (!strcmp(cmd->name, "flush")) {
995 dispatch_calls(opt, output, data, queued_cmd, nr);
996 free_cmds(queued_cmd, &nr);
997 } else if (!opt->buffer_output) {
998 cmd->fn(opt, p, output, data);
999 } else {
1000 ALLOC_GROW(queued_cmd, nr + 1, alloc);
1001 call.fn = cmd->fn;
1002 call.line = xstrdup_or_null(p);
1003 queued_cmd[nr++] = call;
1004 }
1005 }
1006
1007 if (opt->buffer_output &&
1008 nr &&
1009 !git_env_bool("GIT_TEST_CAT_FILE_NO_FLUSH_ON_EXIT", 0)) {
1010 dispatch_calls(opt, output, data, queued_cmd, nr);
1011 free_cmds(queued_cmd, &nr);
1012 }
1013
1014 free_cmds(queued_cmd, &nr);
1015 free(queued_cmd);
1016 strbuf_release(&input);
1017 }
1018
1019 #define DEFAULT_FORMAT "%(objectname) %(objecttype) %(objectsize)"
1020
1021 typedef int (*for_each_object_fn)(const struct object_id *oid, struct packed_git *pack,
1022 off_t offset, void *data);
1023
1024 struct for_each_object_payload {
1025 for_each_object_fn callback;
1026 void *payload;
1027 };
1028
1029 static int batch_one_object_oi(const struct object_id *oid,
1030 struct object_info *oi,
1031 void *_payload)
1032 {
1033 struct for_each_object_payload *payload = _payload;
1034 if (oi && oi->source_infop->source->type == ODB_SOURCE_PACKED)
1035 return payload->callback(oid, oi->source_infop->u.packed.pack,
1036 oi->source_infop->u.packed.offset,
1037 payload->payload);
1038 return payload->callback(oid, NULL, 0, payload->payload);
1039 }
1040
1041 static void batch_each_object(struct batch_options *opt,
1042 for_each_object_fn callback,
1043 unsigned flags,
1044 void *_payload)
1045 {
1046 struct for_each_object_payload payload = {
1047 .callback = callback,
1048 .payload = _payload,
1049 };
1050 struct odb_source_info source_info;
1051 struct object_info oi = {
1052 .source_infop = &source_info,
1053 };
1054 struct odb_for_each_object_options opts = {
1055 .flags = flags,
1056 .filter = &opt->objects_filter,
1057 };
1058
1059 odb_for_each_object_ext(the_repository->objects, &oi,
1060 batch_one_object_oi, &payload, &opts);
1061 }
1062
1063 static int batch_objects(struct batch_options *opt)
1064 {
1065 struct strbuf input = STRBUF_INIT;
1066 struct strbuf output = STRBUF_INIT;
1067 struct expand_data data = EXPAND_DATA_INIT;
1068 struct repo_config_values *cfg = repo_config_values(the_repository);
1069 int save_warning;
1070 int retval = 0;
1071
1072 /*
1073 * Expand once with our special mark_query flag, which will prime the
1074 * object_info to be handed to odb_read_object_info_extended for each
1075 * object.
1076 */
1077 data.mark_query = 1;
1078 expand_format(&output,
1079 opt->format ? opt->format : DEFAULT_FORMAT,
1080 &data);
1081 data.mark_query = 0;
1082 strbuf_release(&output);
1083 if (opt->transform_mode)
1084 data.split_on_whitespace = 1;
1085
1086 if (opt->format && !strcmp(opt->format, DEFAULT_FORMAT))
1087 opt->format = NULL;
1088 /*
1089 * If we are printing out the object, then always fill in the type,
1090 * since we will want to decide whether or not to stream.
1091 */
1092 if (opt->batch_mode == BATCH_MODE_CONTENTS)
1093 data.info.typep = &data.type;
1094
1095 if (opt->all_objects) {
1096 struct object_cb_data cb;
1097 struct object_info empty = OBJECT_INFO_INIT;
1098
1099 if (!memcmp(&data.info, &empty, sizeof(empty)) &&
1100 opt->objects_filter.choice == LOFC_DISABLED)
1101 data.skip_object_info = 1;
1102
1103 if (repo_has_promisor_remote(the_repository))
1104 warning("This repository uses promisor remotes. Some objects may not be loaded.");
1105
1106 disable_replace_refs();
1107
1108 cb.opt = opt;
1109 cb.expand = &data;
1110 cb.scratch = &output;
1111
1112 if (opt->unordered) {
1113 struct oidset seen = OIDSET_INIT;
1114
1115 cb.seen = &seen;
1116
1117 batch_each_object(opt, batch_unordered_object,
1118 ODB_FOR_EACH_OBJECT_PACK_ORDER, &cb);
1119
1120 oidset_clear(&seen);
1121 } else {
1122 struct oid_array sa = OID_ARRAY_INIT;
1123
1124 batch_each_object(opt, collect_object, 0, &sa);
1125 oid_array_for_each_unique(&sa, batch_object_cb, &cb);
1126
1127 oid_array_clear(&sa);
1128 }
1129
1130 strbuf_release(&output);
1131 return 0;
1132 }
1133
1134 /*
1135 * We are going to call get_sha1 on a potentially very large number of
1136 * objects. In most large cases, these will be actual object sha1s. The
1137 * cost to double-check that each one is not also a ref (just so we can
1138 * warn) ends up dwarfing the actual cost of the object lookups
1139 * themselves. We can work around it by just turning off the warning.
1140 */
1141 save_warning = cfg->warn_on_object_refname_ambiguity;
1142 cfg->warn_on_object_refname_ambiguity = 0;
1143
1144 if (opt->batch_mode == BATCH_MODE_QUEUE_AND_DISPATCH) {
1145 batch_objects_command(opt, &output, &data);
1146 goto cleanup;
1147 }
1148
1149 while (strbuf_getdelim_strip_crlf(&input, stdin, opt->input_delim) != EOF) {
1150 if (data.split_on_whitespace) {
1151 /*
1152 * Split at first whitespace, tying off the beginning
1153 * of the string and saving the remainder (or NULL) in
1154 * data.rest.
1155 */
1156 char *p = strpbrk(input.buf, " \t");
1157 if (p) {
1158 while (*p && strchr(" \t", *p))
1159 *p++ = '\0';
1160 }
1161 data.rest = p;
1162 }
1163
1164 batch_one_object(input.buf, &output, opt, &data);
1165 }
1166
1167 cleanup:
1168 strbuf_release(&input);
1169 strbuf_release(&output);
1170 string_list_clear(&data.remote_allowed_atoms, 0);
1171 cfg->warn_on_object_refname_ambiguity = save_warning;
1172 return retval;
1173 }
1174
1175 static int git_cat_file_config(const char *var, const char *value,
1176 const struct config_context *ctx, void *cb)
1177 {
1178 if (userdiff_config(var, value) < 0)
1179 return -1;
1180
1181 return git_default_config(var, value, ctx, cb);
1182 }
1183
1184 static int batch_option_callback(const struct option *opt,
1185 const char *arg,
1186 int unset)
1187 {
1188 struct batch_options *bo = opt->value;
1189
1190 BUG_ON_OPT_NEG(unset);
1191
1192 if (bo->enabled) {
1193 return error(_("only one batch option may be specified"));
1194 }
1195
1196 bo->enabled = 1;
1197
1198 if (!strcmp(opt->long_name, "batch"))
1199 bo->batch_mode = BATCH_MODE_CONTENTS;
1200 else if (!strcmp(opt->long_name, "batch-check"))
1201 bo->batch_mode = BATCH_MODE_INFO;
1202 else if (!strcmp(opt->long_name, "batch-command"))
1203 bo->batch_mode = BATCH_MODE_QUEUE_AND_DISPATCH;
1204 else
1205 BUG("%s given to batch-option-callback", opt->long_name);
1206
1207 bo->format = arg;
1208
1209 return 0;
1210 }
1211
1212 int cmd_cat_file(int argc,
1213 const char **argv,
1214 const char *prefix,
1215 struct repository *repo UNUSED)
1216 {
1217 int opt = 0;
1218 int opt_cw = 0;
1219 int opt_epts = 0;
1220 const char *exp_type = NULL, *obj_name = NULL;
1221 struct batch_options batch = {
1222 .objects_filter = LIST_OBJECTS_FILTER_INIT,
1223 };
1224 int unknown_type = 0;
1225 int input_nul_terminated = 0;
1226 int nul_terminated = 0;
1227 int ret;
1228
1229 const char * const builtin_catfile_usage[] = {
1230 N_("git cat-file <type> <object>"),
1231 N_("git cat-file (-e | -p | -t | -s) <object>"),
1232 N_("git cat-file (--textconv | --filters)\n"
1233 " [<rev>:<path|tree-ish> | --path=<path|tree-ish> <rev>]"),
1234 N_("git cat-file (--batch | --batch-check | --batch-command) [--batch-all-objects]\n"
1235 " [--buffer] [--follow-symlinks] [--unordered]\n"
1236 " [--textconv | --filters] [-Z]"),
1237 NULL
1238 };
1239 const struct option options[] = {
1240 /* Simple queries */
1241 OPT_GROUP(N_("Check object existence or emit object contents")),
1242 OPT_CMDMODE('e', NULL, &opt,
1243 N_("check if <object> exists"), 'e'),
1244 OPT_CMDMODE('p', NULL, &opt, N_("pretty-print <object> content"), 'p'),
1245
1246 OPT_GROUP(N_("Emit [broken] object attributes")),
1247 OPT_CMDMODE('t', NULL, &opt, N_("show object type (one of 'blob', 'tree', 'commit', 'tag', ...)"), 't'),
1248 OPT_CMDMODE('s', NULL, &opt, N_("show object size"), 's'),
1249 OPT_HIDDEN_BOOL(0, "allow-unknown-type", &unknown_type,
1250 N_("historical option -- no-op")),
1251 OPT_BOOL(0, "use-mailmap", &use_mailmap, N_("use mail map file")),
1252 OPT_ALIAS(0, "mailmap", "use-mailmap"),
1253 /* Batch mode */
1254 OPT_GROUP(N_("Batch objects requested on stdin (or --batch-all-objects)")),
1255 OPT_CALLBACK_F(0, "batch", &batch, N_("format"),
1256 N_("show full <object> or <rev> contents"),
1257 PARSE_OPT_OPTARG | PARSE_OPT_NONEG,
1258 batch_option_callback),
1259 OPT_CALLBACK_F(0, "batch-check", &batch, N_("format"),
1260 N_("like --batch, but don't emit <contents>"),
1261 PARSE_OPT_OPTARG | PARSE_OPT_NONEG,
1262 batch_option_callback),
1263 OPT_BOOL_F('z', NULL, &input_nul_terminated, N_("stdin is NUL-terminated"),
1264 PARSE_OPT_HIDDEN),
1265 OPT_BOOL('Z', NULL, &nul_terminated, N_("stdin and stdout is NUL-terminated")),
1266 OPT_CALLBACK_F(0, "batch-command", &batch, N_("format"),
1267 N_("read commands from stdin"),
1268 PARSE_OPT_OPTARG | PARSE_OPT_NONEG,
1269 batch_option_callback),
1270 OPT_CMDMODE(0, "batch-all-objects", &opt,
1271 N_("with --batch[-check]: ignores stdin, batches all known objects"), 'b'),
1272 /* Batch-specific options */
1273 OPT_GROUP(N_("Change or optimize batch output")),
1274 OPT_BOOL(0, "buffer", &batch.buffer_output, N_("buffer --batch output")),
1275 OPT_BOOL(0, "follow-symlinks", &batch.follow_symlinks,
1276 N_("follow in-tree symlinks")),
1277 OPT_BOOL(0, "unordered", &batch.unordered,
1278 N_("do not order objects before emitting them")),
1279 /* Textconv options, stand-ole*/
1280 OPT_GROUP(N_("Emit object (blob or tree) with conversion or filter (stand-alone, or with batch)")),
1281 OPT_CMDMODE(0, "textconv", &opt,
1282 N_("run textconv on object's content"), 'c'),
1283 OPT_CMDMODE(0, "filters", &opt,
1284 N_("run filters on object's content"), 'w'),
1285 OPT_STRING(0, "path", &force_path, N_("blob|tree"),
1286 N_("use a <path> for (--textconv | --filters); Not with 'batch'")),
1287 OPT_PARSE_LIST_OBJECTS_FILTER(&batch.objects_filter),
1288 OPT_END()
1289 };
1290
1291 repo_config(the_repository, git_cat_file_config, NULL);
1292
1293 batch.buffer_output = -1;
1294
1295 argc = parse_options(argc, argv, prefix, options, builtin_catfile_usage, 0);
1296 opt_cw = (opt == 'c' || opt == 'w');
1297 opt_epts = (opt == 'e' || opt == 'p' || opt == 't' || opt == 's');
1298
1299 if (use_mailmap)
1300 load_mailmap();
1301
1302 switch (batch.objects_filter.choice) {
1303 case LOFC_DISABLED:
1304 break;
1305 case LOFC_BLOB_NONE:
1306 case LOFC_BLOB_LIMIT:
1307 case LOFC_OBJECT_TYPE:
1308 if (!batch.enabled)
1309 usage(_("objects filter only supported in batch mode"));
1310 break;
1311 default:
1312 usagef(_("objects filter not supported: '%s'"),
1313 list_object_filter_config_name(batch.objects_filter.choice));
1314 }
1315
1316 /* --batch-all-objects? */
1317 if (opt == 'b')
1318 batch.all_objects = 1;
1319
1320 /* Option compatibility */
1321 if (force_path && !opt_cw)
1322 usage_msg_optf(_("'%s=<%s>' needs '%s' or '%s'"),
1323 builtin_catfile_usage, options,
1324 "--path", _("path|tree-ish"), "--filters",
1325 "--textconv");
1326
1327 /* Option compatibility with batch mode */
1328 if (batch.enabled)
1329 ;
1330 else if (batch.follow_symlinks)
1331 usage_msg_optf(_("'%s' requires a batch mode"), builtin_catfile_usage,
1332 options, "--follow-symlinks");
1333 else if (batch.buffer_output >= 0)
1334 usage_msg_optf(_("'%s' requires a batch mode"), builtin_catfile_usage,
1335 options, "--buffer");
1336 else if (batch.all_objects)
1337 usage_msg_optf(_("'%s' requires a batch mode"), builtin_catfile_usage,
1338 options, "--batch-all-objects");
1339 else if (input_nul_terminated)
1340 usage_msg_optf(_("'%s' requires a batch mode"), builtin_catfile_usage,
1341 options, "-z");
1342 else if (nul_terminated)
1343 usage_msg_optf(_("'%s' requires a batch mode"), builtin_catfile_usage,
1344 options, "-Z");
1345
1346 batch.input_delim = batch.output_delim = '\n';
1347 if (input_nul_terminated)
1348 batch.input_delim = '\0';
1349 if (nul_terminated)
1350 batch.input_delim = batch.output_delim = '\0';
1351
1352 /* Batch defaults */
1353 if (batch.buffer_output < 0)
1354 batch.buffer_output = batch.all_objects;
1355
1356 prepare_repo_settings(the_repository);
1357 the_repository->settings.command_requires_full_index = 0;
1358
1359 /* Return early if we're in batch mode? */
1360 if (batch.enabled) {
1361 if (opt_cw)
1362 batch.transform_mode = opt;
1363 else if (opt && opt != 'b')
1364 usage_msg_optf(_("'-%c' is incompatible with batch mode"),
1365 builtin_catfile_usage, options, opt);
1366 else if (argc)
1367 usage_msg_opt(_("batch modes take no arguments"),
1368 builtin_catfile_usage, options);
1369
1370 ret = batch_objects(&batch);
1371 goto out;
1372 }
1373
1374 if (opt) {
1375 if (!argc && opt == 'c')
1376 usage_msg_optf(_("<rev> required with '%s'"),
1377 builtin_catfile_usage, options,
1378 "--textconv");
1379 else if (!argc && opt == 'w')
1380 usage_msg_optf(_("<rev> required with '%s'"),
1381 builtin_catfile_usage, options,
1382 "--filters");
1383 else if (!argc && opt_epts)
1384 usage_msg_optf(_("<object> required with '-%c'"),
1385 builtin_catfile_usage, options, opt);
1386 else if (argc == 1)
1387 obj_name = argv[0];
1388 else
1389 usage_msg_opt(_("too many arguments"), builtin_catfile_usage,
1390 options);
1391 } else if (!argc) {
1392 usage_with_options(builtin_catfile_usage, options);
1393 } else if (argc != 2) {
1394 usage_msg_optf(_("only two arguments allowed in <type> <object> mode, not %d"),
1395 builtin_catfile_usage, options, argc);
1396 } else if (argc) {
1397 exp_type = argv[0];
1398 obj_name = argv[1];
1399 }
1400
1401 ret = cat_one_file(opt, exp_type, obj_name);
1402
1403 out:
1404 list_objects_filter_release(&batch.objects_filter);
1405 return ret;
1406 }