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