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 { .mode = S_IFINVALID, \
349 .type = OBJ_BAD, \
350 .remote_allowed_atoms = STRING_LIST_INIT_NODUP }
351
352 static int is_atom(const char *atom, const char *s, int slen)
353 {
354 int alen = strlen(atom);
355 return alen == slen && !memcmp(atom, s, alen);
356 }
357
358 static int expand_atom(struct strbuf *sb, const char *atom, int len,
359 struct expand_data *data)
360 {
361 if (data->is_remote) {
362 size_t i;
363 for (i = 0; i < data->remote_allowed_atoms.nr; i++)
364 if (is_atom(data->remote_allowed_atoms.items[i].string,
365 atom, len))
366 break;
367 if (i == data->remote_allowed_atoms.nr)
368 return 1;
369 }
370
371 if (is_atom("objectname", atom, len)) {
372 if (!data->mark_query)
373 strbuf_add_oid_hex(sb, &data->oid);
374 } else if (is_atom("objecttype", atom, len)) {
375 if (data->mark_query) {
376 data->info.typep = &data->type;
377 } else {
378 const char *t = type_name(data->type);
379 strbuf_addstr(sb, t ? t : "");
380 }
381 } else if (is_atom("objectsize", atom, len)) {
382 if (data->mark_query)
383 data->info.sizep = &data->size;
384 else
385 strbuf_add_uint(sb, data->size);
386 } else if (is_atom("objectsize:disk", atom, len)) {
387 if (data->mark_query)
388 data->info.disk_sizep = &data->disk_size;
389 else
390 strbuf_add_uint(sb, data->disk_size);
391 } else if (is_atom("rest", atom, len)) {
392 if (data->mark_query)
393 data->split_on_whitespace = 1;
394 else if (data->rest)
395 strbuf_addstr(sb, data->rest);
396 } else if (is_atom("deltabase", atom, len)) {
397 if (data->mark_query)
398 data->info.delta_base_oid = &data->delta_base_oid;
399 else
400 strbuf_add_oid_hex(sb, &data->delta_base_oid);
401 } else if (is_atom("objectmode", atom, len)) {
402 if (!data->mark_query && !(S_IFINVALID == data->mode))
403 strbuf_addf(sb, "%06o", data->mode);
404 } else
405 return 0;
406 return 1;
407 }
408
409 static void expand_format(struct strbuf *sb, const char *start,
410 struct expand_data *data)
411 {
412 while (strbuf_expand_step(sb, &start)) {
413 const char *end;
414
415 if (skip_prefix(start, "%", &start) || *start != '(')
416 strbuf_addch(sb, '%');
417 else if ((end = strchr(start + 1, ')')) &&
418 expand_atom(sb, start + 1, end - start - 1, data))
419 start = end + 1;
420 else
421 strbuf_expand_bad_format(start, "cat-file");
422 }
423 }
424
425 static void batch_write(struct batch_options *opt, const void *data, int len)
426 {
427 if (opt->buffer_output) {
428 if (fwrite(data, 1, len, stdout) != len)
429 die_errno("unable to write to stdout");
430 } else
431 write_or_die(1, data, len);
432 }
433
434 static void print_object_or_die(struct batch_options *opt, struct expand_data *data)
435 {
436 const struct object_id *oid = &data->oid;
437
438 assert(data->info.typep);
439
440 if (data->type == OBJ_BLOB) {
441 if (opt->buffer_output)
442 fflush(stdout);
443 if (opt->transform_mode) {
444 char *contents;
445 size_t size;
446
447 if (!data->rest)
448 die("missing path for '%s'", oid_to_hex(oid));
449
450 if (opt->transform_mode == 'w') {
451 if (filter_object(data->rest, 0100644, oid,
452 &contents, &size))
453 die("could not convert '%s' %s",
454 oid_to_hex(oid), data->rest);
455 } else if (opt->transform_mode == 'c') {
456 enum object_type type;
457 unsigned long size_ul = 0;
458 if (textconv_object(the_repository,
459 data->rest, 0100644, oid,
460 1, &contents, &size_ul))
461 size = size_ul;
462 else
463 contents = odb_read_object(the_repository->objects,
464 oid, &type, &size);
465 if (!contents)
466 die("could not convert '%s' %s",
467 oid_to_hex(oid), data->rest);
468 } else
469 BUG("invalid transform_mode: %c", opt->transform_mode);
470 batch_write(opt, contents, size);
471 free(contents);
472 } else {
473 stream_blob(oid);
474 }
475 }
476 else {
477 enum object_type type;
478 size_t size;
479 void *contents;
480
481 contents = odb_read_object(the_repository->objects, oid,
482 &type, &size);
483 if (!contents)
484 die("object %s disappeared", oid_to_hex(oid));
485
486 if (use_mailmap)
487 contents = replace_idents_using_mailmap(contents, &size);
488
489 if (type != data->type)
490 die("object %s changed type!?", oid_to_hex(oid));
491 if (data->info.sizep && size != data->size && !use_mailmap)
492 die("object %s changed size!?", oid_to_hex(oid));
493
494 batch_write(opt, contents, size);
495 free(contents);
496 }
497 }
498
499 static void print_default_format(struct strbuf *scratch, struct expand_data *data,
500 struct batch_options *opt)
501 {
502 strbuf_add_oid_hex(scratch, &data->oid);
503 strbuf_addch(scratch, ' ');
504 strbuf_addstr(scratch, type_name(data->type));
505 strbuf_addch(scratch, ' ');
506 strbuf_add_uint(scratch, data->size);
507 strbuf_addch(scratch, opt->output_delim);
508 }
509
510 static void report_object_status(struct batch_options *opt,
511 const char *obj_name,
512 const struct object_id *oid,
513 const char *status)
514 {
515 printf("%s %s%c", obj_name ? obj_name : oid_to_hex(oid),
516 status, opt->output_delim);
517 fflush(stdout);
518 }
519
520 /*
521 * If "pack" is non-NULL, then "offset" is the byte offset within the pack from
522 * which the object may be accessed (though note that we may also rely on
523 * data->oid, too). If "pack" is NULL, then offset is ignored.
524 */
525 static void batch_object_write(const char *obj_name,
526 struct strbuf *scratch,
527 struct batch_options *opt,
528 struct expand_data *data,
529 struct packed_git *pack,
530 off_t offset)
531 {
532 if (!data->skip_object_info) {
533 int ret;
534
535 if (use_mailmap ||
536 opt->objects_filter.choice == LOFC_BLOB_NONE ||
537 opt->objects_filter.choice == LOFC_BLOB_LIMIT ||
538 opt->objects_filter.choice == LOFC_OBJECT_TYPE)
539 data->info.typep = &data->type;
540 if (opt->objects_filter.choice == LOFC_BLOB_LIMIT)
541 data->info.sizep = &data->size;
542
543 if (pack)
544 ret = packed_object_info(NULL, pack, offset, &data->info);
545 else
546 ret = odb_read_object_info_extended(the_repository->objects,
547 &data->oid, &data->info,
548 OBJECT_INFO_LOOKUP_REPLACE);
549 if (ret < 0) {
550 if (data->mode == S_IFGITLINK)
551 report_object_status(opt, NULL, &data->oid, "submodule");
552 else
553 report_object_status(opt, obj_name, &data->oid, "missing");
554 return;
555 }
556
557 switch (opt->objects_filter.choice) {
558 case LOFC_DISABLED:
559 break;
560 case LOFC_BLOB_NONE:
561 if (data->type == OBJ_BLOB) {
562 if (!opt->all_objects)
563 report_object_status(opt, obj_name,
564 &data->oid, "excluded");
565 return;
566 }
567 break;
568 case LOFC_BLOB_LIMIT:
569 if (data->type == OBJ_BLOB &&
570 data->size >= opt->objects_filter.blob_limit_value) {
571 if (!opt->all_objects)
572 report_object_status(opt, obj_name,
573 &data->oid, "excluded");
574 return;
575 }
576 break;
577 case LOFC_OBJECT_TYPE:
578 if (data->type != opt->objects_filter.object_type) {
579 if (!opt->all_objects)
580 report_object_status(opt, obj_name,
581 &data->oid, "excluded");
582 return;
583 }
584 break;
585 default:
586 BUG("unsupported objects filter");
587 }
588
589 if (use_mailmap && (data->type == OBJ_COMMIT || data->type == OBJ_TAG)) {
590 char *buf = NULL;
591
592 buf = odb_read_object(the_repository->objects, &data->oid,
593 &data->type, &data->size);
594 if (!buf)
595 die(_("unable to read %s"), oid_to_hex(&data->oid));
596 buf = replace_idents_using_mailmap(buf, &data->size);
597
598 free(buf);
599 }
600 }
601
602 strbuf_reset(scratch);
603
604 if (!opt->format) {
605 print_default_format(scratch, data, opt);
606 } else {
607 expand_format(scratch, opt->format, data);
608 strbuf_addch(scratch, opt->output_delim);
609 }
610
611 batch_write(opt, scratch->buf, scratch->len);
612
613 if (opt->batch_mode == BATCH_MODE_CONTENTS) {
614 print_object_or_die(opt, data);
615 batch_write(opt, &opt->output_delim, 1);
616 }
617 }
618
619 static void batch_one_object(const char *obj_name,
620 struct strbuf *scratch,
621 struct batch_options *opt,
622 struct expand_data *data)
623 {
624 struct object_context ctx = {0};
625 int flags =
626 GET_OID_HASH_ANY |
627 (opt->follow_symlinks ? GET_OID_FOLLOW_SYMLINKS : 0);
628 enum get_oid_result result;
629
630 result = get_oid_with_context(the_repository, obj_name,
631 flags, &data->oid, &ctx);
632 if (result != FOUND) {
633 switch (result) {
634 case MISSING_OBJECT:
635 report_object_status(opt, obj_name, &data->oid, "missing");
636 break;
637 case SHORT_NAME_AMBIGUOUS:
638 report_object_status(opt, obj_name, &data->oid, "ambiguous");
639 break;
640 case DANGLING_SYMLINK:
641 printf("dangling %"PRIuMAX"%c%s%c",
642 (uintmax_t)strlen(obj_name),
643 opt->output_delim, obj_name, opt->output_delim);
644 break;
645 case SYMLINK_LOOP:
646 printf("loop %"PRIuMAX"%c%s%c",
647 (uintmax_t)strlen(obj_name),
648 opt->output_delim, obj_name, opt->output_delim);
649 break;
650 case NOT_DIR:
651 printf("notdir %"PRIuMAX"%c%s%c",
652 (uintmax_t)strlen(obj_name),
653 opt->output_delim, obj_name, opt->output_delim);
654 break;
655 default:
656 BUG("unknown get_sha1_with_context result %d\n",
657 result);
658 break;
659 }
660 fflush(stdout);
661
662 goto out;
663 }
664
665 if (ctx.mode == 0) {
666 printf("symlink %"PRIuMAX"%c%s%c",
667 (uintmax_t)ctx.symlink_path.len,
668 opt->output_delim, ctx.symlink_path.buf, opt->output_delim);
669 fflush(stdout);
670 goto out;
671 }
672
673 data->mode = ctx.mode;
674 batch_object_write(obj_name, scratch, opt, data, NULL, 0);
675
676 out:
677 object_context_release(&ctx);
678 }
679
680 static int get_remote_info(int argc,
681 const char **argv,
682 struct object_info **remote_object_info,
683 struct oid_array *object_info_oids,
684 struct string_list *object_info_options)
685 {
686 int retval = 0;
687 struct remote *remote = NULL;
688 struct object_id oid;
689 struct transport *gtransport;
690
691 remote = remote_get(argv[0]);
692 if (!remote)
693 die(_("must supply valid remote when using remote-object-info"));
694
695 oid_array_clear(object_info_oids);
696 for (size_t i = 1; i < argc; i++) {
697 if (get_oid_hex(argv[i], &oid)) {
698 size_t len = strlen(argv[i]);
699
700 if (len < the_hash_algo->hexsz && len >= 4) {
701 size_t j;
702 for (j = 0; j < len; j++)
703 if (!isxdigit(argv[i][j]))
704 break;
705 if (j == len)
706 die(_("remote-object-info does not support "
707 "short oids, %d characters required"),
708 (int)the_hash_algo->hexsz);
709 }
710 die(_("not a valid object name '%s'"), argv[i]);
711 }
712 oid_array_append(object_info_oids, &oid);
713 }
714
715 if (!object_info_oids->nr)
716 die(_("remote-object-info requires objects"));
717
718 gtransport = transport_get(remote, NULL);
719
720 if (!gtransport->smart_options) {
721 retval = -1;
722 goto cleanup;
723 }
724
725 CALLOC_ARRAY(*remote_object_info, object_info_oids->nr);
726 gtransport->smart_options->object_info_oids = object_info_oids;
727
728 gtransport->smart_options->object_info_options = object_info_options;
729 gtransport->smart_options->object_info_data = *remote_object_info;
730 retval = transport_fetch_object_info(gtransport);
731 cleanup:
732 transport_disconnect(gtransport);
733 return retval;
734 }
735
736 struct object_cb_data {
737 struct batch_options *opt;
738 struct expand_data *expand;
739 struct oidset *seen;
740 struct strbuf *scratch;
741 };
742
743 static int batch_object_cb(const struct object_id *oid, void *vdata)
744 {
745 struct object_cb_data *data = vdata;
746 oidcpy(&data->expand->oid, oid);
747 batch_object_write(NULL, data->scratch, data->opt, data->expand,
748 NULL, 0);
749 return 0;
750 }
751
752 static int collect_object(const struct object_id *oid,
753 struct packed_git *pack UNUSED,
754 off_t offset UNUSED,
755 void *data)
756 {
757 oid_array_append(data, oid);
758 return 0;
759 }
760
761 static int batch_unordered_object(const struct object_id *oid,
762 struct packed_git *pack,
763 off_t offset,
764 void *vdata)
765 {
766 struct object_cb_data *data = vdata;
767
768 if (oidset_insert(data->seen, oid))
769 return 0;
770
771 oidcpy(&data->expand->oid, oid);
772 batch_object_write(NULL, data->scratch, data->opt, data->expand,
773 pack, offset);
774 return 0;
775 }
776
777 typedef void (*parse_cmd_fn_t)(struct batch_options *, const char *,
778 struct strbuf *, struct expand_data *);
779
780 struct queued_cmd {
781 parse_cmd_fn_t fn;
782 char *line;
783 };
784
785 static void parse_cmd_contents(struct batch_options *opt,
786 const char *line,
787 struct strbuf *output,
788 struct expand_data *data)
789 {
790 opt->batch_mode = BATCH_MODE_CONTENTS;
791 batch_one_object(line, output, opt, data);
792 }
793
794 static void parse_cmd_info(struct batch_options *opt,
795 const char *line,
796 struct strbuf *output,
797 struct expand_data *data)
798 {
799 opt->batch_mode = BATCH_MODE_INFO;
800 batch_one_object(line, output, opt, data);
801 }
802
803 static void parse_cmd_mailmap(struct batch_options *opt UNUSED,
804 const char *line,
805 struct strbuf *output UNUSED,
806 struct expand_data *data UNUSED)
807 {
808 use_mailmap = git_parse_maybe_bool(line);
809
810 if (use_mailmap < 0)
811 die(_("mailmap: invalid boolean '%s'"), line);
812
813 if (use_mailmap)
814 load_mailmap();
815 }
816
817 struct protocol_placeholder_entry {
818 const char *option;
819 const char *atom;
820 };
821
822 static const struct protocol_placeholder_entry remote_atom_map[] = {
823 {"size", "objectsize"},
824 {"type", "objecttype"},
825 /*
826 * Add new protocol options here. Even if the server doesn't support
827 * them the allow_list will drop them if the server doesn't advertise
828 * them.
829 */
830 };
831
832 static void parse_cmd_remote_object_info(struct batch_options *opt,
833 const char *line, struct strbuf *output,
834 struct expand_data *data)
835 {
836 int count;
837 const char **argv;
838 char *line_to_split;
839 struct object_info *remote_object_info = NULL;
840 struct oid_array object_info_oids = OID_ARRAY_INIT;
841 struct string_list object_info_options = STRING_LIST_INIT_NODUP;
842 const char *saved_format = opt->format;
843
844 if (strlen(line) >= MAX_REMOTE_OBJ_INFO_LINE)
845 die(_("remote-object-info command too long"));
846 /*
847 * TODO: Use the default format once %(objecttype) is supported.
848 */
849 if (!opt->format)
850 opt->format = "%(objectname) %(objectsize)";
851
852 line_to_split = xstrdup(line);
853 count = split_cmdline(line_to_split, &argv);
854 if (count < 0)
855 die(_("remote-object-info: failed to parse command line: %s"),
856 split_cmdline_strerror(count));
857 if (count - 1 > MAX_ALLOWED_OBJ_LIMIT)
858 die(_("remote-object-info supports at most %d objects"),
859 MAX_ALLOWED_OBJ_LIMIT);
860
861 if (data->info.sizep)
862 string_list_append(&object_info_options, "size");
863 if (data->info.typep)
864 string_list_append(&object_info_options, "type");
865
866 if (get_remote_info(count, argv, &remote_object_info,
867 &object_info_oids, &object_info_options))
868 die(_("failed to get object info from the remote: %s"), argv[0]);
869
870 string_list_clear(&data->remote_allowed_atoms, 0);
871 string_list_append(&data->remote_allowed_atoms, "objectname");
872 for (size_t i = 0; i < ARRAY_SIZE(remote_atom_map); i++)
873 if (unsorted_string_list_has_string(&object_info_options, remote_atom_map[i].option))
874 string_list_append(&data->remote_allowed_atoms,
875 remote_atom_map[i].atom);
876
877 data->skip_object_info = 1;
878 for (size_t i = 0; i < object_info_oids.nr; i++) {
879 data->oid = object_info_oids.oid[i];
880
881 if (remote_object_info[i].unrecognized) {
882 report_object_status(opt, oid_to_hex(&data->oid),
883 &data->oid, "missing");
884 continue;
885 }
886
887 /*
888 * When reaching here, it means remote-object-info can retrieve
889 * information from server without downloading them.
890 */
891 if (remote_object_info[i].sizep) {
892 data->size = *remote_object_info[i].sizep;
893 }
894
895 if (remote_object_info[i].typep) {
896 data->type = *remote_object_info[i].typep;
897 }
898
899 opt->batch_mode = BATCH_MODE_INFO;
900 data->is_remote = 1;
901 batch_object_write(argv[i + 1], output, opt, data, NULL, 0);
902 data->is_remote = 0;
903 }
904 data->skip_object_info = 0;
905 opt->format = saved_format;
906
907 for (size_t i = 0; i < object_info_oids.nr; i++)
908 free_object_info_contents(&remote_object_info[i]);
909 string_list_clear(&object_info_options, 0);
910 free(line_to_split);
911 free(argv);
912 free(remote_object_info);
913 oid_array_clear(&object_info_oids);
914 }
915
916 static void dispatch_calls(struct batch_options *opt,
917 struct strbuf *output,
918 struct expand_data *data,
919 struct queued_cmd *cmd,
920 size_t nr)
921 {
922 if (!opt->buffer_output)
923 die(_("flush is only for --buffer mode"));
924
925 for (size_t i = 0; i < nr; i++)
926 cmd[i].fn(opt, cmd[i].line, output, data);
927
928 fflush(stdout);
929 }
930
931 static void free_cmds(struct queued_cmd *cmd, size_t *nr)
932 {
933 for (size_t i = 0; i < *nr; i++)
934 FREE_AND_NULL(cmd[i].line);
935
936 *nr = 0;
937 }
938
939
940 static const struct parse_cmd {
941 const char *name;
942 parse_cmd_fn_t fn;
943 unsigned takes_args;
944 } commands[] = {
945 { "contents", parse_cmd_contents, 1 },
946 { "flush", NULL, 0 },
947 { "info", parse_cmd_info, 1 },
948 { "mailmap", parse_cmd_mailmap, 1 },
949 { "remote-object-info", parse_cmd_remote_object_info, 1 },
950 };
951
952 static void batch_objects_command(struct batch_options *opt,
953 struct strbuf *output,
954 struct expand_data *data)
955 {
956 struct strbuf input = STRBUF_INIT;
957 struct queued_cmd *queued_cmd = NULL;
958 size_t alloc = 0, nr = 0;
959
960 while (strbuf_getdelim_strip_crlf(&input, stdin, opt->input_delim) != EOF) {
961 const struct parse_cmd *cmd = NULL;
962 const char *p = NULL, *cmd_end;
963 struct queued_cmd call = {0};
964
965 if (!input.len)
966 die(_("empty command in input"));
967 if (isspace(*input.buf))
968 die(_("whitespace before command: '%s'"), input.buf);
969
970 for (size_t i = 0; i < ARRAY_SIZE(commands); i++) {
971 if (!skip_prefix(input.buf, commands[i].name, &cmd_end))
972 continue;
973
974 cmd = &commands[i];
975 if (cmd->takes_args) {
976 if (*cmd_end != ' ')
977 die(_("%s requires arguments"),
978 commands[i].name);
979
980 p = cmd_end + 1;
981 } else if (*cmd_end) {
982 die(_("%s takes no arguments"),
983 commands[i].name);
984 }
985
986 break;
987 }
988
989 if (!cmd)
990 die(_("unknown command: '%s'"), input.buf);
991
992 if (!strcmp(cmd->name, "flush")) {
993 dispatch_calls(opt, output, data, queued_cmd, nr);
994 free_cmds(queued_cmd, &nr);
995 } else if (!opt->buffer_output) {
996 cmd->fn(opt, p, output, data);
997 } else {
998 ALLOC_GROW(queued_cmd, nr + 1, alloc);
999 call.fn = cmd->fn;
1000 call.line = xstrdup_or_null(p);
1001 queued_cmd[nr++] = call;
1002 }
1003 }
1004
1005 if (opt->buffer_output &&
1006 nr &&
1007 !git_env_bool("GIT_TEST_CAT_FILE_NO_FLUSH_ON_EXIT", 0)) {
1008 dispatch_calls(opt, output, data, queued_cmd, nr);
1009 free_cmds(queued_cmd, &nr);
1010 }
1011
1012 free_cmds(queued_cmd, &nr);
1013 free(queued_cmd);
1014 strbuf_release(&input);
1015 }
1016
1017 #define DEFAULT_FORMAT "%(objectname) %(objecttype) %(objectsize)"
1018
1019 typedef int (*for_each_object_fn)(const struct object_id *oid, struct packed_git *pack,
1020 off_t offset, void *data);
1021
1022 struct for_each_object_payload {
1023 for_each_object_fn callback;
1024 void *payload;
1025 };
1026
1027 static int batch_one_object_oi(const struct object_id *oid,
1028 struct object_info *oi,
1029 void *_payload)
1030 {
1031 struct for_each_object_payload *payload = _payload;
1032 if (oi && oi->source_infop->source->type == ODB_SOURCE_PACKED)
1033 return payload->callback(oid, oi->source_infop->u.packed.pack,
1034 oi->source_infop->u.packed.offset,
1035 payload->payload);
1036 return payload->callback(oid, NULL, 0, payload->payload);
1037 }
1038
1039 static void batch_each_object(struct batch_options *opt,
1040 for_each_object_fn callback,
1041 unsigned flags,
1042 void *_payload)
1043 {
1044 struct for_each_object_payload payload = {
1045 .callback = callback,
1046 .payload = _payload,
1047 };
1048 struct odb_source_info source_info;
1049 struct object_info oi = {
1050 .source_infop = &source_info,
1051 };
1052 struct odb_for_each_object_options opts = {
1053 .flags = flags,
1054 .filter = &opt->objects_filter,
1055 };
1056
1057 odb_for_each_object_ext(the_repository->objects, &oi,
1058 batch_one_object_oi, &payload, &opts);
1059 }
1060
1061 static int batch_objects(struct batch_options *opt)
1062 {
1063 struct strbuf input = STRBUF_INIT;
1064 struct strbuf output = STRBUF_INIT;
1065 struct expand_data data = EXPAND_DATA_INIT;
1066 struct repo_config_values *cfg = repo_config_values(the_repository);
1067 int save_warning;
1068 int retval = 0;
1069
1070 /*
1071 * Expand once with our special mark_query flag, which will prime the
1072 * object_info to be handed to odb_read_object_info_extended for each
1073 * object.
1074 */
1075 data.mark_query = 1;
1076 expand_format(&output,
1077 opt->format ? opt->format : DEFAULT_FORMAT,
1078 &data);
1079 data.mark_query = 0;
1080 strbuf_release(&output);
1081 if (opt->transform_mode)
1082 data.split_on_whitespace = 1;
1083
1084 if (opt->format && !strcmp(opt->format, DEFAULT_FORMAT))
1085 opt->format = NULL;
1086 /*
1087 * If we are printing out the object, then always fill in the type,
1088 * since we will want to decide whether or not to stream.
1089 */
1090 if (opt->batch_mode == BATCH_MODE_CONTENTS)
1091 data.info.typep = &data.type;
1092
1093 if (opt->all_objects) {
1094 struct object_cb_data cb;
1095 struct object_info empty = OBJECT_INFO_INIT;
1096
1097 if (!memcmp(&data.info, &empty, sizeof(empty)) &&
1098 opt->objects_filter.choice == LOFC_DISABLED)
1099 data.skip_object_info = 1;
1100
1101 if (repo_has_promisor_remote(the_repository))
1102 warning("This repository uses promisor remotes. Some objects may not be loaded.");
1103
1104 disable_replace_refs();
1105
1106 cb.opt = opt;
1107 cb.expand = &data;
1108 cb.scratch = &output;
1109
1110 if (opt->unordered) {
1111 struct oidset seen = OIDSET_INIT;
1112
1113 cb.seen = &seen;
1114
1115 batch_each_object(opt, batch_unordered_object,
1116 ODB_FOR_EACH_OBJECT_PACK_ORDER, &cb);
1117
1118 oidset_clear(&seen);
1119 } else {
1120 struct oid_array sa = OID_ARRAY_INIT;
1121
1122 batch_each_object(opt, collect_object, 0, &sa);
1123 oid_array_for_each_unique(&sa, batch_object_cb, &cb);
1124
1125 oid_array_clear(&sa);
1126 }
1127
1128 strbuf_release(&output);
1129 return 0;
1130 }
1131
1132 /*
1133 * We are going to call get_sha1 on a potentially very large number of
1134 * objects. In most large cases, these will be actual object sha1s. The
1135 * cost to double-check that each one is not also a ref (just so we can
1136 * warn) ends up dwarfing the actual cost of the object lookups
1137 * themselves. We can work around it by just turning off the warning.
1138 */
1139 save_warning = cfg->warn_on_object_refname_ambiguity;
1140 cfg->warn_on_object_refname_ambiguity = 0;
1141
1142 if (opt->batch_mode == BATCH_MODE_QUEUE_AND_DISPATCH) {
1143 batch_objects_command(opt, &output, &data);
1144 goto cleanup;
1145 }
1146
1147 while (strbuf_getdelim_strip_crlf(&input, stdin, opt->input_delim) != EOF) {
1148 if (data.split_on_whitespace) {
1149 /*
1150 * Split at first whitespace, tying off the beginning
1151 * of the string and saving the remainder (or NULL) in
1152 * data.rest.
1153 */
1154 char *p = strpbrk(input.buf, " \t");
1155 if (p) {
1156 while (*p && strchr(" \t", *p))
1157 *p++ = '\0';
1158 }
1159 data.rest = p;
1160 }
1161
1162 batch_one_object(input.buf, &output, opt, &data);
1163 }
1164
1165 cleanup:
1166 strbuf_release(&input);
1167 strbuf_release(&output);
1168 string_list_clear(&data.remote_allowed_atoms, 0);
1169 cfg->warn_on_object_refname_ambiguity = save_warning;
1170 return retval;
1171 }
1172
1173 static int git_cat_file_config(const char *var, const char *value,
1174 const struct config_context *ctx, void *cb)
1175 {
1176 if (userdiff_config(var, value) < 0)
1177 return -1;
1178
1179 return git_default_config(var, value, ctx, cb);
1180 }
1181
1182 static int batch_option_callback(const struct option *opt,
1183 const char *arg,
1184 int unset)
1185 {
1186 struct batch_options *bo = opt->value;
1187
1188 BUG_ON_OPT_NEG(unset);
1189
1190 if (bo->enabled) {
1191 return error(_("only one batch option may be specified"));
1192 }
1193
1194 bo->enabled = 1;
1195
1196 if (!strcmp(opt->long_name, "batch"))
1197 bo->batch_mode = BATCH_MODE_CONTENTS;
1198 else if (!strcmp(opt->long_name, "batch-check"))
1199 bo->batch_mode = BATCH_MODE_INFO;
1200 else if (!strcmp(opt->long_name, "batch-command"))
1201 bo->batch_mode = BATCH_MODE_QUEUE_AND_DISPATCH;
1202 else
1203 BUG("%s given to batch-option-callback", opt->long_name);
1204
1205 bo->format = arg;
1206
1207 return 0;
1208 }
1209
1210 int cmd_cat_file(int argc,
1211 const char **argv,
1212 const char *prefix,
1213 struct repository *repo UNUSED)
1214 {
1215 int opt = 0;
1216 int opt_cw = 0;
1217 int opt_epts = 0;
1218 const char *exp_type = NULL, *obj_name = NULL;
1219 struct batch_options batch = {
1220 .objects_filter = LIST_OBJECTS_FILTER_INIT,
1221 };
1222 int unknown_type = 0;
1223 int input_nul_terminated = 0;
1224 int nul_terminated = 0;
1225 int ret;
1226
1227 const char * const builtin_catfile_usage[] = {
1228 N_("git cat-file <type> <object>"),
1229 N_("git cat-file (-e | -p | -t | -s) <object>"),
1230 N_("git cat-file (--textconv | --filters)\n"
1231 " [<rev>:<path|tree-ish> | --path=<path|tree-ish> <rev>]"),
1232 N_("git cat-file (--batch | --batch-check | --batch-command) [--batch-all-objects]\n"
1233 " [--buffer] [--follow-symlinks] [--unordered]\n"
1234 " [--textconv | --filters] [-Z]"),
1235 NULL
1236 };
1237 const struct option options[] = {
1238 /* Simple queries */
1239 OPT_GROUP(N_("Check object existence or emit object contents")),
1240 OPT_CMDMODE('e', NULL, &opt,
1241 N_("check if <object> exists"), 'e'),
1242 OPT_CMDMODE('p', NULL, &opt, N_("pretty-print <object> content"), 'p'),
1243
1244 OPT_GROUP(N_("Emit [broken] object attributes")),
1245 OPT_CMDMODE('t', NULL, &opt, N_("show object type (one of 'blob', 'tree', 'commit', 'tag', ...)"), 't'),
1246 OPT_CMDMODE('s', NULL, &opt, N_("show object size"), 's'),
1247 OPT_HIDDEN_BOOL(0, "allow-unknown-type", &unknown_type,
1248 N_("historical option -- no-op")),
1249 OPT_BOOL(0, "use-mailmap", &use_mailmap, N_("use mail map file")),
1250 OPT_ALIAS(0, "mailmap", "use-mailmap"),
1251 /* Batch mode */
1252 OPT_GROUP(N_("Batch objects requested on stdin (or --batch-all-objects)")),
1253 OPT_CALLBACK_F(0, "batch", &batch, N_("format"),
1254 N_("show full <object> or <rev> contents"),
1255 PARSE_OPT_OPTARG | PARSE_OPT_NONEG,
1256 batch_option_callback),
1257 OPT_CALLBACK_F(0, "batch-check", &batch, N_("format"),
1258 N_("like --batch, but don't emit <contents>"),
1259 PARSE_OPT_OPTARG | PARSE_OPT_NONEG,
1260 batch_option_callback),
1261 OPT_BOOL_F('z', NULL, &input_nul_terminated, N_("stdin is NUL-terminated"),
1262 PARSE_OPT_HIDDEN),
1263 OPT_BOOL('Z', NULL, &nul_terminated, N_("stdin and stdout is NUL-terminated")),
1264 OPT_CALLBACK_F(0, "batch-command", &batch, N_("format"),
1265 N_("read commands from stdin"),
1266 PARSE_OPT_OPTARG | PARSE_OPT_NONEG,
1267 batch_option_callback),
1268 OPT_CMDMODE(0, "batch-all-objects", &opt,
1269 N_("with --batch[-check]: ignores stdin, batches all known objects"), 'b'),
1270 /* Batch-specific options */
1271 OPT_GROUP(N_("Change or optimize batch output")),
1272 OPT_BOOL(0, "buffer", &batch.buffer_output, N_("buffer --batch output")),
1273 OPT_BOOL(0, "follow-symlinks", &batch.follow_symlinks,
1274 N_("follow in-tree symlinks")),
1275 OPT_BOOL(0, "unordered", &batch.unordered,
1276 N_("do not order objects before emitting them")),
1277 /* Textconv options, stand-ole*/
1278 OPT_GROUP(N_("Emit object (blob or tree) with conversion or filter (stand-alone, or with batch)")),
1279 OPT_CMDMODE(0, "textconv", &opt,
1280 N_("run textconv on object's content"), 'c'),
1281 OPT_CMDMODE(0, "filters", &opt,
1282 N_("run filters on object's content"), 'w'),
1283 OPT_STRING(0, "path", &force_path, N_("blob|tree"),
1284 N_("use a <path> for (--textconv | --filters); Not with 'batch'")),
1285 OPT_PARSE_LIST_OBJECTS_FILTER(&batch.objects_filter),
1286 OPT_END()
1287 };
1288
1289 repo_config(the_repository, git_cat_file_config, NULL);
1290
1291 batch.buffer_output = -1;
1292
1293 argc = parse_options(argc, argv, prefix, options, builtin_catfile_usage, 0);
1294 opt_cw = (opt == 'c' || opt == 'w');
1295 opt_epts = (opt == 'e' || opt == 'p' || opt == 't' || opt == 's');
1296
1297 if (use_mailmap)
1298 load_mailmap();
1299
1300 switch (batch.objects_filter.choice) {
1301 case LOFC_DISABLED:
1302 break;
1303 case LOFC_BLOB_NONE:
1304 case LOFC_BLOB_LIMIT:
1305 case LOFC_OBJECT_TYPE:
1306 if (!batch.enabled)
1307 usage(_("objects filter only supported in batch mode"));
1308 break;
1309 default:
1310 usagef(_("objects filter not supported: '%s'"),
1311 list_object_filter_config_name(batch.objects_filter.choice));
1312 }
1313
1314 /* --batch-all-objects? */
1315 if (opt == 'b')
1316 batch.all_objects = 1;
1317
1318 /* Option compatibility */
1319 if (force_path && !opt_cw)
1320 usage_msg_optf(_("'%s=<%s>' needs '%s' or '%s'"),
1321 builtin_catfile_usage, options,
1322 "--path", _("path|tree-ish"), "--filters",
1323 "--textconv");
1324
1325 /* Option compatibility with batch mode */
1326 if (batch.enabled)
1327 ;
1328 else if (batch.follow_symlinks)
1329 usage_msg_optf(_("'%s' requires a batch mode"), builtin_catfile_usage,
1330 options, "--follow-symlinks");
1331 else if (batch.buffer_output >= 0)
1332 usage_msg_optf(_("'%s' requires a batch mode"), builtin_catfile_usage,
1333 options, "--buffer");
1334 else if (batch.all_objects)
1335 usage_msg_optf(_("'%s' requires a batch mode"), builtin_catfile_usage,
1336 options, "--batch-all-objects");
1337 else if (input_nul_terminated)
1338 usage_msg_optf(_("'%s' requires a batch mode"), builtin_catfile_usage,
1339 options, "-z");
1340 else if (nul_terminated)
1341 usage_msg_optf(_("'%s' requires a batch mode"), builtin_catfile_usage,
1342 options, "-Z");
1343
1344 batch.input_delim = batch.output_delim = '\n';
1345 if (input_nul_terminated)
1346 batch.input_delim = '\0';
1347 if (nul_terminated)
1348 batch.input_delim = batch.output_delim = '\0';
1349
1350 /* Batch defaults */
1351 if (batch.buffer_output < 0)
1352 batch.buffer_output = batch.all_objects;
1353
1354 prepare_repo_settings(the_repository);
1355 the_repository->settings.command_requires_full_index = 0;
1356
1357 /* Return early if we're in batch mode? */
1358 if (batch.enabled) {
1359 if (opt_cw)
1360 batch.transform_mode = opt;
1361 else if (opt && opt != 'b')
1362 usage_msg_optf(_("'-%c' is incompatible with batch mode"),
1363 builtin_catfile_usage, options, opt);
1364 else if (argc)
1365 usage_msg_opt(_("batch modes take no arguments"),
1366 builtin_catfile_usage, options);
1367
1368 ret = batch_objects(&batch);
1369 goto out;
1370 }
1371
1372 if (opt) {
1373 if (!argc && opt == 'c')
1374 usage_msg_optf(_("<rev> required with '%s'"),
1375 builtin_catfile_usage, options,
1376 "--textconv");
1377 else if (!argc && opt == 'w')
1378 usage_msg_optf(_("<rev> required with '%s'"),
1379 builtin_catfile_usage, options,
1380 "--filters");
1381 else if (!argc && opt_epts)
1382 usage_msg_optf(_("<object> required with '-%c'"),
1383 builtin_catfile_usage, options, opt);
1384 else if (argc == 1)
1385 obj_name = argv[0];
1386 else
1387 usage_msg_opt(_("too many arguments"), builtin_catfile_usage,
1388 options);
1389 } else if (!argc) {
1390 usage_with_options(builtin_catfile_usage, options);
1391 } else if (argc != 2) {
1392 usage_msg_optf(_("only two arguments allowed in <type> <object> mode, not %d"),
1393 builtin_catfile_usage, options, argc);
1394 } else if (argc) {
1395 exp_type = argv[0];
1396 obj_name = argv[1];
1397 }
1398
1399 ret = cat_one_file(opt, exp_type, obj_name);
1400
1401 out:
1402 list_objects_filter_release(&batch.objects_filter);
1403 return ret;
1404 }