interplane.Get Omega
Read in your language

git

[Ported from github.com/git/git] Sync with Git 2.56.1

Brought by drakestapleton

branch master Branches Tags History

git / builtin / cat-file.c

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