Sync with 2.22.2
[git] / builtin / cat-file.c
1 /*
2  * GIT - The information manager from hell
3  *
4  * Copyright (C) Linus Torvalds, 2005
5  */
6 #define USE_THE_INDEX_COMPATIBILITY_MACROS
7 #include "cache.h"
8 #include "config.h"
9 #include "builtin.h"
10 #include "diff.h"
11 #include "parse-options.h"
12 #include "userdiff.h"
13 #include "streaming.h"
14 #include "tree-walk.h"
15 #include "sha1-array.h"
16 #include "packfile.h"
17 #include "object-store.h"
18
19 struct batch_options {
20         int enabled;
21         int follow_symlinks;
22         int print_contents;
23         int buffer_output;
24         int all_objects;
25         int unordered;
26         int cmdmode; /* may be 'w' or 'c' for --filters or --textconv */
27         const char *format;
28 };
29
30 static const char *force_path;
31
32 static int filter_object(const char *path, unsigned mode,
33                          const struct object_id *oid,
34                          char **buf, unsigned long *size)
35 {
36         enum object_type type;
37
38         *buf = read_object_file(oid, &type, size);
39         if (!*buf)
40                 return error(_("cannot read object %s '%s'"),
41                              oid_to_hex(oid), path);
42         if ((type == OBJ_BLOB) && S_ISREG(mode)) {
43                 struct strbuf strbuf = STRBUF_INIT;
44                 if (convert_to_working_tree(&the_index, path, *buf, *size, &strbuf)) {
45                         free(*buf);
46                         *size = strbuf.len;
47                         *buf = strbuf_detach(&strbuf, NULL);
48                 }
49         }
50
51         return 0;
52 }
53
54 static int stream_blob(const struct object_id *oid)
55 {
56         if (stream_blob_to_fd(1, oid, NULL, 0))
57                 die("unable to stream %s to stdout", oid_to_hex(oid));
58         return 0;
59 }
60
61 static int cat_one_file(int opt, const char *exp_type, const char *obj_name,
62                         int unknown_type)
63 {
64         struct object_id oid;
65         enum object_type type;
66         char *buf;
67         unsigned long size;
68         struct object_context obj_context;
69         struct object_info oi = OBJECT_INFO_INIT;
70         struct strbuf sb = STRBUF_INIT;
71         unsigned flags = OBJECT_INFO_LOOKUP_REPLACE;
72         const char *path = force_path;
73
74         if (unknown_type)
75                 flags |= OBJECT_INFO_ALLOW_UNKNOWN_TYPE;
76
77         if (get_oid_with_context(the_repository, obj_name,
78                                  GET_OID_RECORD_PATH,
79                                  &oid, &obj_context))
80                 die("Not a valid object name %s", obj_name);
81
82         if (!path)
83                 path = obj_context.path;
84         if (obj_context.mode == S_IFINVALID)
85                 obj_context.mode = 0100644;
86
87         buf = NULL;
88         switch (opt) {
89         case 't':
90                 oi.type_name = &sb;
91                 if (oid_object_info_extended(the_repository, &oid, &oi, flags) < 0)
92                         die("git cat-file: could not get object info");
93                 if (sb.len) {
94                         printf("%s\n", sb.buf);
95                         strbuf_release(&sb);
96                         return 0;
97                 }
98                 break;
99
100         case 's':
101                 oi.sizep = &size;
102                 if (oid_object_info_extended(the_repository, &oid, &oi, flags) < 0)
103                         die("git cat-file: could not get object info");
104                 printf("%"PRIuMAX"\n", (uintmax_t)size);
105                 return 0;
106
107         case 'e':
108                 return !has_object_file(&oid);
109
110         case 'w':
111                 if (!path)
112                         die("git cat-file --filters %s: <object> must be "
113                             "<sha1:path>", obj_name);
114
115                 if (filter_object(path, obj_context.mode,
116                                   &oid, &buf, &size))
117                         return -1;
118                 break;
119
120         case 'c':
121                 if (!path)
122                         die("git cat-file --textconv %s: <object> must be <sha1:path>",
123                             obj_name);
124
125                 if (textconv_object(the_repository, path, obj_context.mode,
126                                     &oid, 1, &buf, &size))
127                         break;
128                 /* else fallthrough */
129
130         case 'p':
131                 type = oid_object_info(the_repository, &oid, NULL);
132                 if (type < 0)
133                         die("Not a valid object name %s", obj_name);
134
135                 /* custom pretty-print here */
136                 if (type == OBJ_TREE) {
137                         const char *ls_args[3] = { NULL };
138                         ls_args[0] =  "ls-tree";
139                         ls_args[1] =  obj_name;
140                         return cmd_ls_tree(2, ls_args, NULL);
141                 }
142
143                 if (type == OBJ_BLOB)
144                         return stream_blob(&oid);
145                 buf = read_object_file(&oid, &type, &size);
146                 if (!buf)
147                         die("Cannot read object %s", obj_name);
148
149                 /* otherwise just spit out the data */
150                 break;
151
152         case 0:
153                 if (type_from_string(exp_type) == OBJ_BLOB) {
154                         struct object_id blob_oid;
155                         if (oid_object_info(the_repository, &oid, NULL) == OBJ_TAG) {
156                                 char *buffer = read_object_file(&oid, &type,
157                                                                 &size);
158                                 const char *target;
159                                 if (!skip_prefix(buffer, "object ", &target) ||
160                                     get_oid_hex(target, &blob_oid))
161                                         die("%s not a valid tag", oid_to_hex(&oid));
162                                 free(buffer);
163                         } else
164                                 oidcpy(&blob_oid, &oid);
165
166                         if (oid_object_info(the_repository, &blob_oid, NULL) == OBJ_BLOB)
167                                 return stream_blob(&blob_oid);
168                         /*
169                          * we attempted to dereference a tag to a blob
170                          * and failed; there may be new dereference
171                          * mechanisms this code is not aware of.
172                          * fall-back to the usual case.
173                          */
174                 }
175                 buf = read_object_with_reference(the_repository,
176                                                  &oid, exp_type, &size, NULL);
177                 break;
178
179         default:
180                 die("git cat-file: unknown option: %s", exp_type);
181         }
182
183         if (!buf)
184                 die("git cat-file %s: bad file", obj_name);
185
186         write_or_die(1, buf, size);
187         free(buf);
188         free(obj_context.path);
189         return 0;
190 }
191
192 struct expand_data {
193         struct object_id oid;
194         enum object_type type;
195         unsigned long size;
196         off_t disk_size;
197         const char *rest;
198         struct object_id delta_base_oid;
199
200         /*
201          * If mark_query is true, we do not expand anything, but rather
202          * just mark the object_info with items we wish to query.
203          */
204         int mark_query;
205
206         /*
207          * Whether to split the input on whitespace before feeding it to
208          * get_sha1; this is decided during the mark_query phase based on
209          * whether we have a %(rest) token in our format.
210          */
211         int split_on_whitespace;
212
213         /*
214          * After a mark_query run, this object_info is set up to be
215          * passed to oid_object_info_extended. It will point to the data
216          * elements above, so you can retrieve the response from there.
217          */
218         struct object_info info;
219
220         /*
221          * This flag will be true if the requested batch format and options
222          * don't require us to call oid_object_info, which can then be
223          * optimized out.
224          */
225         unsigned skip_object_info : 1;
226 };
227
228 static int is_atom(const char *atom, const char *s, int slen)
229 {
230         int alen = strlen(atom);
231         return alen == slen && !memcmp(atom, s, alen);
232 }
233
234 static void expand_atom(struct strbuf *sb, const char *atom, int len,
235                         void *vdata)
236 {
237         struct expand_data *data = vdata;
238
239         if (is_atom("objectname", atom, len)) {
240                 if (!data->mark_query)
241                         strbuf_addstr(sb, oid_to_hex(&data->oid));
242         } else if (is_atom("objecttype", atom, len)) {
243                 if (data->mark_query)
244                         data->info.typep = &data->type;
245                 else
246                         strbuf_addstr(sb, type_name(data->type));
247         } else if (is_atom("objectsize", atom, len)) {
248                 if (data->mark_query)
249                         data->info.sizep = &data->size;
250                 else
251                         strbuf_addf(sb, "%"PRIuMAX , (uintmax_t)data->size);
252         } else if (is_atom("objectsize:disk", atom, len)) {
253                 if (data->mark_query)
254                         data->info.disk_sizep = &data->disk_size;
255                 else
256                         strbuf_addf(sb, "%"PRIuMAX, (uintmax_t)data->disk_size);
257         } else if (is_atom("rest", atom, len)) {
258                 if (data->mark_query)
259                         data->split_on_whitespace = 1;
260                 else if (data->rest)
261                         strbuf_addstr(sb, data->rest);
262         } else if (is_atom("deltabase", atom, len)) {
263                 if (data->mark_query)
264                         data->info.delta_base_sha1 = data->delta_base_oid.hash;
265                 else
266                         strbuf_addstr(sb,
267                                       oid_to_hex(&data->delta_base_oid));
268         } else
269                 die("unknown format element: %.*s", len, atom);
270 }
271
272 static size_t expand_format(struct strbuf *sb, const char *start, void *data)
273 {
274         const char *end;
275
276         if (*start != '(')
277                 return 0;
278         end = strchr(start + 1, ')');
279         if (!end)
280                 die("format element '%s' does not end in ')'", start);
281
282         expand_atom(sb, start + 1, end - start - 1, data);
283
284         return end - start + 1;
285 }
286
287 static void batch_write(struct batch_options *opt, const void *data, int len)
288 {
289         if (opt->buffer_output) {
290                 if (fwrite(data, 1, len, stdout) != len)
291                         die_errno("unable to write to stdout");
292         } else
293                 write_or_die(1, data, len);
294 }
295
296 static void print_object_or_die(struct batch_options *opt, struct expand_data *data)
297 {
298         const struct object_id *oid = &data->oid;
299
300         assert(data->info.typep);
301
302         if (data->type == OBJ_BLOB) {
303                 if (opt->buffer_output)
304                         fflush(stdout);
305                 if (opt->cmdmode) {
306                         char *contents;
307                         unsigned long size;
308
309                         if (!data->rest)
310                                 die("missing path for '%s'", oid_to_hex(oid));
311
312                         if (opt->cmdmode == 'w') {
313                                 if (filter_object(data->rest, 0100644, oid,
314                                                   &contents, &size))
315                                         die("could not convert '%s' %s",
316                                             oid_to_hex(oid), data->rest);
317                         } else if (opt->cmdmode == 'c') {
318                                 enum object_type type;
319                                 if (!textconv_object(the_repository,
320                                                      data->rest, 0100644, oid,
321                                                      1, &contents, &size))
322                                         contents = read_object_file(oid,
323                                                                     &type,
324                                                                     &size);
325                                 if (!contents)
326                                         die("could not convert '%s' %s",
327                                             oid_to_hex(oid), data->rest);
328                         } else
329                                 BUG("invalid cmdmode: %c", opt->cmdmode);
330                         batch_write(opt, contents, size);
331                         free(contents);
332                 } else {
333                         stream_blob(oid);
334                 }
335         }
336         else {
337                 enum object_type type;
338                 unsigned long size;
339                 void *contents;
340
341                 contents = read_object_file(oid, &type, &size);
342                 if (!contents)
343                         die("object %s disappeared", oid_to_hex(oid));
344                 if (type != data->type)
345                         die("object %s changed type!?", oid_to_hex(oid));
346                 if (data->info.sizep && size != data->size)
347                         die("object %s changed size!?", oid_to_hex(oid));
348
349                 batch_write(opt, contents, size);
350                 free(contents);
351         }
352 }
353
354 static void batch_object_write(const char *obj_name,
355                                struct strbuf *scratch,
356                                struct batch_options *opt,
357                                struct expand_data *data)
358 {
359         if (!data->skip_object_info &&
360             oid_object_info_extended(the_repository, &data->oid, &data->info,
361                                      OBJECT_INFO_LOOKUP_REPLACE) < 0) {
362                 printf("%s missing\n",
363                        obj_name ? obj_name : oid_to_hex(&data->oid));
364                 fflush(stdout);
365                 return;
366         }
367
368         strbuf_reset(scratch);
369         strbuf_expand(scratch, opt->format, expand_format, data);
370         strbuf_addch(scratch, '\n');
371         batch_write(opt, scratch->buf, scratch->len);
372
373         if (opt->print_contents) {
374                 print_object_or_die(opt, data);
375                 batch_write(opt, "\n", 1);
376         }
377 }
378
379 static void batch_one_object(const char *obj_name,
380                              struct strbuf *scratch,
381                              struct batch_options *opt,
382                              struct expand_data *data)
383 {
384         struct object_context ctx;
385         int flags = opt->follow_symlinks ? GET_OID_FOLLOW_SYMLINKS : 0;
386         enum get_oid_result result;
387
388         result = get_oid_with_context(the_repository, obj_name,
389                                       flags, &data->oid, &ctx);
390         if (result != FOUND) {
391                 switch (result) {
392                 case MISSING_OBJECT:
393                         printf("%s missing\n", obj_name);
394                         break;
395                 case SHORT_NAME_AMBIGUOUS:
396                         printf("%s ambiguous\n", obj_name);
397                         break;
398                 case DANGLING_SYMLINK:
399                         printf("dangling %"PRIuMAX"\n%s\n",
400                                (uintmax_t)strlen(obj_name), obj_name);
401                         break;
402                 case SYMLINK_LOOP:
403                         printf("loop %"PRIuMAX"\n%s\n",
404                                (uintmax_t)strlen(obj_name), obj_name);
405                         break;
406                 case NOT_DIR:
407                         printf("notdir %"PRIuMAX"\n%s\n",
408                                (uintmax_t)strlen(obj_name), obj_name);
409                         break;
410                 default:
411                         BUG("unknown get_sha1_with_context result %d\n",
412                                result);
413                         break;
414                 }
415                 fflush(stdout);
416                 return;
417         }
418
419         if (ctx.mode == 0) {
420                 printf("symlink %"PRIuMAX"\n%s\n",
421                        (uintmax_t)ctx.symlink_path.len,
422                        ctx.symlink_path.buf);
423                 fflush(stdout);
424                 return;
425         }
426
427         batch_object_write(obj_name, scratch, opt, data);
428 }
429
430 struct object_cb_data {
431         struct batch_options *opt;
432         struct expand_data *expand;
433         struct oidset *seen;
434         struct strbuf *scratch;
435 };
436
437 static int batch_object_cb(const struct object_id *oid, void *vdata)
438 {
439         struct object_cb_data *data = vdata;
440         oidcpy(&data->expand->oid, oid);
441         batch_object_write(NULL, data->scratch, data->opt, data->expand);
442         return 0;
443 }
444
445 static int collect_loose_object(const struct object_id *oid,
446                                 const char *path,
447                                 void *data)
448 {
449         oid_array_append(data, oid);
450         return 0;
451 }
452
453 static int collect_packed_object(const struct object_id *oid,
454                                  struct packed_git *pack,
455                                  uint32_t pos,
456                                  void *data)
457 {
458         oid_array_append(data, oid);
459         return 0;
460 }
461
462 static int batch_unordered_object(const struct object_id *oid, void *vdata)
463 {
464         struct object_cb_data *data = vdata;
465
466         if (oidset_insert(data->seen, oid))
467                 return 0;
468
469         return batch_object_cb(oid, data);
470 }
471
472 static int batch_unordered_loose(const struct object_id *oid,
473                                  const char *path,
474                                  void *data)
475 {
476         return batch_unordered_object(oid, data);
477 }
478
479 static int batch_unordered_packed(const struct object_id *oid,
480                                   struct packed_git *pack,
481                                   uint32_t pos,
482                                   void *data)
483 {
484         return batch_unordered_object(oid, data);
485 }
486
487 static int batch_objects(struct batch_options *opt)
488 {
489         struct strbuf input = STRBUF_INIT;
490         struct strbuf output = STRBUF_INIT;
491         struct expand_data data;
492         int save_warning;
493         int retval = 0;
494
495         if (!opt->format)
496                 opt->format = "%(objectname) %(objecttype) %(objectsize)";
497
498         /*
499          * Expand once with our special mark_query flag, which will prime the
500          * object_info to be handed to oid_object_info_extended for each
501          * object.
502          */
503         memset(&data, 0, sizeof(data));
504         data.mark_query = 1;
505         strbuf_expand(&output, opt->format, expand_format, &data);
506         data.mark_query = 0;
507         strbuf_release(&output);
508         if (opt->cmdmode)
509                 data.split_on_whitespace = 1;
510
511         if (opt->all_objects) {
512                 struct object_info empty = OBJECT_INFO_INIT;
513                 if (!memcmp(&data.info, &empty, sizeof(empty)))
514                         data.skip_object_info = 1;
515         }
516
517         /*
518          * If we are printing out the object, then always fill in the type,
519          * since we will want to decide whether or not to stream.
520          */
521         if (opt->print_contents)
522                 data.info.typep = &data.type;
523
524         if (opt->all_objects) {
525                 struct object_cb_data cb;
526
527                 if (repository_format_partial_clone)
528                         warning("This repository has extensions.partialClone set. Some objects may not be loaded.");
529
530                 cb.opt = opt;
531                 cb.expand = &data;
532                 cb.scratch = &output;
533
534                 if (opt->unordered) {
535                         struct oidset seen = OIDSET_INIT;
536
537                         cb.seen = &seen;
538
539                         for_each_loose_object(batch_unordered_loose, &cb, 0);
540                         for_each_packed_object(batch_unordered_packed, &cb,
541                                                FOR_EACH_OBJECT_PACK_ORDER);
542
543                         oidset_clear(&seen);
544                 } else {
545                         struct oid_array sa = OID_ARRAY_INIT;
546
547                         for_each_loose_object(collect_loose_object, &sa, 0);
548                         for_each_packed_object(collect_packed_object, &sa, 0);
549
550                         oid_array_for_each_unique(&sa, batch_object_cb, &cb);
551
552                         oid_array_clear(&sa);
553                 }
554
555                 strbuf_release(&output);
556                 return 0;
557         }
558
559         /*
560          * We are going to call get_sha1 on a potentially very large number of
561          * objects. In most large cases, these will be actual object sha1s. The
562          * cost to double-check that each one is not also a ref (just so we can
563          * warn) ends up dwarfing the actual cost of the object lookups
564          * themselves. We can work around it by just turning off the warning.
565          */
566         save_warning = warn_on_object_refname_ambiguity;
567         warn_on_object_refname_ambiguity = 0;
568
569         while (strbuf_getline(&input, stdin) != EOF) {
570                 if (data.split_on_whitespace) {
571                         /*
572                          * Split at first whitespace, tying off the beginning
573                          * of the string and saving the remainder (or NULL) in
574                          * data.rest.
575                          */
576                         char *p = strpbrk(input.buf, " \t");
577                         if (p) {
578                                 while (*p && strchr(" \t", *p))
579                                         *p++ = '\0';
580                         }
581                         data.rest = p;
582                 }
583
584                 batch_one_object(input.buf, &output, opt, &data);
585         }
586
587         strbuf_release(&input);
588         strbuf_release(&output);
589         warn_on_object_refname_ambiguity = save_warning;
590         return retval;
591 }
592
593 static const char * const cat_file_usage[] = {
594         N_("git cat-file (-t [--allow-unknown-type] | -s [--allow-unknown-type] | -e | -p | <type> | --textconv | --filters) [--path=<path>] <object>"),
595         N_("git cat-file (--batch | --batch-check) [--follow-symlinks] [--textconv | --filters]"),
596         NULL
597 };
598
599 static int git_cat_file_config(const char *var, const char *value, void *cb)
600 {
601         if (userdiff_config(var, value) < 0)
602                 return -1;
603
604         return git_default_config(var, value, cb);
605 }
606
607 static int batch_option_callback(const struct option *opt,
608                                  const char *arg,
609                                  int unset)
610 {
611         struct batch_options *bo = opt->value;
612
613         BUG_ON_OPT_NEG(unset);
614
615         if (bo->enabled) {
616                 return error(_("only one batch option may be specified"));
617         }
618
619         bo->enabled = 1;
620         bo->print_contents = !strcmp(opt->long_name, "batch");
621         bo->format = arg;
622
623         return 0;
624 }
625
626 int cmd_cat_file(int argc, const char **argv, const char *prefix)
627 {
628         int opt = 0;
629         const char *exp_type = NULL, *obj_name = NULL;
630         struct batch_options batch = {0};
631         int unknown_type = 0;
632
633         const struct option options[] = {
634                 OPT_GROUP(N_("<type> can be one of: blob, tree, commit, tag")),
635                 OPT_CMDMODE('t', NULL, &opt, N_("show object type"), 't'),
636                 OPT_CMDMODE('s', NULL, &opt, N_("show object size"), 's'),
637                 OPT_CMDMODE('e', NULL, &opt,
638                             N_("exit with zero when there's no error"), 'e'),
639                 OPT_CMDMODE('p', NULL, &opt, N_("pretty-print object's content"), 'p'),
640                 OPT_CMDMODE(0, "textconv", &opt,
641                             N_("for blob objects, run textconv on object's content"), 'c'),
642                 OPT_CMDMODE(0, "filters", &opt,
643                             N_("for blob objects, run filters on object's content"), 'w'),
644                 OPT_STRING(0, "path", &force_path, N_("blob"),
645                            N_("use a specific path for --textconv/--filters")),
646                 OPT_BOOL(0, "allow-unknown-type", &unknown_type,
647                           N_("allow -s and -t to work with broken/corrupt objects")),
648                 OPT_BOOL(0, "buffer", &batch.buffer_output, N_("buffer --batch output")),
649                 { OPTION_CALLBACK, 0, "batch", &batch, "format",
650                         N_("show info and content of objects fed from the standard input"),
651                         PARSE_OPT_OPTARG | PARSE_OPT_NONEG,
652                         batch_option_callback },
653                 { OPTION_CALLBACK, 0, "batch-check", &batch, "format",
654                         N_("show info about objects fed from the standard input"),
655                         PARSE_OPT_OPTARG | PARSE_OPT_NONEG,
656                         batch_option_callback },
657                 OPT_BOOL(0, "follow-symlinks", &batch.follow_symlinks,
658                          N_("follow in-tree symlinks (used with --batch or --batch-check)")),
659                 OPT_BOOL(0, "batch-all-objects", &batch.all_objects,
660                          N_("show all objects with --batch or --batch-check")),
661                 OPT_BOOL(0, "unordered", &batch.unordered,
662                          N_("do not order --batch-all-objects output")),
663                 OPT_END()
664         };
665
666         git_config(git_cat_file_config, NULL);
667
668         batch.buffer_output = -1;
669         argc = parse_options(argc, argv, prefix, options, cat_file_usage, 0);
670
671         if (opt) {
672                 if (batch.enabled && (opt == 'c' || opt == 'w'))
673                         batch.cmdmode = opt;
674                 else if (argc == 1)
675                         obj_name = argv[0];
676                 else
677                         usage_with_options(cat_file_usage, options);
678         }
679         if (!opt && !batch.enabled) {
680                 if (argc == 2) {
681                         exp_type = argv[0];
682                         obj_name = argv[1];
683                 } else
684                         usage_with_options(cat_file_usage, options);
685         }
686         if (batch.enabled) {
687                 if (batch.cmdmode != opt || argc)
688                         usage_with_options(cat_file_usage, options);
689                 if (batch.cmdmode && batch.all_objects)
690                         die("--batch-all-objects cannot be combined with "
691                             "--textconv nor with --filters");
692         }
693
694         if ((batch.follow_symlinks || batch.all_objects) && !batch.enabled) {
695                 usage_with_options(cat_file_usage, options);
696         }
697
698         if (force_path && opt != 'c' && opt != 'w') {
699                 error("--path=<path> needs --textconv or --filters");
700                 usage_with_options(cat_file_usage, options);
701         }
702
703         if (force_path && batch.enabled) {
704                 error("--path=<path> incompatible with --batch");
705                 usage_with_options(cat_file_usage, options);
706         }
707
708         if (batch.buffer_output < 0)
709                 batch.buffer_output = batch.all_objects;
710
711         if (batch.enabled)
712                 return batch_objects(&batch);
713
714         if (unknown_type && opt != 't' && opt != 's')
715                 die("git cat-file --allow-unknown-type: use with -s or -t");
716         return cat_one_file(opt, exp_type, obj_name, unknown_type);
717 }