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