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