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 enum object_type *saved_typep = data->info.typep;
793 data->info.typep = &data->type;
794 opt->batch_mode = BATCH_MODE_CONTENTS;
795 batch_one_object(line, output, opt, data);
796 data->info.typep = saved_typep;
797 }
798
799 static void parse_cmd_info(struct batch_options *opt,
800 const char *line,
801 struct strbuf *output,
802 struct expand_data *data)
803 {
804 opt->batch_mode = BATCH_MODE_INFO;
805 batch_one_object(line, output, opt, data);
806 }
807
808 static void parse_cmd_mailmap(struct batch_options *opt UNUSED,
809 const char *line,
810 struct strbuf *output UNUSED,
811 struct expand_data *data UNUSED)
812 {
813 use_mailmap = git_parse_maybe_bool(line);
814
815 if (use_mailmap < 0)
816 die(_("mailmap: invalid boolean '%s'"), line);
817
818 if (use_mailmap)
819 load_mailmap();
820 }
821
822 struct protocol_placeholder_entry {
823 const char *option;
824 const char *atom;
825 };
826
827 static const struct protocol_placeholder_entry remote_atom_map[] = {
828 {"size", "objectsize"},
829 {"type", "objecttype"},
830 /*
831 * Add new protocol options here. Even if the server doesn't support
832 * them the allow_list will drop them if the server doesn't advertise
833 * them.
834 */
835 };
836
837 static void parse_cmd_remote_object_info(struct batch_options *opt,
838 const char *line, struct strbuf *output,
839 struct expand_data *data)
840 {
841 int count;
842 const char **argv;
843 char *line_to_split;
844 struct object_info *remote_object_info = NULL;
845 struct oid_array object_info_oids = OID_ARRAY_INIT;
846 struct string_list object_info_options = STRING_LIST_INIT_NODUP;
847 const char *saved_format = opt->format;
848
849 if (strlen(line) >= MAX_REMOTE_OBJ_INFO_LINE)
850 die(_("remote-object-info command too long"));
851 /*
852 * TODO: Use the default format once %(objecttype) is supported.
853 */
854 if (!opt->format)
855 opt->format = "%(objectname) %(objectsize)";
856
857 line_to_split = xstrdup(line);
858 count = split_cmdline(line_to_split, &argv);
859 if (count < 0)
860 die(_("remote-object-info: failed to parse command line: %s"),
861 split_cmdline_strerror(count));
862 if (count - 1 > MAX_ALLOWED_OBJ_LIMIT)
863 die(_("remote-object-info supports at most %d objects"),
864 MAX_ALLOWED_OBJ_LIMIT);
865
866 if (data->info.sizep)
867 string_list_append(&object_info_options, "size");
868 if (data->info.typep)
869 string_list_append(&object_info_options, "type");
870
871 if (get_remote_info(count, argv, &remote_object_info,
872 &object_info_oids, &object_info_options))
873 die(_("failed to get object info from the remote: %s"), argv[0]);
874
875 string_list_clear(&data->remote_allowed_atoms, 0);
876 string_list_append(&data->remote_allowed_atoms, "objectname");
877 for (size_t i = 0; i < ARRAY_SIZE(remote_atom_map); i++)
878 if (unsorted_string_list_has_string(&object_info_options, remote_atom_map[i].option))
879 string_list_append(&data->remote_allowed_atoms,
880 remote_atom_map[i].atom);
881
882 data->skip_object_info = 1;
883 for (size_t i = 0; i < object_info_oids.nr; i++) {
884 data->oid = object_info_oids.oid[i];
885
886 if (remote_object_info[i].unrecognized) {
887 report_object_status(opt, oid_to_hex(&data->oid),
888 &data->oid, "missing");
889 continue;
890 }
891
892 /*
893 * When reaching here, it means remote-object-info can retrieve
894 * information from server without downloading them.
895 */
896 if (remote_object_info[i].sizep) {
897 data->size = *remote_object_info[i].sizep;
898 }
899
900 if (remote_object_info[i].typep) {
901 data->type = *remote_object_info[i].typep;
902 }
903
904 opt->batch_mode = BATCH_MODE_INFO;
905 data->is_remote = 1;
906 batch_object_write(argv[i + 1], output, opt, data, NULL, 0);
907 data->is_remote = 0;
908 }
909 data->skip_object_info = 0;
910 opt->format = saved_format;
911
912 for (size_t i = 0; i < object_info_oids.nr; i++)
913 free_object_info_contents(&remote_object_info[i]);
914 string_list_clear(&object_info_options, 0);
915 free(line_to_split);
916 free(argv);
917 free(remote_object_info);
918 oid_array_clear(&object_info_oids);
919 }
920
921 static void dispatch_calls(struct batch_options *opt,
922 struct strbuf *output,
923 struct expand_data *data,
924 struct queued_cmd *cmd,
925 size_t nr)
926 {
927 if (!opt->buffer_output)
928 die(_("flush is only for --buffer mode"));
929
930 for (size_t i = 0; i < nr; i++)
931 cmd[i].fn(opt, cmd[i].line, output, data);
932
933 fflush(stdout);
934 }
935
936 static void free_cmds(struct queued_cmd *cmd, size_t *nr)
937 {
938 for (size_t i = 0; i < *nr; i++)
939 FREE_AND_NULL(cmd[i].line);
940
941 *nr = 0;
942 }
943
944
945 static const struct parse_cmd {
946 const char *name;
947 parse_cmd_fn_t fn;
948 unsigned takes_args;
949 } commands[] = {
950 { "contents", parse_cmd_contents, 1 },
951 { "flush", NULL, 0 },
952 { "info", parse_cmd_info, 1 },
953 { "mailmap", parse_cmd_mailmap, 1 },
954 { "remote-object-info", parse_cmd_remote_object_info, 1 },
955 };
956
957 static void batch_objects_command(struct batch_options *opt,
958 struct strbuf *output,
959 struct expand_data *data)
960 {
961 struct strbuf input = STRBUF_INIT;
962 struct queued_cmd *queued_cmd = NULL;
963 size_t alloc = 0, nr = 0;
964
965 while (strbuf_getdelim_strip_crlf(&input, stdin, opt->input_delim) != EOF) {
966 const struct parse_cmd *cmd = NULL;
967 const char *p = NULL, *cmd_end;
968 struct queued_cmd call = {0};
969
970 if (!input.len)
971 die(_("empty command in input"));
972 if (isspace(*input.buf))
973 die(_("whitespace before command: '%s'"), input.buf);
974
975 for (size_t i = 0; i < ARRAY_SIZE(commands); i++) {
976 if (!skip_prefix(input.buf, commands[i].name, &cmd_end))
977 continue;
978
979 cmd = &commands[i];
980 if (cmd->takes_args) {
981 if (*cmd_end != ' ')
982 die(_("%s requires arguments"),
983 commands[i].name);
984
985 p = cmd_end + 1;
986 } else if (*cmd_end) {
987 die(_("%s takes no arguments"),
988 commands[i].name);
989 }
990
991 break;
992 }
993
994 if (!cmd)
995 die(_("unknown command: '%s'"), input.buf);
996
997 if (!strcmp(cmd->name, "flush")) {
998 dispatch_calls(opt, output, data, queued_cmd, nr);
999 free_cmds(queued_cmd, &nr);
1000 } else if (!opt->buffer_output) {
1001 cmd->fn(opt, p, output, data);
1002 } else {
1003 ALLOC_GROW(queued_cmd, nr + 1, alloc);
1004 call.fn = cmd->fn;
1005 call.line = xstrdup_or_null(p);
1006 queued_cmd[nr++] = call;
1007 }
1008 }
1009
1010 if (opt->buffer_output &&
1011 nr &&
1012 !git_env_bool("GIT_TEST_CAT_FILE_NO_FLUSH_ON_EXIT", 0)) {
1013 dispatch_calls(opt, output, data, queued_cmd, nr);
1014 free_cmds(queued_cmd, &nr);
1015 }
1016
1017 free_cmds(queued_cmd, &nr);
1018 free(queued_cmd);
1019 strbuf_release(&input);
1020 }
1021
1022 #define DEFAULT_FORMAT "%(objectname) %(objecttype) %(objectsize)"
1023
1024 typedef int (*for_each_object_fn)(const struct object_id *oid, struct packed_git *pack,
1025 off_t offset, void *data);
1026
1027 struct for_each_object_payload {
1028 for_each_object_fn callback;
1029 void *payload;
1030 };
1031
1032 static int batch_one_object_oi(const struct object_id *oid,
1033 struct object_info *oi,
1034 void *_payload)
1035 {
1036 struct for_each_object_payload *payload = _payload;
1037 if (oi && oi->source_infop->source->type == ODB_SOURCE_PACKED)
1038 return payload->callback(oid, oi->source_infop->u.packed.pack,
1039 oi->source_infop->u.packed.offset,
1040 payload->payload);
1041 return payload->callback(oid, NULL, 0, payload->payload);
1042 }
1043
1044 static void batch_each_object(struct batch_options *opt,
1045 for_each_object_fn callback,
1046 unsigned flags,
1047 void *_payload)
1048 {
1049 struct for_each_object_payload payload = {
1050 .callback = callback,
1051 .payload = _payload,
1052 };
1053 struct odb_source_info source_info;
1054 struct object_info oi = {
1055 .source_infop = &source_info,
1056 };
1057 struct odb_for_each_object_options opts = {
1058 .flags = flags,
1059 .filter = &opt->objects_filter,
1060 };
1061
1062 odb_for_each_object_ext(the_repository->objects, &oi,
1063 batch_one_object_oi, &payload, &opts);
1064 }
1065
1066 static int batch_objects(struct batch_options *opt)
1067 {
1068 struct strbuf input = STRBUF_INIT;
1069 struct strbuf output = STRBUF_INIT;
1070 struct expand_data data = EXPAND_DATA_INIT;
1071 struct repo_config_values *cfg = repo_config_values(the_repository);
1072 int save_warning;
1073 int retval = 0;
1074
1075 /*
1076 * Expand once with our special mark_query flag, which will prime the
1077 * object_info to be handed to odb_read_object_info_extended for each
1078 * object.
1079 */
1080 data.mark_query = 1;
1081 expand_format(&output,
1082 opt->format ? opt->format : DEFAULT_FORMAT,
1083 &data);
1084 data.mark_query = 0;
1085 strbuf_release(&output);
1086 if (opt->transform_mode)
1087 data.split_on_whitespace = 1;
1088
1089 if (opt->format && !strcmp(opt->format, DEFAULT_FORMAT))
1090 opt->format = NULL;
1091 /*
1092 * If we are printing out the object, then always fill in the type,
1093 * since we will want to decide whether or not to stream.
1094 */
1095 if (opt->batch_mode == BATCH_MODE_CONTENTS)
1096 data.info.typep = &data.type;
1097
1098 if (opt->all_objects) {
1099 struct object_cb_data cb;
1100 struct object_info empty = OBJECT_INFO_INIT;
1101
1102 if (!memcmp(&data.info, &empty, sizeof(empty)) &&
1103 opt->objects_filter.choice == LOFC_DISABLED)
1104 data.skip_object_info = 1;
1105
1106 if (repo_has_promisor_remote(the_repository))
1107 warning("This repository uses promisor remotes. Some objects may not be loaded.");
1108
1109 disable_replace_refs();
1110
1111 cb.opt = opt;
1112 cb.expand = &data;
1113 cb.scratch = &output;
1114
1115 if (opt->unordered) {
1116 struct oidset seen = OIDSET_INIT;
1117
1118 cb.seen = &seen;
1119
1120 batch_each_object(opt, batch_unordered_object,
1121 ODB_FOR_EACH_OBJECT_PACK_ORDER, &cb);
1122
1123 oidset_clear(&seen);
1124 } else {
1125 struct oid_array sa = OID_ARRAY_INIT;
1126
1127 batch_each_object(opt, collect_object, 0, &sa);
1128 oid_array_for_each_unique(&sa, batch_object_cb, &cb);
1129
1130 oid_array_clear(&sa);
1131 }
1132
1133 strbuf_release(&output);
1134 return 0;
1135 }
1136
1137 /*
1138 * We are going to call get_sha1 on a potentially very large number of
1139 * objects. In most large cases, these will be actual object sha1s. The
1140 * cost to double-check that each one is not also a ref (just so we can
1141 * warn) ends up dwarfing the actual cost of the object lookups
1142 * themselves. We can work around it by just turning off the warning.
1143 */
1144 save_warning = cfg->warn_on_object_refname_ambiguity;
1145 cfg->warn_on_object_refname_ambiguity = 0;
1146
1147 if (opt->batch_mode == BATCH_MODE_QUEUE_AND_DISPATCH) {
1148 batch_objects_command(opt, &output, &data);
1149 goto cleanup;
1150 }
1151
1152 while (strbuf_getdelim_strip_crlf(&input, stdin, opt->input_delim) != EOF) {
1153 if (data.split_on_whitespace) {
1154 /*
1155 * Split at first whitespace, tying off the beginning
1156 * of the string and saving the remainder (or NULL) in
1157 * data.rest.
1158 */
1159 char *p = strpbrk(input.buf, " \t");
1160 if (p) {
1161 while (*p && strchr(" \t", *p))
1162 *p++ = '\0';
1163 }
1164 data.rest = p;
1165 }
1166
1167 batch_one_object(input.buf, &output, opt, &data);
1168 }
1169
1170 cleanup:
1171 strbuf_release(&input);
1172 strbuf_release(&output);
1173 string_list_clear(&data.remote_allowed_atoms, 0);
1174 cfg->warn_on_object_refname_ambiguity = save_warning;
1175 return retval;
1176 }
1177
1178 static int git_cat_file_config(const char *var, const char *value,
1179 const struct config_context *ctx, void *cb)
1180 {
1181 if (userdiff_config(var, value) < 0)
1182 return -1;
1183
1184 return git_default_config(var, value, ctx, cb);
1185 }
1186
1187 static int batch_option_callback(const struct option *opt,
1188 const char *arg,
1189 int unset)
1190 {
1191 struct batch_options *bo = opt->value;
1192
1193 BUG_ON_OPT_NEG(unset);
1194
1195 if (bo->enabled) {
1196 return error(_("only one batch option may be specified"));
1197 }
1198
1199 bo->enabled = 1;
1200
1201 if (!strcmp(opt->long_name, "batch"))
1202 bo->batch_mode = BATCH_MODE_CONTENTS;
1203 else if (!strcmp(opt->long_name, "batch-check"))
1204 bo->batch_mode = BATCH_MODE_INFO;
1205 else if (!strcmp(opt->long_name, "batch-command"))
1206 bo->batch_mode = BATCH_MODE_QUEUE_AND_DISPATCH;
1207 else
1208 BUG("%s given to batch-option-callback", opt->long_name);
1209
1210 bo->format = arg;
1211
1212 return 0;
1213 }
1214
1215 int cmd_cat_file(int argc,
1216 const char **argv,
1217 const char *prefix,
1218 struct repository *repo UNUSED)
1219 {
1220 int opt = 0;
1221 int opt_cw = 0;
1222 int opt_epts = 0;
1223 const char *exp_type = NULL, *obj_name = NULL;
1224 struct batch_options batch = {
1225 .objects_filter = LIST_OBJECTS_FILTER_INIT,
1226 };
1227 int unknown_type = 0;
1228 int input_nul_terminated = 0;
1229 int nul_terminated = 0;
1230 int ret;
1231
1232 const char * const builtin_catfile_usage[] = {
1233 N_("git cat-file <type> <object>"),
1234 N_("git cat-file (-e | -p | -t | -s) <object>"),
1235 N_("git cat-file (--textconv | --filters)\n"
1236 " [<rev>:<path|tree-ish> | --path=<path|tree-ish> <rev>]"),
1237 N_("git cat-file (--batch | --batch-check | --batch-command) [--batch-all-objects]\n"
1238 " [--buffer] [--follow-symlinks] [--unordered]\n"
1239 " [--textconv | --filters] [-Z]"),
1240 NULL
1241 };
1242 const struct option options[] = {
1243 /* Simple queries */
1244 OPT_GROUP(N_("Check object existence or emit object contents")),
1245 OPT_CMDMODE('e', NULL, &opt,
1246 N_("check if <object> exists"), 'e'),
1247 OPT_CMDMODE('p', NULL, &opt, N_("pretty-print <object> content"), 'p'),
1248
1249 OPT_GROUP(N_("Emit [broken] object attributes")),
1250 OPT_CMDMODE('t', NULL, &opt, N_("show object type (one of 'blob', 'tree', 'commit', 'tag', ...)"), 't'),
1251 OPT_CMDMODE('s', NULL, &opt, N_("show object size"), 's'),
1252 OPT_HIDDEN_BOOL(0, "allow-unknown-type", &unknown_type,
1253 N_("historical option -- no-op")),
1254 OPT_BOOL(0, "use-mailmap", &use_mailmap, N_("use mail map file")),
1255 OPT_ALIAS(0, "mailmap", "use-mailmap"),
1256 /* Batch mode */
1257 OPT_GROUP(N_("Batch objects requested on stdin (or --batch-all-objects)")),
1258 OPT_CALLBACK_F(0, "batch", &batch, N_("format"),
1259 N_("show full <object> or <rev> contents"),
1260 PARSE_OPT_OPTARG | PARSE_OPT_NONEG,
1261 batch_option_callback),
1262 OPT_CALLBACK_F(0, "batch-check", &batch, N_("format"),
1263 N_("like --batch, but don't emit <contents>"),
1264 PARSE_OPT_OPTARG | PARSE_OPT_NONEG,
1265 batch_option_callback),
1266 OPT_BOOL_F('z', NULL, &input_nul_terminated, N_("stdin is NUL-terminated"),
1267 PARSE_OPT_HIDDEN),
1268 OPT_BOOL('Z', NULL, &nul_terminated, N_("stdin and stdout is NUL-terminated")),
1269 OPT_CALLBACK_F(0, "batch-command", &batch, N_("format"),
1270 N_("read commands from stdin"),
1271 PARSE_OPT_OPTARG | PARSE_OPT_NONEG,
1272 batch_option_callback),
1273 OPT_CMDMODE(0, "batch-all-objects", &opt,
1274 N_("with --batch[-check]: ignores stdin, batches all known objects"), 'b'),
1275 /* Batch-specific options */
1276 OPT_GROUP(N_("Change or optimize batch output")),
1277 OPT_BOOL(0, "buffer", &batch.buffer_output, N_("buffer --batch output")),
1278 OPT_BOOL(0, "follow-symlinks", &batch.follow_symlinks,
1279 N_("follow in-tree symlinks")),
1280 OPT_BOOL(0, "unordered", &batch.unordered,
1281 N_("do not order objects before emitting them")),
1282 /* Textconv options, stand-ole*/
1283 OPT_GROUP(N_("Emit object (blob or tree) with conversion or filter (stand-alone, or with batch)")),
1284 OPT_CMDMODE(0, "textconv", &opt,
1285 N_("run textconv on object's content"), 'c'),
1286 OPT_CMDMODE(0, "filters", &opt,
1287 N_("run filters on object's content"), 'w'),
1288 OPT_STRING(0, "path", &force_path, N_("blob|tree"),
1289 N_("use a <path> for (--textconv | --filters); Not with 'batch'")),
1290 OPT_PARSE_LIST_OBJECTS_FILTER(&batch.objects_filter),
1291 OPT_END()
1292 };
1293
1294 repo_config(the_repository, git_cat_file_config, NULL);
1295
1296 batch.buffer_output = -1;
1297
1298 argc = parse_options(argc, argv, prefix, options, builtin_catfile_usage, 0);
1299 opt_cw = (opt == 'c' || opt == 'w');
1300 opt_epts = (opt == 'e' || opt == 'p' || opt == 't' || opt == 's');
1301
1302 if (use_mailmap)
1303 load_mailmap();
1304
1305 switch (batch.objects_filter.choice) {
1306 case LOFC_DISABLED:
1307 break;
1308 case LOFC_BLOB_NONE:
1309 case LOFC_BLOB_LIMIT:
1310 case LOFC_OBJECT_TYPE:
1311 if (!batch.enabled)
1312 usage(_("objects filter only supported in batch mode"));
1313 break;
1314 default:
1315 usagef(_("objects filter not supported: '%s'"),
1316 list_object_filter_config_name(batch.objects_filter.choice));
1317 }
1318
1319 /* --batch-all-objects? */
1320 if (opt == 'b')
1321 batch.all_objects = 1;
1322
1323 /* Option compatibility */
1324 if (force_path && !opt_cw)
1325 usage_msg_optf(_("'%s=<%s>' needs '%s' or '%s'"),
1326 builtin_catfile_usage, options,
1327 "--path", _("path|tree-ish"), "--filters",
1328 "--textconv");
1329
1330 /* Option compatibility with batch mode */
1331 if (batch.enabled)
1332 ;
1333 else if (batch.follow_symlinks)
1334 usage_msg_optf(_("'%s' requires a batch mode"), builtin_catfile_usage,
1335 options, "--follow-symlinks");
1336 else if (batch.buffer_output >= 0)
1337 usage_msg_optf(_("'%s' requires a batch mode"), builtin_catfile_usage,
1338 options, "--buffer");
1339 else if (batch.all_objects)
1340 usage_msg_optf(_("'%s' requires a batch mode"), builtin_catfile_usage,
1341 options, "--batch-all-objects");
1342 else if (input_nul_terminated)
1343 usage_msg_optf(_("'%s' requires a batch mode"), builtin_catfile_usage,
1344 options, "-z");
1345 else if (nul_terminated)
1346 usage_msg_optf(_("'%s' requires a batch mode"), builtin_catfile_usage,
1347 options, "-Z");
1348
1349 batch.input_delim = batch.output_delim = '\n';
1350 if (input_nul_terminated)
1351 batch.input_delim = '\0';
1352 if (nul_terminated)
1353 batch.input_delim = batch.output_delim = '\0';
1354
1355 /* Batch defaults */
1356 if (batch.buffer_output < 0)
1357 batch.buffer_output = batch.all_objects;
1358
1359 prepare_repo_settings(the_repository);
1360 the_repository->settings.command_requires_full_index = 0;
1361
1362 /* Return early if we're in batch mode? */
1363 if (batch.enabled) {
1364 if (opt_cw)
1365 batch.transform_mode = opt;
1366 else if (opt && opt != 'b')
1367 usage_msg_optf(_("'-%c' is incompatible with batch mode"),
1368 builtin_catfile_usage, options, opt);
1369 else if (argc)
1370 usage_msg_opt(_("batch modes take no arguments"),
1371 builtin_catfile_usage, options);
1372
1373 ret = batch_objects(&batch);
1374 goto out;
1375 }
1376
1377 if (opt) {
1378 if (!argc && opt == 'c')
1379 usage_msg_optf(_("<rev> required with '%s'"),
1380 builtin_catfile_usage, options,
1381 "--textconv");
1382 else if (!argc && opt == 'w')
1383 usage_msg_optf(_("<rev> required with '%s'"),
1384 builtin_catfile_usage, options,
1385 "--filters");
1386 else if (!argc && opt_epts)
1387 usage_msg_optf(_("<object> required with '-%c'"),
1388 builtin_catfile_usage, options, opt);
1389 else if (argc == 1)
1390 obj_name = argv[0];
1391 else
1392 usage_msg_opt(_("too many arguments"), builtin_catfile_usage,
1393 options);
1394 } else if (!argc) {
1395 usage_with_options(builtin_catfile_usage, options);
1396 } else if (argc != 2) {
1397 usage_msg_optf(_("only two arguments allowed in <type> <object> mode, not %d"),
1398 builtin_catfile_usage, options, argc);
1399 } else if (argc) {
1400 exp_type = argv[0];
1401 obj_name = argv[1];
1402 }
1403
1404 ret = cat_one_file(opt, exp_type, obj_name);
1405
1406 out:
1407 list_objects_filter_release(&batch.objects_filter);
1408 return ret;
1409 }