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