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