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