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