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