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