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