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