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