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