Merge branch 'sg/subtree-signed-commits' into pu
[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 "ref-filter.h"
17
18 struct batch_options {
19         struct ref_format format;
20         int enabled;
21         int follow_symlinks;
22         int print_contents;
23         int buffer_output;
24         int all_objects;
25         int cmdmode; /* may be 'w' or 'c' for --filters or --textconv */
26 };
27
28 static const char *force_path;
29
30 static int filter_object(const char *path, unsigned mode,
31                          const struct object_id *oid,
32                          char **buf, unsigned long *size)
33 {
34         enum object_type type;
35
36         *buf = read_sha1_file(oid->hash, &type, size);
37         if (!*buf)
38                 return error(_("cannot read object %s '%s'"),
39                              oid_to_hex(oid), path);
40         if ((type == OBJ_BLOB) && S_ISREG(mode)) {
41                 struct strbuf strbuf = STRBUF_INIT;
42                 if (convert_to_working_tree(path, *buf, *size, &strbuf)) {
43                         free(*buf);
44                         *size = strbuf.len;
45                         *buf = strbuf_detach(&strbuf, NULL);
46                 }
47         }
48
49         return 0;
50 }
51
52 static int cat_one_file(int opt, const char *exp_type, const char *obj_name,
53                         int unknown_type)
54 {
55         struct object_id oid;
56         enum object_type type;
57         char *buf;
58         unsigned long size;
59         struct object_context obj_context;
60         struct object_info oi = OBJECT_INFO_INIT;
61         struct strbuf sb = STRBUF_INIT;
62         unsigned flags = OBJECT_INFO_LOOKUP_REPLACE;
63         const char *path = force_path;
64
65         if (unknown_type)
66                 flags |= OBJECT_INFO_ALLOW_UNKNOWN_TYPE;
67
68         if (get_oid_with_context(obj_name, GET_OID_RECORD_PATH,
69                                  &oid, &obj_context))
70                 die("Not a valid object name %s", obj_name);
71
72         if (!path)
73                 path = obj_context.path;
74         if (obj_context.mode == S_IFINVALID)
75                 obj_context.mode = 0100644;
76
77         buf = NULL;
78         switch (opt) {
79         case 't':
80                 oi.type_name = &sb;
81                 if (sha1_object_info_extended(oid.hash, &oi, flags) < 0)
82                         die("git cat-file: could not get object info");
83                 if (sb.len) {
84                         printf("%s\n", sb.buf);
85                         strbuf_release(&sb);
86                         return 0;
87                 }
88                 break;
89
90         case 's':
91                 oi.sizep = &size;
92                 if (sha1_object_info_extended(oid.hash, &oi, flags) < 0)
93                         die("git cat-file: could not get object info");
94                 printf("%lu\n", size);
95                 return 0;
96
97         case 'e':
98                 return !has_object_file(&oid);
99
100         case 'w':
101                 if (!path)
102                         die("git cat-file --filters %s: <object> must be "
103                             "<sha1:path>", obj_name);
104
105                 if (filter_object(path, obj_context.mode,
106                                   &oid, &buf, &size))
107                         return -1;
108                 break;
109
110         case 'c':
111                 if (!path)
112                         die("git cat-file --textconv %s: <object> must be <sha1:path>",
113                             obj_name);
114
115                 if (textconv_object(path, obj_context.mode, &oid, 1, &buf, &size))
116                         break;
117                 /* else fallthrough */
118
119         case 'p':
120                 type = sha1_object_info(oid.hash, NULL);
121                 if (type < 0)
122                         die("Not a valid object name %s", obj_name);
123
124                 /* custom pretty-print here */
125                 if (type == OBJ_TREE) {
126                         const char *ls_args[3] = { NULL };
127                         ls_args[0] =  "ls-tree";
128                         ls_args[1] =  obj_name;
129                         return cmd_ls_tree(2, ls_args, NULL);
130                 }
131
132                 if (type == OBJ_BLOB)
133                         return stream_blob_to_fd(1, &oid, NULL, 0);
134                 buf = read_sha1_file(oid.hash, &type, &size);
135                 if (!buf)
136                         die("Cannot read object %s", obj_name);
137
138                 /* otherwise just spit out the data */
139                 break;
140
141         case 0:
142                 if (type_from_string(exp_type) == OBJ_BLOB) {
143                         struct object_id blob_oid;
144                         if (sha1_object_info(oid.hash, NULL) == OBJ_TAG) {
145                                 char *buffer = read_sha1_file(oid.hash, &type, &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 (sha1_object_info(blob_oid.hash, 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.hash, 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 static void batch_write(struct batch_options *opt, const void *data, int len)
180 {
181         if (opt->buffer_output) {
182                 if (fwrite(data, 1, len, stdout) != len)
183                         die_errno("unable to write to stdout");
184         } else
185                 write_or_die(1, data, len);
186 }
187
188 static void print_object_or_die(struct batch_options *opt, struct expand_data *data)
189 {
190         const struct object_id *oid = &data->oid;
191
192         assert(data->info.typep);
193
194         if (data->type == OBJ_BLOB) {
195                 if (opt->buffer_output)
196                         fflush(stdout);
197                 if (opt->cmdmode) {
198                         char *contents;
199                         unsigned long size;
200
201                         if (!data->rest)
202                                 die("missing path for '%s'", oid_to_hex(oid));
203
204                         if (opt->cmdmode == 'w') {
205                                 if (filter_object(data->rest, 0100644, oid,
206                                                   &contents, &size))
207                                         die("could not convert '%s' %s",
208                                             oid_to_hex(oid), data->rest);
209                         } else if (opt->cmdmode == 'c') {
210                                 enum object_type type;
211                                 if (!textconv_object(data->rest, 0100644, oid,
212                                                      1, &contents, &size))
213                                         contents = read_sha1_file(oid->hash, &type,
214                                                                   &size);
215                                 if (!contents)
216                                         die("could not convert '%s' %s",
217                                             oid_to_hex(oid), data->rest);
218                         } else
219                                 die("BUG: invalid cmdmode: %c", opt->cmdmode);
220                         batch_write(opt, contents, size);
221                         free(contents);
222                 } else if (stream_blob_to_fd(1, oid, NULL, 0) < 0)
223                         die("unable to stream %s to stdout", oid_to_hex(oid));
224         }
225         else {
226                 enum object_type type;
227                 unsigned long size;
228                 void *contents;
229
230                 contents = read_sha1_file(oid->hash, &type, &size);
231                 if (!contents)
232                         die("object %s disappeared", oid_to_hex(oid));
233                 if (type != data->type)
234                         die("object %s changed type!?", oid_to_hex(oid));
235                 if (data->info.sizep && size != data->size)
236                         die("object %s changed size!?", oid_to_hex(oid));
237
238                 batch_write(opt, contents, size);
239                 free(contents);
240         }
241 }
242
243 static void batch_object_write(const char *obj_name, struct batch_options *opt,
244                                struct expand_data *data)
245 {
246         struct ref_array_item item = {0};
247
248         item.oid = data->oid;
249         item.rest = data->rest;
250         item.objectname = obj_name;
251
252         if (show_ref_array_item(&item, &opt->format))
253                 return;
254         if (!opt->buffer_output)
255                 fflush(stdout);
256
257         if (opt->print_contents) {
258                 data->type = item.type;
259                 print_object_or_die(opt, data);
260                 batch_write(opt, "\n", 1);
261         }
262 }
263
264 static void batch_one_object(const char *obj_name, struct batch_options *opt,
265                              struct expand_data *data)
266 {
267         struct object_context ctx;
268         int flags = opt->follow_symlinks ? GET_OID_FOLLOW_SYMLINKS : 0;
269         enum follow_symlinks_result result;
270
271         result = get_oid_with_context(obj_name, flags, &data->oid, &ctx);
272         if (result != FOUND) {
273                 switch (result) {
274                 case MISSING_OBJECT:
275                         printf("%s missing\n", obj_name);
276                         break;
277                 case DANGLING_SYMLINK:
278                         printf("dangling %"PRIuMAX"\n%s\n",
279                                (uintmax_t)strlen(obj_name), obj_name);
280                         break;
281                 case SYMLINK_LOOP:
282                         printf("loop %"PRIuMAX"\n%s\n",
283                                (uintmax_t)strlen(obj_name), obj_name);
284                         break;
285                 case NOT_DIR:
286                         printf("notdir %"PRIuMAX"\n%s\n",
287                                (uintmax_t)strlen(obj_name), obj_name);
288                         break;
289                 default:
290                         die("BUG: unknown get_sha1_with_context result %d\n",
291                                result);
292                         break;
293                 }
294                 fflush(stdout);
295                 return;
296         }
297
298         if (ctx.mode == 0) {
299                 printf("symlink %"PRIuMAX"\n%s\n",
300                        (uintmax_t)ctx.symlink_path.len,
301                        ctx.symlink_path.buf);
302                 fflush(stdout);
303                 return;
304         }
305
306         batch_object_write(obj_name, opt, data);
307 }
308
309 struct object_cb_data {
310         struct batch_options *opt;
311         struct expand_data *expand;
312 };
313
314 static int batch_object_cb(const struct object_id *oid, void *vdata)
315 {
316         struct object_cb_data *data = vdata;
317         oidcpy(&data->expand->oid, oid);
318         batch_object_write(NULL, data->opt, data->expand);
319         return 0;
320 }
321
322 static int batch_loose_object(const struct object_id *oid,
323                               const char *path,
324                               void *data)
325 {
326         oid_array_append(data, oid);
327         return 0;
328 }
329
330 static int batch_packed_object(const struct object_id *oid,
331                                struct packed_git *pack,
332                                uint32_t pos,
333                                void *data)
334 {
335         oid_array_append(data, oid);
336         return 0;
337 }
338
339 static int batch_objects(struct batch_options *opt)
340 {
341         struct strbuf buf = STRBUF_INIT;
342         struct expand_data data;
343         int save_warning, is_rest, retval = 0;
344
345         if (!opt->format.format)
346                 opt->format.format = "%(objectname) %(objecttype) %(objectsize)";
347
348         /*
349          * Call verify_ref_format to prepare object_info to be handed to
350          * sha1_object_info_extended for each object.
351          */
352         memset(&data, 0, sizeof(data));
353         opt->format.is_cat_file = 1;
354         opt->format.all_objects = opt->all_objects;
355         verify_ref_format(&opt->format);
356
357         /*
358          * If we are printing out the object, then always fill in the type,
359          * since we will want to decide whether or not to stream.
360          */
361         if (opt->print_contents)
362                 data.info.typep = &data.type;
363
364         if (opt->all_objects) {
365                 struct oid_array sa = OID_ARRAY_INIT;
366                 struct object_cb_data cb;
367
368                 for_each_loose_object(batch_loose_object, &sa, 0);
369                 for_each_packed_object(batch_packed_object, &sa, 0);
370                 if (repository_format_partial_clone)
371                         warning("This repository has extensions.partialClone set. Some objects may not be loaded.");
372
373                 cb.opt = opt;
374                 cb.expand = &data;
375                 oid_array_for_each_unique(&sa, batch_object_cb, &cb);
376
377                 oid_array_clear(&sa);
378                 return 0;
379         }
380
381         /*
382          * We are going to call get_sha1 on a potentially very large number of
383          * objects. In most large cases, these will be actual object sha1s. The
384          * cost to double-check that each one is not also a ref (just so we can
385          * warn) ends up dwarfing the actual cost of the object lookups
386          * themselves. We can work around it by just turning off the warning.
387          */
388         save_warning = warn_on_object_refname_ambiguity;
389         warn_on_object_refname_ambiguity = 0;
390         is_rest = opt->cmdmode || is_atom_used(&opt->format, "rest");
391
392         while (strbuf_getline(&buf, stdin) != EOF) {
393                 if (is_rest) {
394                         /*
395                          * Split at first whitespace, tying off the beginning
396                          * of the string and saving the remainder (or NULL) in
397                          * data.rest.
398                          */
399                         char *p = strpbrk(buf.buf, " \t");
400                         if (p) {
401                                 while (*p && strchr(" \t", *p))
402                                         *p++ = '\0';
403                         }
404                         data.rest = p;
405                 }
406
407                 batch_one_object(buf.buf, opt, &data);
408         }
409
410         strbuf_release(&buf);
411         warn_on_object_refname_ambiguity = save_warning;
412         return retval;
413 }
414
415 static const char * const cat_file_usage[] = {
416         N_("git cat-file (-t [--allow-unknown-type] | -s [--allow-unknown-type] | -e | -p | <type> | --textconv | --filters) [--path=<path>] <object>"),
417         N_("git cat-file (--batch | --batch-check) [--follow-symlinks] [--textconv | --filters]"),
418         NULL
419 };
420
421 static int git_cat_file_config(const char *var, const char *value, void *cb)
422 {
423         if (userdiff_config(var, value) < 0)
424                 return -1;
425
426         return git_default_config(var, value, cb);
427 }
428
429 static int batch_option_callback(const struct option *opt,
430                                  const char *arg,
431                                  int unset)
432 {
433         struct batch_options *bo = opt->value;
434
435         if (bo->enabled) {
436                 return 1;
437         }
438
439         bo->enabled = 1;
440         bo->print_contents = !strcmp(opt->long_name, "batch");
441         bo->format.format = arg;
442
443         return 0;
444 }
445
446 int cmd_cat_file(int argc, const char **argv, const char *prefix)
447 {
448         int opt = 0;
449         const char *exp_type = NULL, *obj_name = NULL;
450         struct batch_options batch = { REF_FORMAT_INIT };
451         int unknown_type = 0;
452
453         const struct option options[] = {
454                 OPT_GROUP(N_("<type> can be one of: blob, tree, commit, tag")),
455                 OPT_CMDMODE('t', NULL, &opt, N_("show object type"), 't'),
456                 OPT_CMDMODE('s', NULL, &opt, N_("show object size"), 's'),
457                 OPT_CMDMODE('e', NULL, &opt,
458                             N_("exit with zero when there's no error"), 'e'),
459                 OPT_CMDMODE('p', NULL, &opt, N_("pretty-print object's content"), 'p'),
460                 OPT_CMDMODE(0, "textconv", &opt,
461                             N_("for blob objects, run textconv on object's content"), 'c'),
462                 OPT_CMDMODE(0, "filters", &opt,
463                             N_("for blob objects, run filters on object's content"), 'w'),
464                 OPT_STRING(0, "path", &force_path, N_("blob"),
465                            N_("use a specific path for --textconv/--filters")),
466                 OPT_BOOL(0, "allow-unknown-type", &unknown_type,
467                           N_("allow -s and -t to work with broken/corrupt objects")),
468                 OPT_BOOL(0, "buffer", &batch.buffer_output, N_("buffer --batch output")),
469                 { OPTION_CALLBACK, 0, "batch", &batch, "format",
470                         N_("show info and content of objects fed from the standard input"),
471                         PARSE_OPT_OPTARG, batch_option_callback },
472                 { OPTION_CALLBACK, 0, "batch-check", &batch, "format",
473                         N_("show info about objects fed from the standard input"),
474                         PARSE_OPT_OPTARG, batch_option_callback },
475                 OPT_BOOL(0, "follow-symlinks", &batch.follow_symlinks,
476                          N_("follow in-tree symlinks (used with --batch or --batch-check)")),
477                 OPT_BOOL(0, "batch-all-objects", &batch.all_objects,
478                          N_("show all objects with --batch or --batch-check")),
479                 OPT_END()
480         };
481
482         git_config(git_cat_file_config, NULL);
483
484         batch.buffer_output = -1;
485         argc = parse_options(argc, argv, prefix, options, cat_file_usage, 0);
486
487         if (opt) {
488                 if (batch.enabled && (opt == 'c' || opt == 'w'))
489                         batch.cmdmode = opt;
490                 else if (argc == 1)
491                         obj_name = argv[0];
492                 else
493                         usage_with_options(cat_file_usage, options);
494         }
495         if (!opt && !batch.enabled) {
496                 if (argc == 2) {
497                         exp_type = argv[0];
498                         obj_name = argv[1];
499                 } else
500                         usage_with_options(cat_file_usage, options);
501         }
502         if (batch.enabled) {
503                 if (batch.cmdmode != opt || argc)
504                         usage_with_options(cat_file_usage, options);
505                 if (batch.cmdmode && batch.all_objects)
506                         die("--batch-all-objects cannot be combined with "
507                             "--textconv nor with --filters");
508         }
509
510         if ((batch.follow_symlinks || batch.all_objects) && !batch.enabled) {
511                 usage_with_options(cat_file_usage, options);
512         }
513
514         if (force_path && opt != 'c' && opt != 'w') {
515                 error("--path=<path> needs --textconv or --filters");
516                 usage_with_options(cat_file_usage, options);
517         }
518
519         if (force_path && batch.enabled) {
520                 error("--path=<path> incompatible with --batch");
521                 usage_with_options(cat_file_usage, options);
522         }
523
524         if (batch.buffer_output < 0)
525                 batch.buffer_output = batch.all_objects;
526
527         if (batch.enabled)
528                 return batch_objects(&batch);
529
530         if (unknown_type && opt != 't' && opt != 's')
531                 die("git cat-file --allow-unknown-type: use with -s or -t");
532         return cat_one_file(opt, exp_type, obj_name, unknown_type);
533 }