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