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