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