f7e388490a3647172ddb8f1bb21db56d67c61e66
   1#include "cache.h"
   2#include "tag.h"
   3#include "commit.h"
   4#include "tree.h"
   5#include "blob.h"
   6#include "tree-walk.h"
   7#include "refs.h"
   8#include "remote.h"
   9#include "dir.h"
  10#include "sha1-array.h"
  11
  12static int get_sha1_oneline(const char *, unsigned char *, struct commit_list *);
  13
  14typedef int (*disambiguate_hint_fn)(const unsigned char *, void *);
  15
  16struct disambiguate_state {
  17        int len; /* length of prefix in hex chars */
  18        char hex_pfx[GIT_SHA1_HEXSZ + 1];
  19        unsigned char bin_pfx[GIT_SHA1_RAWSZ];
  20
  21        disambiguate_hint_fn fn;
  22        void *cb_data;
  23        unsigned char candidate[GIT_SHA1_RAWSZ];
  24        unsigned candidate_exists:1;
  25        unsigned candidate_checked:1;
  26        unsigned candidate_ok:1;
  27        unsigned disambiguate_fn_used:1;
  28        unsigned ambiguous:1;
  29        unsigned always_call_fn:1;
  30};
  31
  32static void update_candidates(struct disambiguate_state *ds, const unsigned char *current)
  33{
  34        if (ds->always_call_fn) {
  35                ds->ambiguous = ds->fn(current, ds->cb_data) ? 1 : 0;
  36                return;
  37        }
  38        if (!ds->candidate_exists) {
  39                /* this is the first candidate */
  40                hashcpy(ds->candidate, current);
  41                ds->candidate_exists = 1;
  42                return;
  43        } else if (!hashcmp(ds->candidate, current)) {
  44                /* the same as what we already have seen */
  45                return;
  46        }
  47
  48        if (!ds->fn) {
  49                /* cannot disambiguate between ds->candidate and current */
  50                ds->ambiguous = 1;
  51                return;
  52        }
  53
  54        if (!ds->candidate_checked) {
  55                ds->candidate_ok = ds->fn(ds->candidate, ds->cb_data);
  56                ds->disambiguate_fn_used = 1;
  57                ds->candidate_checked = 1;
  58        }
  59
  60        if (!ds->candidate_ok) {
  61                /* discard the candidate; we know it does not satisfy fn */
  62                hashcpy(ds->candidate, current);
  63                ds->candidate_checked = 0;
  64                return;
  65        }
  66
  67        /* if we reach this point, we know ds->candidate satisfies fn */
  68        if (ds->fn(current, ds->cb_data)) {
  69                /*
  70                 * if both current and candidate satisfy fn, we cannot
  71                 * disambiguate.
  72                 */
  73                ds->candidate_ok = 0;
  74                ds->ambiguous = 1;
  75        }
  76
  77        /* otherwise, current can be discarded and candidate is still good */
  78}
  79
  80static void find_short_object_filename(struct disambiguate_state *ds)
  81{
  82        struct alternate_object_database *alt;
  83        char hex[GIT_SHA1_HEXSZ];
  84        static struct alternate_object_database *fakeent;
  85
  86        if (!fakeent) {
  87                /*
  88                 * Create a "fake" alternate object database that
  89                 * points to our own object database, to make it
  90                 * easier to get a temporary working space in
  91                 * alt->name/alt->base while iterating over the
  92                 * object databases including our own.
  93                 */
  94                const char *objdir = get_object_directory();
  95                size_t objdir_len = strlen(objdir);
  96                fakeent = xmalloc(st_add3(sizeof(*fakeent), objdir_len, 43));
  97                memcpy(fakeent->base, objdir, objdir_len);
  98                fakeent->name = fakeent->base + objdir_len + 1;
  99                fakeent->name[-1] = '/';
 100        }
 101        fakeent->next = alt_odb_list;
 102
 103        xsnprintf(hex, sizeof(hex), "%.2s", ds->hex_pfx);
 104        for (alt = fakeent; alt && !ds->ambiguous; alt = alt->next) {
 105                struct dirent *de;
 106                DIR *dir;
 107                /*
 108                 * every alt_odb struct has 42 extra bytes after the base
 109                 * for exactly this purpose
 110                 */
 111                xsnprintf(alt->name, 42, "%.2s/", ds->hex_pfx);
 112                dir = opendir(alt->base);
 113                if (!dir)
 114                        continue;
 115
 116                while (!ds->ambiguous && (de = readdir(dir)) != NULL) {
 117                        unsigned char sha1[20];
 118
 119                        if (strlen(de->d_name) != 38)
 120                                continue;
 121                        if (memcmp(de->d_name, ds->hex_pfx + 2, ds->len - 2))
 122                                continue;
 123                        memcpy(hex + 2, de->d_name, 38);
 124                        if (!get_sha1_hex(hex, sha1))
 125                                update_candidates(ds, sha1);
 126                }
 127                closedir(dir);
 128        }
 129}
 130
 131static int match_sha(unsigned len, const unsigned char *a, const unsigned char *b)
 132{
 133        do {
 134                if (*a != *b)
 135                        return 0;
 136                a++;
 137                b++;
 138                len -= 2;
 139        } while (len > 1);
 140        if (len)
 141                if ((*a ^ *b) & 0xf0)
 142                        return 0;
 143        return 1;
 144}
 145
 146static void unique_in_pack(struct packed_git *p,
 147                           struct disambiguate_state *ds)
 148{
 149        uint32_t num, last, i, first = 0;
 150        const unsigned char *current = NULL;
 151
 152        open_pack_index(p);
 153        num = p->num_objects;
 154        last = num;
 155        while (first < last) {
 156                uint32_t mid = (first + last) / 2;
 157                const unsigned char *current;
 158                int cmp;
 159
 160                current = nth_packed_object_sha1(p, mid);
 161                cmp = hashcmp(ds->bin_pfx, current);
 162                if (!cmp) {
 163                        first = mid;
 164                        break;
 165                }
 166                if (cmp > 0) {
 167                        first = mid+1;
 168                        continue;
 169                }
 170                last = mid;
 171        }
 172
 173        /*
 174         * At this point, "first" is the location of the lowest object
 175         * with an object name that could match "bin_pfx".  See if we have
 176         * 0, 1 or more objects that actually match(es).
 177         */
 178        for (i = first; i < num && !ds->ambiguous; i++) {
 179                current = nth_packed_object_sha1(p, i);
 180                if (!match_sha(ds->len, ds->bin_pfx, current))
 181                        break;
 182                update_candidates(ds, current);
 183        }
 184}
 185
 186static void find_short_packed_object(struct disambiguate_state *ds)
 187{
 188        struct packed_git *p;
 189
 190        prepare_packed_git();
 191        for (p = packed_git; p && !ds->ambiguous; p = p->next)
 192                unique_in_pack(p, ds);
 193}
 194
 195#define SHORT_NAME_NOT_FOUND (-1)
 196#define SHORT_NAME_AMBIGUOUS (-2)
 197
 198static int finish_object_disambiguation(struct disambiguate_state *ds,
 199                                        unsigned char *sha1)
 200{
 201        if (ds->ambiguous)
 202                return SHORT_NAME_AMBIGUOUS;
 203
 204        if (!ds->candidate_exists)
 205                return SHORT_NAME_NOT_FOUND;
 206
 207        if (!ds->candidate_checked)
 208                /*
 209                 * If this is the only candidate, there is no point
 210                 * calling the disambiguation hint callback.
 211                 *
 212                 * On the other hand, if the current candidate
 213                 * replaced an earlier candidate that did _not_ pass
 214                 * the disambiguation hint callback, then we do have
 215                 * more than one objects that match the short name
 216                 * given, so we should make sure this one matches;
 217                 * otherwise, if we discovered this one and the one
 218                 * that we previously discarded in the reverse order,
 219                 * we would end up showing different results in the
 220                 * same repository!
 221                 */
 222                ds->candidate_ok = (!ds->disambiguate_fn_used ||
 223                                    ds->fn(ds->candidate, ds->cb_data));
 224
 225        if (!ds->candidate_ok)
 226                return SHORT_NAME_AMBIGUOUS;
 227
 228        hashcpy(sha1, ds->candidate);
 229        return 0;
 230}
 231
 232static int disambiguate_commit_only(const unsigned char *sha1, void *cb_data_unused)
 233{
 234        int kind = sha1_object_info(sha1, NULL);
 235        return kind == OBJ_COMMIT;
 236}
 237
 238static int disambiguate_committish_only(const unsigned char *sha1, void *cb_data_unused)
 239{
 240        struct object *obj;
 241        int kind;
 242
 243        kind = sha1_object_info(sha1, NULL);
 244        if (kind == OBJ_COMMIT)
 245                return 1;
 246        if (kind != OBJ_TAG)
 247                return 0;
 248
 249        /* We need to do this the hard way... */
 250        obj = deref_tag(parse_object(sha1), NULL, 0);
 251        if (obj && obj->type == OBJ_COMMIT)
 252                return 1;
 253        return 0;
 254}
 255
 256static int disambiguate_tree_only(const unsigned char *sha1, void *cb_data_unused)
 257{
 258        int kind = sha1_object_info(sha1, NULL);
 259        return kind == OBJ_TREE;
 260}
 261
 262static int disambiguate_treeish_only(const unsigned char *sha1, void *cb_data_unused)
 263{
 264        struct object *obj;
 265        int kind;
 266
 267        kind = sha1_object_info(sha1, NULL);
 268        if (kind == OBJ_TREE || kind == OBJ_COMMIT)
 269                return 1;
 270        if (kind != OBJ_TAG)
 271                return 0;
 272
 273        /* We need to do this the hard way... */
 274        obj = deref_tag(parse_object(sha1), NULL, 0);
 275        if (obj && (obj->type == OBJ_TREE || obj->type == OBJ_COMMIT))
 276                return 1;
 277        return 0;
 278}
 279
 280static int disambiguate_blob_only(const unsigned char *sha1, void *cb_data_unused)
 281{
 282        int kind = sha1_object_info(sha1, NULL);
 283        return kind == OBJ_BLOB;
 284}
 285
 286static int init_object_disambiguation(const char *name, int len,
 287                                      struct disambiguate_state *ds)
 288{
 289        int i;
 290
 291        if (len < MINIMUM_ABBREV || len > GIT_SHA1_HEXSZ)
 292                return -1;
 293
 294        memset(ds, 0, sizeof(*ds));
 295
 296        for (i = 0; i < len ;i++) {
 297                unsigned char c = name[i];
 298                unsigned char val;
 299                if (c >= '0' && c <= '9')
 300                        val = c - '0';
 301                else if (c >= 'a' && c <= 'f')
 302                        val = c - 'a' + 10;
 303                else if (c >= 'A' && c <='F') {
 304                        val = c - 'A' + 10;
 305                        c -= 'A' - 'a';
 306                }
 307                else
 308                        return -1;
 309                ds->hex_pfx[i] = c;
 310                if (!(i & 1))
 311                        val <<= 4;
 312                ds->bin_pfx[i >> 1] |= val;
 313        }
 314
 315        ds->len = len;
 316        ds->hex_pfx[len] = '\0';
 317        prepare_alt_odb();
 318        return 0;
 319}
 320
 321static int get_short_sha1(const char *name, int len, unsigned char *sha1,
 322                          unsigned flags)
 323{
 324        int status;
 325        struct disambiguate_state ds;
 326        int quietly = !!(flags & GET_SHA1_QUIETLY);
 327
 328        if (init_object_disambiguation(name, len, &ds) < 0)
 329                return -1;
 330
 331        if (HAS_MULTI_BITS(flags & GET_SHA1_DISAMBIGUATORS))
 332                die("BUG: multiple get_short_sha1 disambiguator flags");
 333
 334        if (flags & GET_SHA1_COMMIT)
 335                ds.fn = disambiguate_commit_only;
 336        else if (flags & GET_SHA1_COMMITTISH)
 337                ds.fn = disambiguate_committish_only;
 338        else if (flags & GET_SHA1_TREE)
 339                ds.fn = disambiguate_tree_only;
 340        else if (flags & GET_SHA1_TREEISH)
 341                ds.fn = disambiguate_treeish_only;
 342        else if (flags & GET_SHA1_BLOB)
 343                ds.fn = disambiguate_blob_only;
 344
 345        find_short_object_filename(&ds);
 346        find_short_packed_object(&ds);
 347        status = finish_object_disambiguation(&ds, sha1);
 348
 349        if (!quietly && (status == SHORT_NAME_AMBIGUOUS))
 350                return error(_("short SHA1 %s is ambiguous"), ds.hex_pfx);
 351        return status;
 352}
 353
 354static int collect_ambiguous(const unsigned char *sha1, void *data)
 355{
 356        sha1_array_append(data, sha1);
 357        return 0;
 358}
 359
 360int for_each_abbrev(const char *prefix, each_abbrev_fn fn, void *cb_data)
 361{
 362        struct sha1_array collect = SHA1_ARRAY_INIT;
 363        struct disambiguate_state ds;
 364        int ret;
 365
 366        if (init_object_disambiguation(prefix, strlen(prefix), &ds) < 0)
 367                return -1;
 368
 369        ds.always_call_fn = 1;
 370        ds.fn = collect_ambiguous;
 371        ds.cb_data = &collect;
 372        find_short_object_filename(&ds);
 373        find_short_packed_object(&ds);
 374
 375        ret = sha1_array_for_each_unique(&collect, fn, cb_data);
 376        sha1_array_clear(&collect);
 377        return ret;
 378}
 379
 380int find_unique_abbrev_r(char *hex, const unsigned char *sha1, int len)
 381{
 382        int status, exists;
 383
 384        sha1_to_hex_r(hex, sha1);
 385        if (len == 40 || !len)
 386                return 40;
 387        exists = has_sha1_file(sha1);
 388        while (len < 40) {
 389                unsigned char sha1_ret[20];
 390                status = get_short_sha1(hex, len, sha1_ret, GET_SHA1_QUIETLY);
 391                if (exists
 392                    ? !status
 393                    : status == SHORT_NAME_NOT_FOUND) {
 394                        hex[len] = 0;
 395                        return len;
 396                }
 397                len++;
 398        }
 399        return len;
 400}
 401
 402const char *find_unique_abbrev(const unsigned char *sha1, int len)
 403{
 404        static char hex[GIT_SHA1_HEXSZ + 1];
 405        find_unique_abbrev_r(hex, sha1, len);
 406        return hex;
 407}
 408
 409static int ambiguous_path(const char *path, int len)
 410{
 411        int slash = 1;
 412        int cnt;
 413
 414        for (cnt = 0; cnt < len; cnt++) {
 415                switch (*path++) {
 416                case '\0':
 417                        break;
 418                case '/':
 419                        if (slash)
 420                                break;
 421                        slash = 1;
 422                        continue;
 423                case '.':
 424                        continue;
 425                default:
 426                        slash = 0;
 427                        continue;
 428                }
 429                break;
 430        }
 431        return slash;
 432}
 433
 434static inline int at_mark(const char *string, int len,
 435                          const char **suffix, int nr)
 436{
 437        int i;
 438
 439        for (i = 0; i < nr; i++) {
 440                int suffix_len = strlen(suffix[i]);
 441                if (suffix_len <= len
 442                    && !memcmp(string, suffix[i], suffix_len))
 443                        return suffix_len;
 444        }
 445        return 0;
 446}
 447
 448static inline int upstream_mark(const char *string, int len)
 449{
 450        const char *suffix[] = { "@{upstream}", "@{u}" };
 451        return at_mark(string, len, suffix, ARRAY_SIZE(suffix));
 452}
 453
 454static inline int push_mark(const char *string, int len)
 455{
 456        const char *suffix[] = { "@{push}" };
 457        return at_mark(string, len, suffix, ARRAY_SIZE(suffix));
 458}
 459
 460static int get_sha1_1(const char *name, int len, unsigned char *sha1, unsigned lookup_flags);
 461static int interpret_nth_prior_checkout(const char *name, int namelen, struct strbuf *buf);
 462
 463static int get_sha1_basic(const char *str, int len, unsigned char *sha1,
 464                          unsigned int flags)
 465{
 466        static const char *warn_msg = "refname '%.*s' is ambiguous.";
 467        static const char *object_name_msg = N_(
 468        "Git normally never creates a ref that ends with 40 hex characters\n"
 469        "because it will be ignored when you just specify 40-hex. These refs\n"
 470        "may be created by mistake. For example,\n"
 471        "\n"
 472        "  git checkout -b $br $(git rev-parse ...)\n"
 473        "\n"
 474        "where \"$br\" is somehow empty and a 40-hex ref is created. Please\n"
 475        "examine these refs and maybe delete them. Turn this message off by\n"
 476        "running \"git config advice.objectNameWarning false\"");
 477        unsigned char tmp_sha1[20];
 478        char *real_ref = NULL;
 479        int refs_found = 0;
 480        int at, reflog_len, nth_prior = 0;
 481
 482        if (len == 40 && !get_sha1_hex(str, sha1)) {
 483                if (warn_ambiguous_refs && warn_on_object_refname_ambiguity) {
 484                        refs_found = dwim_ref(str, len, tmp_sha1, &real_ref);
 485                        if (refs_found > 0) {
 486                                warning(warn_msg, len, str);
 487                                if (advice_object_name_warning)
 488                                        fprintf(stderr, "%s\n", _(object_name_msg));
 489                        }
 490                        free(real_ref);
 491                }
 492                return 0;
 493        }
 494
 495        /* basic@{time or number or -number} format to query ref-log */
 496        reflog_len = at = 0;
 497        if (len && str[len-1] == '}') {
 498                for (at = len-4; at >= 0; at--) {
 499                        if (str[at] == '@' && str[at+1] == '{') {
 500                                if (str[at+2] == '-') {
 501                                        if (at != 0)
 502                                                /* @{-N} not at start */
 503                                                return -1;
 504                                        nth_prior = 1;
 505                                        continue;
 506                                }
 507                                if (!upstream_mark(str + at, len - at) &&
 508                                    !push_mark(str + at, len - at)) {
 509                                        reflog_len = (len-1) - (at+2);
 510                                        len = at;
 511                                }
 512                                break;
 513                        }
 514                }
 515        }
 516
 517        /* Accept only unambiguous ref paths. */
 518        if (len && ambiguous_path(str, len))
 519                return -1;
 520
 521        if (nth_prior) {
 522                struct strbuf buf = STRBUF_INIT;
 523                int detached;
 524
 525                if (interpret_nth_prior_checkout(str, len, &buf) > 0) {
 526                        detached = (buf.len == 40 && !get_sha1_hex(buf.buf, sha1));
 527                        strbuf_release(&buf);
 528                        if (detached)
 529                                return 0;
 530                }
 531        }
 532
 533        if (!len && reflog_len)
 534                /* allow "@{...}" to mean the current branch reflog */
 535                refs_found = dwim_ref("HEAD", 4, sha1, &real_ref);
 536        else if (reflog_len)
 537                refs_found = dwim_log(str, len, sha1, &real_ref);
 538        else
 539                refs_found = dwim_ref(str, len, sha1, &real_ref);
 540
 541        if (!refs_found)
 542                return -1;
 543
 544        if (warn_ambiguous_refs && !(flags & GET_SHA1_QUIETLY) &&
 545            (refs_found > 1 ||
 546             !get_short_sha1(str, len, tmp_sha1, GET_SHA1_QUIETLY)))
 547                warning(warn_msg, len, str);
 548
 549        if (reflog_len) {
 550                int nth, i;
 551                unsigned long at_time;
 552                unsigned long co_time;
 553                int co_tz, co_cnt;
 554
 555                /* Is it asking for N-th entry, or approxidate? */
 556                for (i = nth = 0; 0 <= nth && i < reflog_len; i++) {
 557                        char ch = str[at+2+i];
 558                        if ('0' <= ch && ch <= '9')
 559                                nth = nth * 10 + ch - '0';
 560                        else
 561                                nth = -1;
 562                }
 563                if (100000000 <= nth) {
 564                        at_time = nth;
 565                        nth = -1;
 566                } else if (0 <= nth)
 567                        at_time = 0;
 568                else {
 569                        int errors = 0;
 570                        char *tmp = xstrndup(str + at + 2, reflog_len);
 571                        at_time = approxidate_careful(tmp, &errors);
 572                        free(tmp);
 573                        if (errors) {
 574                                free(real_ref);
 575                                return -1;
 576                        }
 577                }
 578                if (read_ref_at(real_ref, flags, at_time, nth, sha1, NULL,
 579                                &co_time, &co_tz, &co_cnt)) {
 580                        if (!len) {
 581                                if (starts_with(real_ref, "refs/heads/")) {
 582                                        str = real_ref + 11;
 583                                        len = strlen(real_ref + 11);
 584                                } else {
 585                                        /* detached HEAD */
 586                                        str = "HEAD";
 587                                        len = 4;
 588                                }
 589                        }
 590                        if (at_time) {
 591                                if (!(flags & GET_SHA1_QUIETLY)) {
 592                                        warning("Log for '%.*s' only goes "
 593                                                "back to %s.", len, str,
 594                                                show_date(co_time, co_tz, DATE_MODE(RFC2822)));
 595                                }
 596                        } else {
 597                                if (flags & GET_SHA1_QUIETLY) {
 598                                        exit(128);
 599                                }
 600                                die("Log for '%.*s' only has %d entries.",
 601                                    len, str, co_cnt);
 602                        }
 603                }
 604        }
 605
 606        free(real_ref);
 607        return 0;
 608}
 609
 610static int get_parent(const char *name, int len,
 611                      unsigned char *result, int idx)
 612{
 613        unsigned char sha1[20];
 614        int ret = get_sha1_1(name, len, sha1, GET_SHA1_COMMITTISH);
 615        struct commit *commit;
 616        struct commit_list *p;
 617
 618        if (ret)
 619                return ret;
 620        commit = lookup_commit_reference(sha1);
 621        if (parse_commit(commit))
 622                return -1;
 623        if (!idx) {
 624                hashcpy(result, commit->object.oid.hash);
 625                return 0;
 626        }
 627        p = commit->parents;
 628        while (p) {
 629                if (!--idx) {
 630                        hashcpy(result, p->item->object.oid.hash);
 631                        return 0;
 632                }
 633                p = p->next;
 634        }
 635        return -1;
 636}
 637
 638static int get_nth_ancestor(const char *name, int len,
 639                            unsigned char *result, int generation)
 640{
 641        unsigned char sha1[20];
 642        struct commit *commit;
 643        int ret;
 644
 645        ret = get_sha1_1(name, len, sha1, GET_SHA1_COMMITTISH);
 646        if (ret)
 647                return ret;
 648        commit = lookup_commit_reference(sha1);
 649        if (!commit)
 650                return -1;
 651
 652        while (generation--) {
 653                if (parse_commit(commit) || !commit->parents)
 654                        return -1;
 655                commit = commit->parents->item;
 656        }
 657        hashcpy(result, commit->object.oid.hash);
 658        return 0;
 659}
 660
 661struct object *peel_to_type(const char *name, int namelen,
 662                            struct object *o, enum object_type expected_type)
 663{
 664        if (name && !namelen)
 665                namelen = strlen(name);
 666        while (1) {
 667                if (!o || (!o->parsed && !parse_object(o->oid.hash)))
 668                        return NULL;
 669                if (expected_type == OBJ_ANY || o->type == expected_type)
 670                        return o;
 671                if (o->type == OBJ_TAG)
 672                        o = ((struct tag*) o)->tagged;
 673                else if (o->type == OBJ_COMMIT)
 674                        o = &(((struct commit *) o)->tree->object);
 675                else {
 676                        if (name)
 677                                error("%.*s: expected %s type, but the object "
 678                                      "dereferences to %s type",
 679                                      namelen, name, typename(expected_type),
 680                                      typename(o->type));
 681                        return NULL;
 682                }
 683        }
 684}
 685
 686static int peel_onion(const char *name, int len, unsigned char *sha1,
 687                      unsigned lookup_flags)
 688{
 689        unsigned char outer[20];
 690        const char *sp;
 691        unsigned int expected_type = 0;
 692        struct object *o;
 693
 694        /*
 695         * "ref^{type}" dereferences ref repeatedly until you cannot
 696         * dereference anymore, or you get an object of given type,
 697         * whichever comes first.  "ref^{}" means just dereference
 698         * tags until you get a non-tag.  "ref^0" is a shorthand for
 699         * "ref^{commit}".  "commit^{tree}" could be used to find the
 700         * top-level tree of the given commit.
 701         */
 702        if (len < 4 || name[len-1] != '}')
 703                return -1;
 704
 705        for (sp = name + len - 1; name <= sp; sp--) {
 706                int ch = *sp;
 707                if (ch == '{' && name < sp && sp[-1] == '^')
 708                        break;
 709        }
 710        if (sp <= name)
 711                return -1;
 712
 713        sp++; /* beginning of type name, or closing brace for empty */
 714        if (starts_with(sp, "commit}"))
 715                expected_type = OBJ_COMMIT;
 716        else if (starts_with(sp, "tag}"))
 717                expected_type = OBJ_TAG;
 718        else if (starts_with(sp, "tree}"))
 719                expected_type = OBJ_TREE;
 720        else if (starts_with(sp, "blob}"))
 721                expected_type = OBJ_BLOB;
 722        else if (starts_with(sp, "object}"))
 723                expected_type = OBJ_ANY;
 724        else if (sp[0] == '}')
 725                expected_type = OBJ_NONE;
 726        else if (sp[0] == '/')
 727                expected_type = OBJ_COMMIT;
 728        else
 729                return -1;
 730
 731        lookup_flags &= ~GET_SHA1_DISAMBIGUATORS;
 732        if (expected_type == OBJ_COMMIT)
 733                lookup_flags |= GET_SHA1_COMMITTISH;
 734        else if (expected_type == OBJ_TREE)
 735                lookup_flags |= GET_SHA1_TREEISH;
 736
 737        if (get_sha1_1(name, sp - name - 2, outer, lookup_flags))
 738                return -1;
 739
 740        o = parse_object(outer);
 741        if (!o)
 742                return -1;
 743        if (!expected_type) {
 744                o = deref_tag(o, name, sp - name - 2);
 745                if (!o || (!o->parsed && !parse_object(o->oid.hash)))
 746                        return -1;
 747                hashcpy(sha1, o->oid.hash);
 748                return 0;
 749        }
 750
 751        /*
 752         * At this point, the syntax look correct, so
 753         * if we do not get the needed object, we should
 754         * barf.
 755         */
 756        o = peel_to_type(name, len, o, expected_type);
 757        if (!o)
 758                return -1;
 759
 760        hashcpy(sha1, o->oid.hash);
 761        if (sp[0] == '/') {
 762                /* "$commit^{/foo}" */
 763                char *prefix;
 764                int ret;
 765                struct commit_list *list = NULL;
 766
 767                /*
 768                 * $commit^{/}. Some regex implementation may reject.
 769                 * We don't need regex anyway. '' pattern always matches.
 770                 */
 771                if (sp[1] == '}')
 772                        return 0;
 773
 774                prefix = xstrndup(sp + 1, name + len - 1 - (sp + 1));
 775                commit_list_insert((struct commit *)o, &list);
 776                ret = get_sha1_oneline(prefix, sha1, list);
 777                free(prefix);
 778                return ret;
 779        }
 780        return 0;
 781}
 782
 783static int get_describe_name(const char *name, int len, unsigned char *sha1)
 784{
 785        const char *cp;
 786        unsigned flags = GET_SHA1_QUIETLY | GET_SHA1_COMMIT;
 787
 788        for (cp = name + len - 1; name + 2 <= cp; cp--) {
 789                char ch = *cp;
 790                if (!isxdigit(ch)) {
 791                        /* We must be looking at g in "SOMETHING-g"
 792                         * for it to be describe output.
 793                         */
 794                        if (ch == 'g' && cp[-1] == '-') {
 795                                cp++;
 796                                len -= cp - name;
 797                                return get_short_sha1(cp, len, sha1, flags);
 798                        }
 799                }
 800        }
 801        return -1;
 802}
 803
 804static int get_sha1_1(const char *name, int len, unsigned char *sha1, unsigned lookup_flags)
 805{
 806        int ret, has_suffix;
 807        const char *cp;
 808
 809        /*
 810         * "name~3" is "name^^^", "name~" is "name~1", and "name^" is "name^1".
 811         */
 812        has_suffix = 0;
 813        for (cp = name + len - 1; name <= cp; cp--) {
 814                int ch = *cp;
 815                if ('0' <= ch && ch <= '9')
 816                        continue;
 817                if (ch == '~' || ch == '^')
 818                        has_suffix = ch;
 819                break;
 820        }
 821
 822        if (has_suffix) {
 823                int num = 0;
 824                int len1 = cp - name;
 825                cp++;
 826                while (cp < name + len)
 827                        num = num * 10 + *cp++ - '0';
 828                if (!num && len1 == len - 1)
 829                        num = 1;
 830                if (has_suffix == '^')
 831                        return get_parent(name, len1, sha1, num);
 832                /* else if (has_suffix == '~') -- goes without saying */
 833                return get_nth_ancestor(name, len1, sha1, num);
 834        }
 835
 836        ret = peel_onion(name, len, sha1, lookup_flags);
 837        if (!ret)
 838                return 0;
 839
 840        ret = get_sha1_basic(name, len, sha1, lookup_flags);
 841        if (!ret)
 842                return 0;
 843
 844        /* It could be describe output that is "SOMETHING-gXXXX" */
 845        ret = get_describe_name(name, len, sha1);
 846        if (!ret)
 847                return 0;
 848
 849        return get_short_sha1(name, len, sha1, lookup_flags);
 850}
 851
 852/*
 853 * This interprets names like ':/Initial revision of "git"' by searching
 854 * through history and returning the first commit whose message starts
 855 * the given regular expression.
 856 *
 857 * For negative-matching, prefix the pattern-part with '!-', like: ':/!-WIP'.
 858 *
 859 * For a literal '!' character at the beginning of a pattern, you have to repeat
 860 * that, like: ':/!!foo'
 861 *
 862 * For future extension, all other sequences beginning with ':/!' are reserved.
 863 */
 864
 865/* Remember to update object flag allocation in object.h */
 866#define ONELINE_SEEN (1u<<20)
 867
 868static int handle_one_ref(const char *path, const struct object_id *oid,
 869                          int flag, void *cb_data)
 870{
 871        struct commit_list **list = cb_data;
 872        struct object *object = parse_object(oid->hash);
 873        if (!object)
 874                return 0;
 875        if (object->type == OBJ_TAG) {
 876                object = deref_tag(object, path, strlen(path));
 877                if (!object)
 878                        return 0;
 879        }
 880        if (object->type != OBJ_COMMIT)
 881                return 0;
 882        commit_list_insert((struct commit *)object, list);
 883        return 0;
 884}
 885
 886static int get_sha1_oneline(const char *prefix, unsigned char *sha1,
 887                            struct commit_list *list)
 888{
 889        struct commit_list *backup = NULL, *l;
 890        int found = 0;
 891        int negative = 0;
 892        regex_t regex;
 893
 894        if (prefix[0] == '!') {
 895                prefix++;
 896
 897                if (prefix[0] == '-') {
 898                        prefix++;
 899                        negative = 1;
 900                } else if (prefix[0] != '!') {
 901                        return -1;
 902                }
 903        }
 904
 905        if (regcomp(&regex, prefix, REG_EXTENDED))
 906                return -1;
 907
 908        for (l = list; l; l = l->next) {
 909                l->item->object.flags |= ONELINE_SEEN;
 910                commit_list_insert(l->item, &backup);
 911        }
 912        while (list) {
 913                const char *p, *buf;
 914                struct commit *commit;
 915                int matches;
 916
 917                commit = pop_most_recent_commit(&list, ONELINE_SEEN);
 918                if (!parse_object(commit->object.oid.hash))
 919                        continue;
 920                buf = get_commit_buffer(commit, NULL);
 921                p = strstr(buf, "\n\n");
 922                matches = negative ^ (p && !regexec(&regex, p + 2, 0, NULL, 0));
 923                unuse_commit_buffer(commit, buf);
 924
 925                if (matches) {
 926                        hashcpy(sha1, commit->object.oid.hash);
 927                        found = 1;
 928                        break;
 929                }
 930        }
 931        regfree(&regex);
 932        free_commit_list(list);
 933        for (l = backup; l; l = l->next)
 934                clear_commit_marks(l->item, ONELINE_SEEN);
 935        free_commit_list(backup);
 936        return found ? 0 : -1;
 937}
 938
 939struct grab_nth_branch_switch_cbdata {
 940        int remaining;
 941        struct strbuf buf;
 942};
 943
 944static int grab_nth_branch_switch(unsigned char *osha1, unsigned char *nsha1,
 945                                  const char *email, unsigned long timestamp, int tz,
 946                                  const char *message, void *cb_data)
 947{
 948        struct grab_nth_branch_switch_cbdata *cb = cb_data;
 949        const char *match = NULL, *target = NULL;
 950        size_t len;
 951
 952        if (skip_prefix(message, "checkout: moving from ", &match))
 953                target = strstr(match, " to ");
 954
 955        if (!match || !target)
 956                return 0;
 957        if (--(cb->remaining) == 0) {
 958                len = target - match;
 959                strbuf_reset(&cb->buf);
 960                strbuf_add(&cb->buf, match, len);
 961                return 1; /* we are done */
 962        }
 963        return 0;
 964}
 965
 966/*
 967 * Parse @{-N} syntax, return the number of characters parsed
 968 * if successful; otherwise signal an error with negative value.
 969 */
 970static int interpret_nth_prior_checkout(const char *name, int namelen,
 971                                        struct strbuf *buf)
 972{
 973        long nth;
 974        int retval;
 975        struct grab_nth_branch_switch_cbdata cb;
 976        const char *brace;
 977        char *num_end;
 978
 979        if (namelen < 4)
 980                return -1;
 981        if (name[0] != '@' || name[1] != '{' || name[2] != '-')
 982                return -1;
 983        brace = memchr(name, '}', namelen);
 984        if (!brace)
 985                return -1;
 986        nth = strtol(name + 3, &num_end, 10);
 987        if (num_end != brace)
 988                return -1;
 989        if (nth <= 0)
 990                return -1;
 991        cb.remaining = nth;
 992        strbuf_init(&cb.buf, 20);
 993
 994        retval = 0;
 995        if (0 < for_each_reflog_ent_reverse("HEAD", grab_nth_branch_switch, &cb)) {
 996                strbuf_reset(buf);
 997                strbuf_addbuf(buf, &cb.buf);
 998                retval = brace - name + 1;
 999        }
1000
1001        strbuf_release(&cb.buf);
1002        return retval;
1003}
1004
1005int get_oid_mb(const char *name, struct object_id *oid)
1006{
1007        struct commit *one, *two;
1008        struct commit_list *mbs;
1009        struct object_id oid_tmp;
1010        const char *dots;
1011        int st;
1012
1013        dots = strstr(name, "...");
1014        if (!dots)
1015                return get_oid(name, oid);
1016        if (dots == name)
1017                st = get_oid("HEAD", &oid_tmp);
1018        else {
1019                struct strbuf sb;
1020                strbuf_init(&sb, dots - name);
1021                strbuf_add(&sb, name, dots - name);
1022                st = get_sha1_committish(sb.buf, oid_tmp.hash);
1023                strbuf_release(&sb);
1024        }
1025        if (st)
1026                return st;
1027        one = lookup_commit_reference_gently(oid_tmp.hash, 0);
1028        if (!one)
1029                return -1;
1030
1031        if (get_sha1_committish(dots[3] ? (dots + 3) : "HEAD", oid_tmp.hash))
1032                return -1;
1033        two = lookup_commit_reference_gently(oid_tmp.hash, 0);
1034        if (!two)
1035                return -1;
1036        mbs = get_merge_bases(one, two);
1037        if (!mbs || mbs->next)
1038                st = -1;
1039        else {
1040                st = 0;
1041                oidcpy(oid, &mbs->item->object.oid);
1042        }
1043        free_commit_list(mbs);
1044        return st;
1045}
1046
1047/* parse @something syntax, when 'something' is not {.*} */
1048static int interpret_empty_at(const char *name, int namelen, int len, struct strbuf *buf)
1049{
1050        const char *next;
1051
1052        if (len || name[1] == '{')
1053                return -1;
1054
1055        /* make sure it's a single @, or @@{.*}, not @foo */
1056        next = memchr(name + len + 1, '@', namelen - len - 1);
1057        if (next && next[1] != '{')
1058                return -1;
1059        if (!next)
1060                next = name + namelen;
1061        if (next != name + 1)
1062                return -1;
1063
1064        strbuf_reset(buf);
1065        strbuf_add(buf, "HEAD", 4);
1066        return 1;
1067}
1068
1069static int reinterpret(const char *name, int namelen, int len, struct strbuf *buf)
1070{
1071        /* we have extra data, which might need further processing */
1072        struct strbuf tmp = STRBUF_INIT;
1073        int used = buf->len;
1074        int ret;
1075
1076        strbuf_add(buf, name + len, namelen - len);
1077        ret = interpret_branch_name(buf->buf, buf->len, &tmp);
1078        /* that data was not interpreted, remove our cruft */
1079        if (ret < 0) {
1080                strbuf_setlen(buf, used);
1081                return len;
1082        }
1083        strbuf_reset(buf);
1084        strbuf_addbuf(buf, &tmp);
1085        strbuf_release(&tmp);
1086        /* tweak for size of {-N} versus expanded ref name */
1087        return ret - used + len;
1088}
1089
1090static void set_shortened_ref(struct strbuf *buf, const char *ref)
1091{
1092        char *s = shorten_unambiguous_ref(ref, 0);
1093        strbuf_reset(buf);
1094        strbuf_addstr(buf, s);
1095        free(s);
1096}
1097
1098static int interpret_branch_mark(const char *name, int namelen,
1099                                 int at, struct strbuf *buf,
1100                                 int (*get_mark)(const char *, int),
1101                                 const char *(*get_data)(struct branch *,
1102                                                         struct strbuf *))
1103{
1104        int len;
1105        struct branch *branch;
1106        struct strbuf err = STRBUF_INIT;
1107        const char *value;
1108
1109        len = get_mark(name + at, namelen - at);
1110        if (!len)
1111                return -1;
1112
1113        if (memchr(name, ':', at))
1114                return -1;
1115
1116        if (at) {
1117                char *name_str = xmemdupz(name, at);
1118                branch = branch_get(name_str);
1119                free(name_str);
1120        } else
1121                branch = branch_get(NULL);
1122
1123        value = get_data(branch, &err);
1124        if (!value)
1125                die("%s", err.buf);
1126
1127        set_shortened_ref(buf, value);
1128        return len + at;
1129}
1130
1131/*
1132 * This reads short-hand syntax that not only evaluates to a commit
1133 * object name, but also can act as if the end user spelled the name
1134 * of the branch from the command line.
1135 *
1136 * - "@{-N}" finds the name of the Nth previous branch we were on, and
1137 *   places the name of the branch in the given buf and returns the
1138 *   number of characters parsed if successful.
1139 *
1140 * - "<branch>@{upstream}" finds the name of the other ref that
1141 *   <branch> is configured to merge with (missing <branch> defaults
1142 *   to the current branch), and places the name of the branch in the
1143 *   given buf and returns the number of characters parsed if
1144 *   successful.
1145 *
1146 * If the input is not of the accepted format, it returns a negative
1147 * number to signal an error.
1148 *
1149 * If the input was ok but there are not N branch switches in the
1150 * reflog, it returns 0.
1151 */
1152int interpret_branch_name(const char *name, int namelen, struct strbuf *buf)
1153{
1154        char *at;
1155        const char *start;
1156        int len = interpret_nth_prior_checkout(name, namelen, buf);
1157
1158        if (!namelen)
1159                namelen = strlen(name);
1160
1161        if (!len) {
1162                return len; /* syntax Ok, not enough switches */
1163        } else if (len > 0) {
1164                if (len == namelen)
1165                        return len; /* consumed all */
1166                else
1167                        return reinterpret(name, namelen, len, buf);
1168        }
1169
1170        for (start = name;
1171             (at = memchr(start, '@', namelen - (start - name)));
1172             start = at + 1) {
1173
1174                len = interpret_empty_at(name, namelen, at - name, buf);
1175                if (len > 0)
1176                        return reinterpret(name, namelen, len, buf);
1177
1178                len = interpret_branch_mark(name, namelen, at - name, buf,
1179                                            upstream_mark, branch_get_upstream);
1180                if (len > 0)
1181                        return len;
1182
1183                len = interpret_branch_mark(name, namelen, at - name, buf,
1184                                            push_mark, branch_get_push);
1185                if (len > 0)
1186                        return len;
1187        }
1188
1189        return -1;
1190}
1191
1192int strbuf_branchname(struct strbuf *sb, const char *name)
1193{
1194        int len = strlen(name);
1195        int used = interpret_branch_name(name, len, sb);
1196
1197        if (used == len)
1198                return 0;
1199        if (used < 0)
1200                used = 0;
1201        strbuf_add(sb, name + used, len - used);
1202        return len;
1203}
1204
1205int strbuf_check_branch_ref(struct strbuf *sb, const char *name)
1206{
1207        strbuf_branchname(sb, name);
1208        if (name[0] == '-')
1209                return -1;
1210        strbuf_splice(sb, 0, 0, "refs/heads/", 11);
1211        return check_refname_format(sb->buf, 0);
1212}
1213
1214/*
1215 * This is like "get_sha1_basic()", except it allows "sha1 expressions",
1216 * notably "xyz^" for "parent of xyz"
1217 */
1218int get_sha1(const char *name, unsigned char *sha1)
1219{
1220        struct object_context unused;
1221        return get_sha1_with_context(name, 0, sha1, &unused);
1222}
1223
1224/*
1225 * This is like "get_sha1()", but for struct object_id.
1226 */
1227int get_oid(const char *name, struct object_id *oid)
1228{
1229        return get_sha1(name, oid->hash);
1230}
1231
1232
1233/*
1234 * Many callers know that the user meant to name a commit-ish by
1235 * syntactical positions where the object name appears.  Calling this
1236 * function allows the machinery to disambiguate shorter-than-unique
1237 * abbreviated object names between commit-ish and others.
1238 *
1239 * Note that this does NOT error out when the named object is not a
1240 * commit-ish. It is merely to give a hint to the disambiguation
1241 * machinery.
1242 */
1243int get_sha1_committish(const char *name, unsigned char *sha1)
1244{
1245        struct object_context unused;
1246        return get_sha1_with_context(name, GET_SHA1_COMMITTISH,
1247                                     sha1, &unused);
1248}
1249
1250int get_sha1_treeish(const char *name, unsigned char *sha1)
1251{
1252        struct object_context unused;
1253        return get_sha1_with_context(name, GET_SHA1_TREEISH,
1254                                     sha1, &unused);
1255}
1256
1257int get_sha1_commit(const char *name, unsigned char *sha1)
1258{
1259        struct object_context unused;
1260        return get_sha1_with_context(name, GET_SHA1_COMMIT,
1261                                     sha1, &unused);
1262}
1263
1264int get_sha1_tree(const char *name, unsigned char *sha1)
1265{
1266        struct object_context unused;
1267        return get_sha1_with_context(name, GET_SHA1_TREE,
1268                                     sha1, &unused);
1269}
1270
1271int get_sha1_blob(const char *name, unsigned char *sha1)
1272{
1273        struct object_context unused;
1274        return get_sha1_with_context(name, GET_SHA1_BLOB,
1275                                     sha1, &unused);
1276}
1277
1278/* Must be called only when object_name:filename doesn't exist. */
1279static void diagnose_invalid_sha1_path(const char *prefix,
1280                                       const char *filename,
1281                                       const unsigned char *tree_sha1,
1282                                       const char *object_name,
1283                                       int object_name_len)
1284{
1285        unsigned char sha1[20];
1286        unsigned mode;
1287
1288        if (!prefix)
1289                prefix = "";
1290
1291        if (file_exists(filename))
1292                die("Path '%s' exists on disk, but not in '%.*s'.",
1293                    filename, object_name_len, object_name);
1294        if (errno == ENOENT || errno == ENOTDIR) {
1295                char *fullname = xstrfmt("%s%s", prefix, filename);
1296
1297                if (!get_tree_entry(tree_sha1, fullname,
1298                                    sha1, &mode)) {
1299                        die("Path '%s' exists, but not '%s'.\n"
1300                            "Did you mean '%.*s:%s' aka '%.*s:./%s'?",
1301                            fullname,
1302                            filename,
1303                            object_name_len, object_name,
1304                            fullname,
1305                            object_name_len, object_name,
1306                            filename);
1307                }
1308                die("Path '%s' does not exist in '%.*s'",
1309                    filename, object_name_len, object_name);
1310        }
1311}
1312
1313/* Must be called only when :stage:filename doesn't exist. */
1314static void diagnose_invalid_index_path(int stage,
1315                                        const char *prefix,
1316                                        const char *filename)
1317{
1318        const struct cache_entry *ce;
1319        int pos;
1320        unsigned namelen = strlen(filename);
1321        struct strbuf fullname = STRBUF_INIT;
1322
1323        if (!prefix)
1324                prefix = "";
1325
1326        /* Wrong stage number? */
1327        pos = cache_name_pos(filename, namelen);
1328        if (pos < 0)
1329                pos = -pos - 1;
1330        if (pos < active_nr) {
1331                ce = active_cache[pos];
1332                if (ce_namelen(ce) == namelen &&
1333                    !memcmp(ce->name, filename, namelen))
1334                        die("Path '%s' is in the index, but not at stage %d.\n"
1335                            "Did you mean ':%d:%s'?",
1336                            filename, stage,
1337                            ce_stage(ce), filename);
1338        }
1339
1340        /* Confusion between relative and absolute filenames? */
1341        strbuf_addstr(&fullname, prefix);
1342        strbuf_addstr(&fullname, filename);
1343        pos = cache_name_pos(fullname.buf, fullname.len);
1344        if (pos < 0)
1345                pos = -pos - 1;
1346        if (pos < active_nr) {
1347                ce = active_cache[pos];
1348                if (ce_namelen(ce) == fullname.len &&
1349                    !memcmp(ce->name, fullname.buf, fullname.len))
1350                        die("Path '%s' is in the index, but not '%s'.\n"
1351                            "Did you mean ':%d:%s' aka ':%d:./%s'?",
1352                            fullname.buf, filename,
1353                            ce_stage(ce), fullname.buf,
1354                            ce_stage(ce), filename);
1355        }
1356
1357        if (file_exists(filename))
1358                die("Path '%s' exists on disk, but not in the index.", filename);
1359        if (errno == ENOENT || errno == ENOTDIR)
1360                die("Path '%s' does not exist (neither on disk nor in the index).",
1361                    filename);
1362
1363        strbuf_release(&fullname);
1364}
1365
1366
1367static char *resolve_relative_path(const char *rel)
1368{
1369        if (!starts_with(rel, "./") && !starts_with(rel, "../"))
1370                return NULL;
1371
1372        if (!is_inside_work_tree())
1373                die("relative path syntax can't be used outside working tree.");
1374
1375        /* die() inside prefix_path() if resolved path is outside worktree */
1376        return prefix_path(startup_info->prefix,
1377                           startup_info->prefix ? strlen(startup_info->prefix) : 0,
1378                           rel);
1379}
1380
1381static int get_sha1_with_context_1(const char *name,
1382                                   unsigned flags,
1383                                   const char *prefix,
1384                                   unsigned char *sha1,
1385                                   struct object_context *oc)
1386{
1387        int ret, bracket_depth;
1388        int namelen = strlen(name);
1389        const char *cp;
1390        int only_to_die = flags & GET_SHA1_ONLY_TO_DIE;
1391
1392        if (only_to_die)
1393                flags |= GET_SHA1_QUIETLY;
1394
1395        memset(oc, 0, sizeof(*oc));
1396        oc->mode = S_IFINVALID;
1397        ret = get_sha1_1(name, namelen, sha1, flags);
1398        if (!ret)
1399                return ret;
1400        /*
1401         * sha1:path --> object name of path in ent sha1
1402         * :path -> object name of absolute path in index
1403         * :./path -> object name of path relative to cwd in index
1404         * :[0-3]:path -> object name of path in index at stage
1405         * :/foo -> recent commit matching foo
1406         */
1407        if (name[0] == ':') {
1408                int stage = 0;
1409                const struct cache_entry *ce;
1410                char *new_path = NULL;
1411                int pos;
1412                if (!only_to_die && namelen > 2 && name[1] == '/') {
1413                        struct commit_list *list = NULL;
1414
1415                        for_each_ref(handle_one_ref, &list);
1416                        commit_list_sort_by_date(&list);
1417                        return get_sha1_oneline(name + 2, sha1, list);
1418                }
1419                if (namelen < 3 ||
1420                    name[2] != ':' ||
1421                    name[1] < '0' || '3' < name[1])
1422                        cp = name + 1;
1423                else {
1424                        stage = name[1] - '0';
1425                        cp = name + 3;
1426                }
1427                new_path = resolve_relative_path(cp);
1428                if (!new_path) {
1429                        namelen = namelen - (cp - name);
1430                } else {
1431                        cp = new_path;
1432                        namelen = strlen(cp);
1433                }
1434
1435                strlcpy(oc->path, cp, sizeof(oc->path));
1436
1437                if (!active_cache)
1438                        read_cache();
1439                pos = cache_name_pos(cp, namelen);
1440                if (pos < 0)
1441                        pos = -pos - 1;
1442                while (pos < active_nr) {
1443                        ce = active_cache[pos];
1444                        if (ce_namelen(ce) != namelen ||
1445                            memcmp(ce->name, cp, namelen))
1446                                break;
1447                        if (ce_stage(ce) == stage) {
1448                                hashcpy(sha1, ce->oid.hash);
1449                                oc->mode = ce->ce_mode;
1450                                free(new_path);
1451                                return 0;
1452                        }
1453                        pos++;
1454                }
1455                if (only_to_die && name[1] && name[1] != '/')
1456                        diagnose_invalid_index_path(stage, prefix, cp);
1457                free(new_path);
1458                return -1;
1459        }
1460        for (cp = name, bracket_depth = 0; *cp; cp++) {
1461                if (*cp == '{')
1462                        bracket_depth++;
1463                else if (bracket_depth && *cp == '}')
1464                        bracket_depth--;
1465                else if (!bracket_depth && *cp == ':')
1466                        break;
1467        }
1468        if (*cp == ':') {
1469                unsigned char tree_sha1[20];
1470                int len = cp - name;
1471                unsigned sub_flags = flags;
1472
1473                sub_flags &= ~GET_SHA1_DISAMBIGUATORS;
1474                sub_flags |= GET_SHA1_TREEISH;
1475
1476                if (!get_sha1_1(name, len, tree_sha1, sub_flags)) {
1477                        const char *filename = cp+1;
1478                        char *new_filename = NULL;
1479
1480                        new_filename = resolve_relative_path(filename);
1481                        if (new_filename)
1482                                filename = new_filename;
1483                        if (flags & GET_SHA1_FOLLOW_SYMLINKS) {
1484                                ret = get_tree_entry_follow_symlinks(tree_sha1,
1485                                        filename, sha1, &oc->symlink_path,
1486                                        &oc->mode);
1487                        } else {
1488                                ret = get_tree_entry(tree_sha1, filename,
1489                                                     sha1, &oc->mode);
1490                                if (ret && only_to_die) {
1491                                        diagnose_invalid_sha1_path(prefix,
1492                                                                   filename,
1493                                                                   tree_sha1,
1494                                                                   name, len);
1495                                }
1496                        }
1497                        hashcpy(oc->tree, tree_sha1);
1498                        strlcpy(oc->path, filename, sizeof(oc->path));
1499
1500                        free(new_filename);
1501                        return ret;
1502                } else {
1503                        if (only_to_die)
1504                                die("Invalid object name '%.*s'.", len, name);
1505                }
1506        }
1507        return ret;
1508}
1509
1510/*
1511 * Call this function when you know "name" given by the end user must
1512 * name an object but it doesn't; the function _may_ die with a better
1513 * diagnostic message than "no such object 'name'", e.g. "Path 'doc' does not
1514 * exist in 'HEAD'" when given "HEAD:doc", or it may return in which case
1515 * you have a chance to diagnose the error further.
1516 */
1517void maybe_die_on_misspelt_object_name(const char *name, const char *prefix)
1518{
1519        struct object_context oc;
1520        unsigned char sha1[20];
1521        get_sha1_with_context_1(name, GET_SHA1_ONLY_TO_DIE, prefix, sha1, &oc);
1522}
1523
1524int get_sha1_with_context(const char *str, unsigned flags, unsigned char *sha1, struct object_context *orc)
1525{
1526        if (flags & GET_SHA1_FOLLOW_SYMLINKS && flags & GET_SHA1_ONLY_TO_DIE)
1527                die("BUG: incompatible flags for get_sha1_with_context");
1528        return get_sha1_with_context_1(str, flags, NULL, sha1, orc);
1529}