174d3df9b34bc208bd552a3452a9c46a399c07ba
   1#include "cache.h"
   2#include "tag.h"
   3#include "commit.h"
   4#include "tree.h"
   5#include "blob.h"
   6#include "tree-walk.h"
   7#include "refs.h"
   8#include "remote.h"
   9
  10static int get_sha1_oneline(const char *, unsigned char *, struct commit_list *);
  11
  12typedef int (*disambiguate_hint_fn)(const unsigned char *, void *);
  13
  14struct disambiguate_state {
  15        disambiguate_hint_fn fn;
  16        void *cb_data;
  17        unsigned char candidate[20];
  18        unsigned candidate_exists:1;
  19        unsigned candidate_checked:1;
  20        unsigned candidate_ok:1;
  21        unsigned disambiguate_fn_used:1;
  22        unsigned ambiguous:1;
  23};
  24
  25static void update_candidates(struct disambiguate_state *ds, const unsigned char *current)
  26{
  27        if (!ds->candidate_exists) {
  28                /* this is the first candidate */
  29                hashcpy(ds->candidate, current);
  30                ds->candidate_exists = 1;
  31                return;
  32        } else if (!hashcmp(ds->candidate, current)) {
  33                /* the same as what we already have seen */
  34                return;
  35        }
  36
  37        if (!ds->fn) {
  38                /* cannot disambiguate between ds->candidate and current */
  39                ds->ambiguous = 1;
  40                return;
  41        }
  42
  43        if (!ds->candidate_checked) {
  44                ds->candidate_ok = ds->fn(ds->candidate, ds->cb_data);
  45                ds->disambiguate_fn_used = 1;
  46                ds->candidate_checked = 1;
  47        }
  48
  49        if (!ds->candidate_ok) {
  50                /* discard the candidate; we know it does not satisify fn */
  51                hashcpy(ds->candidate, current);
  52                ds->candidate_checked = 0;
  53                return;
  54        }
  55
  56        /* if we reach this point, we know ds->candidate satisfies fn */
  57        if (ds->fn(current, ds->cb_data)) {
  58                /*
  59                 * if both current and candidate satisfy fn, we cannot
  60                 * disambiguate.
  61                 */
  62                ds->candidate_ok = 0;
  63                ds->ambiguous = 1;
  64        }
  65
  66        /* otherwise, current can be discarded and candidate is still good */
  67}
  68
  69static void find_short_object_filename(int len, const char *hex_pfx, struct disambiguate_state *ds)
  70{
  71        struct alternate_object_database *alt;
  72        char hex[40];
  73        static struct alternate_object_database *fakeent;
  74
  75        if (!fakeent) {
  76                /*
  77                 * Create a "fake" alternate object database that
  78                 * points to our own object database, to make it
  79                 * easier to get a temporary working space in
  80                 * alt->name/alt->base while iterating over the
  81                 * object databases including our own.
  82                 */
  83                const char *objdir = get_object_directory();
  84                int objdir_len = strlen(objdir);
  85                int entlen = objdir_len + 43;
  86                fakeent = xmalloc(sizeof(*fakeent) + entlen);
  87                memcpy(fakeent->base, objdir, objdir_len);
  88                fakeent->name = fakeent->base + objdir_len + 1;
  89                fakeent->name[-1] = '/';
  90        }
  91        fakeent->next = alt_odb_list;
  92
  93        sprintf(hex, "%.2s", hex_pfx);
  94        for (alt = fakeent; alt && !ds->ambiguous; alt = alt->next) {
  95                struct dirent *de;
  96                DIR *dir;
  97                sprintf(alt->name, "%.2s/", hex_pfx);
  98                dir = opendir(alt->base);
  99                if (!dir)
 100                        continue;
 101
 102                while (!ds->ambiguous && (de = readdir(dir)) != NULL) {
 103                        unsigned char sha1[20];
 104
 105                        if (strlen(de->d_name) != 38)
 106                                continue;
 107                        if (memcmp(de->d_name, hex_pfx + 2, len - 2))
 108                                continue;
 109                        memcpy(hex + 2, de->d_name, 38);
 110                        if (!get_sha1_hex(hex, sha1))
 111                                update_candidates(ds, sha1);
 112                }
 113                closedir(dir);
 114        }
 115}
 116
 117static int match_sha(unsigned len, const unsigned char *a, const unsigned char *b)
 118{
 119        do {
 120                if (*a != *b)
 121                        return 0;
 122                a++;
 123                b++;
 124                len -= 2;
 125        } while (len > 1);
 126        if (len)
 127                if ((*a ^ *b) & 0xf0)
 128                        return 0;
 129        return 1;
 130}
 131
 132static void unique_in_pack(int len,
 133                          const unsigned char *bin_pfx,
 134                           struct packed_git *p,
 135                           struct disambiguate_state *ds)
 136{
 137        uint32_t num, last, i, first = 0;
 138        const unsigned char *current = NULL;
 139
 140        open_pack_index(p);
 141        num = p->num_objects;
 142        last = num;
 143        while (first < last) {
 144                uint32_t mid = (first + last) / 2;
 145                const unsigned char *current;
 146                int cmp;
 147
 148                current = nth_packed_object_sha1(p, mid);
 149                cmp = hashcmp(bin_pfx, current);
 150                if (!cmp) {
 151                        first = mid;
 152                        break;
 153                }
 154                if (cmp > 0) {
 155                        first = mid+1;
 156                        continue;
 157                }
 158                last = mid;
 159        }
 160
 161        /*
 162         * At this point, "first" is the location of the lowest object
 163         * with an object name that could match "bin_pfx".  See if we have
 164         * 0, 1 or more objects that actually match(es).
 165         */
 166        for (i = first; i < num && !ds->ambiguous; i++) {
 167                current = nth_packed_object_sha1(p, i);
 168                if (!match_sha(len, bin_pfx, current))
 169                        break;
 170                update_candidates(ds, current);
 171        }
 172}
 173
 174static void find_short_packed_object(int len, const unsigned char *bin_pfx,
 175                                     struct disambiguate_state *ds)
 176{
 177        struct packed_git *p;
 178
 179        prepare_packed_git();
 180        for (p = packed_git; p && !ds->ambiguous; p = p->next)
 181                unique_in_pack(len, bin_pfx, p, ds);
 182}
 183
 184#define SHORT_NAME_NOT_FOUND (-1)
 185#define SHORT_NAME_AMBIGUOUS (-2)
 186
 187static int finish_object_disambiguation(struct disambiguate_state *ds,
 188                                        unsigned char *sha1)
 189{
 190        if (ds->ambiguous)
 191                return SHORT_NAME_AMBIGUOUS;
 192
 193        if (!ds->candidate_exists)
 194                return SHORT_NAME_NOT_FOUND;
 195
 196        if (!ds->candidate_checked)
 197                /*
 198                 * If this is the only candidate, there is no point
 199                 * calling the disambiguation hint callback.
 200                 *
 201                 * On the other hand, if the current candidate
 202                 * replaced an earlier candidate that did _not_ pass
 203                 * the disambiguation hint callback, then we do have
 204                 * more than one objects that match the short name
 205                 * given, so we should make sure this one matches;
 206                 * otherwise, if we discovered this one and the one
 207                 * that we previously discarded in the reverse order,
 208                 * we would end up showing different results in the
 209                 * same repository!
 210                 */
 211                ds->candidate_ok = (!ds->disambiguate_fn_used ||
 212                                    ds->fn(ds->candidate, ds->cb_data));
 213
 214        if (!ds->candidate_ok)
 215                return SHORT_NAME_AMBIGUOUS;
 216
 217        hashcpy(sha1, ds->candidate);
 218        return 0;
 219}
 220
 221static int disambiguate_commit_only(const unsigned char *sha1, void *cb_data_unused)
 222{
 223        int kind = sha1_object_info(sha1, NULL);
 224        return kind == OBJ_COMMIT;
 225}
 226
 227static int get_short_sha1(const char *name, int len, unsigned char *sha1,
 228                          unsigned flags)
 229{
 230        int i, status;
 231        char hex_pfx[40];
 232        unsigned char bin_pfx[20];
 233        struct disambiguate_state ds;
 234        int quietly = !!(flags & GET_SHA1_QUIETLY);
 235
 236        if (len < MINIMUM_ABBREV || len > 40)
 237                return -1;
 238        hashclr(bin_pfx);
 239        memset(hex_pfx, 'x', 40);
 240        for (i = 0; i < len ;i++) {
 241                unsigned char c = name[i];
 242                unsigned char val;
 243                if (c >= '0' && c <= '9')
 244                        val = c - '0';
 245                else if (c >= 'a' && c <= 'f')
 246                        val = c - 'a' + 10;
 247                else if (c >= 'A' && c <='F') {
 248                        val = c - 'A' + 10;
 249                        c -= 'A' - 'a';
 250                }
 251                else
 252                        return -1;
 253                hex_pfx[i] = c;
 254                if (!(i & 1))
 255                        val <<= 4;
 256                bin_pfx[i >> 1] |= val;
 257        }
 258
 259        prepare_alt_odb();
 260
 261        memset(&ds, 0, sizeof(ds));
 262        if (flags & GET_SHA1_COMMIT)
 263                ds.fn = disambiguate_commit_only;
 264
 265        find_short_object_filename(len, hex_pfx, &ds);
 266        find_short_packed_object(len, bin_pfx, &ds);
 267        status = finish_object_disambiguation(&ds, sha1);
 268
 269        if (!quietly && (status == SHORT_NAME_AMBIGUOUS))
 270                return error("short SHA1 %.*s is ambiguous.", len, hex_pfx);
 271        return status;
 272}
 273
 274const char *find_unique_abbrev(const unsigned char *sha1, int len)
 275{
 276        int status, exists;
 277        static char hex[41];
 278
 279        exists = has_sha1_file(sha1);
 280        memcpy(hex, sha1_to_hex(sha1), 40);
 281        if (len == 40 || !len)
 282                return hex;
 283        while (len < 40) {
 284                unsigned char sha1_ret[20];
 285                status = get_short_sha1(hex, len, sha1_ret, GET_SHA1_QUIETLY);
 286                if (exists
 287                    ? !status
 288                    : status == SHORT_NAME_NOT_FOUND) {
 289                        hex[len] = 0;
 290                        return hex;
 291                }
 292                len++;
 293        }
 294        return hex;
 295}
 296
 297static int ambiguous_path(const char *path, int len)
 298{
 299        int slash = 1;
 300        int cnt;
 301
 302        for (cnt = 0; cnt < len; cnt++) {
 303                switch (*path++) {
 304                case '\0':
 305                        break;
 306                case '/':
 307                        if (slash)
 308                                break;
 309                        slash = 1;
 310                        continue;
 311                case '.':
 312                        continue;
 313                default:
 314                        slash = 0;
 315                        continue;
 316                }
 317                break;
 318        }
 319        return slash;
 320}
 321
 322static inline int upstream_mark(const char *string, int len)
 323{
 324        const char *suffix[] = { "@{upstream}", "@{u}" };
 325        int i;
 326
 327        for (i = 0; i < ARRAY_SIZE(suffix); i++) {
 328                int suffix_len = strlen(suffix[i]);
 329                if (suffix_len <= len
 330                    && !memcmp(string, suffix[i], suffix_len))
 331                        return suffix_len;
 332        }
 333        return 0;
 334}
 335
 336static int get_sha1_1(const char *name, int len, unsigned char *sha1);
 337
 338static int get_sha1_basic(const char *str, int len, unsigned char *sha1)
 339{
 340        static const char *warn_msg = "refname '%.*s' is ambiguous.";
 341        char *real_ref = NULL;
 342        int refs_found = 0;
 343        int at, reflog_len;
 344
 345        if (len == 40 && !get_sha1_hex(str, sha1))
 346                return 0;
 347
 348        /* basic@{time or number or -number} format to query ref-log */
 349        reflog_len = at = 0;
 350        if (len && str[len-1] == '}') {
 351                for (at = len-2; at >= 0; at--) {
 352                        if (str[at] == '@' && str[at+1] == '{') {
 353                                if (!upstream_mark(str + at, len - at)) {
 354                                        reflog_len = (len-1) - (at+2);
 355                                        len = at;
 356                                }
 357                                break;
 358                        }
 359                }
 360        }
 361
 362        /* Accept only unambiguous ref paths. */
 363        if (len && ambiguous_path(str, len))
 364                return -1;
 365
 366        if (!len && reflog_len) {
 367                struct strbuf buf = STRBUF_INIT;
 368                int ret;
 369                /* try the @{-N} syntax for n-th checkout */
 370                ret = interpret_branch_name(str+at, &buf);
 371                if (ret > 0) {
 372                        /* substitute this branch name and restart */
 373                        return get_sha1_1(buf.buf, buf.len, sha1);
 374                } else if (ret == 0) {
 375                        return -1;
 376                }
 377                /* allow "@{...}" to mean the current branch reflog */
 378                refs_found = dwim_ref("HEAD", 4, sha1, &real_ref);
 379        } else if (reflog_len)
 380                refs_found = dwim_log(str, len, sha1, &real_ref);
 381        else
 382                refs_found = dwim_ref(str, len, sha1, &real_ref);
 383
 384        if (!refs_found)
 385                return -1;
 386
 387        if (warn_ambiguous_refs && refs_found > 1)
 388                warning(warn_msg, len, str);
 389
 390        if (reflog_len) {
 391                int nth, i;
 392                unsigned long at_time;
 393                unsigned long co_time;
 394                int co_tz, co_cnt;
 395
 396                /* a @{-N} placed anywhere except the start is an error */
 397                if (str[at+2] == '-')
 398                        return -1;
 399
 400                /* Is it asking for N-th entry, or approxidate? */
 401                for (i = nth = 0; 0 <= nth && i < reflog_len; i++) {
 402                        char ch = str[at+2+i];
 403                        if ('0' <= ch && ch <= '9')
 404                                nth = nth * 10 + ch - '0';
 405                        else
 406                                nth = -1;
 407                }
 408                if (100000000 <= nth) {
 409                        at_time = nth;
 410                        nth = -1;
 411                } else if (0 <= nth)
 412                        at_time = 0;
 413                else {
 414                        int errors = 0;
 415                        char *tmp = xstrndup(str + at + 2, reflog_len);
 416                        at_time = approxidate_careful(tmp, &errors);
 417                        free(tmp);
 418                        if (errors)
 419                                return -1;
 420                }
 421                if (read_ref_at(real_ref, at_time, nth, sha1, NULL,
 422                                &co_time, &co_tz, &co_cnt)) {
 423                        if (at_time)
 424                                warning("Log for '%.*s' only goes "
 425                                        "back to %s.", len, str,
 426                                        show_date(co_time, co_tz, DATE_RFC2822));
 427                        else {
 428                                free(real_ref);
 429                                die("Log for '%.*s' only has %d entries.",
 430                                    len, str, co_cnt);
 431                        }
 432                }
 433        }
 434
 435        free(real_ref);
 436        return 0;
 437}
 438
 439static int get_parent(const char *name, int len,
 440                      unsigned char *result, int idx)
 441{
 442        unsigned char sha1[20];
 443        int ret = get_sha1_1(name, len, sha1);
 444        struct commit *commit;
 445        struct commit_list *p;
 446
 447        if (ret)
 448                return ret;
 449        commit = lookup_commit_reference(sha1);
 450        if (!commit)
 451                return -1;
 452        if (parse_commit(commit))
 453                return -1;
 454        if (!idx) {
 455                hashcpy(result, commit->object.sha1);
 456                return 0;
 457        }
 458        p = commit->parents;
 459        while (p) {
 460                if (!--idx) {
 461                        hashcpy(result, p->item->object.sha1);
 462                        return 0;
 463                }
 464                p = p->next;
 465        }
 466        return -1;
 467}
 468
 469static int get_nth_ancestor(const char *name, int len,
 470                            unsigned char *result, int generation)
 471{
 472        unsigned char sha1[20];
 473        struct commit *commit;
 474        int ret;
 475
 476        ret = get_sha1_1(name, len, sha1);
 477        if (ret)
 478                return ret;
 479        commit = lookup_commit_reference(sha1);
 480        if (!commit)
 481                return -1;
 482
 483        while (generation--) {
 484                if (parse_commit(commit) || !commit->parents)
 485                        return -1;
 486                commit = commit->parents->item;
 487        }
 488        hashcpy(result, commit->object.sha1);
 489        return 0;
 490}
 491
 492struct object *peel_to_type(const char *name, int namelen,
 493                            struct object *o, enum object_type expected_type)
 494{
 495        if (name && !namelen)
 496                namelen = strlen(name);
 497        while (1) {
 498                if (!o || (!o->parsed && !parse_object(o->sha1)))
 499                        return NULL;
 500                if (o->type == expected_type)
 501                        return o;
 502                if (o->type == OBJ_TAG)
 503                        o = ((struct tag*) o)->tagged;
 504                else if (o->type == OBJ_COMMIT)
 505                        o = &(((struct commit *) o)->tree->object);
 506                else {
 507                        if (name)
 508                                error("%.*s: expected %s type, but the object "
 509                                      "dereferences to %s type",
 510                                      namelen, name, typename(expected_type),
 511                                      typename(o->type));
 512                        return NULL;
 513                }
 514        }
 515}
 516
 517static int peel_onion(const char *name, int len, unsigned char *sha1)
 518{
 519        unsigned char outer[20];
 520        const char *sp;
 521        unsigned int expected_type = 0;
 522        struct object *o;
 523
 524        /*
 525         * "ref^{type}" dereferences ref repeatedly until you cannot
 526         * dereference anymore, or you get an object of given type,
 527         * whichever comes first.  "ref^{}" means just dereference
 528         * tags until you get a non-tag.  "ref^0" is a shorthand for
 529         * "ref^{commit}".  "commit^{tree}" could be used to find the
 530         * top-level tree of the given commit.
 531         */
 532        if (len < 4 || name[len-1] != '}')
 533                return -1;
 534
 535        for (sp = name + len - 1; name <= sp; sp--) {
 536                int ch = *sp;
 537                if (ch == '{' && name < sp && sp[-1] == '^')
 538                        break;
 539        }
 540        if (sp <= name)
 541                return -1;
 542
 543        sp++; /* beginning of type name, or closing brace for empty */
 544        if (!strncmp(commit_type, sp, 6) && sp[6] == '}')
 545                expected_type = OBJ_COMMIT;
 546        else if (!strncmp(tree_type, sp, 4) && sp[4] == '}')
 547                expected_type = OBJ_TREE;
 548        else if (!strncmp(blob_type, sp, 4) && sp[4] == '}')
 549                expected_type = OBJ_BLOB;
 550        else if (sp[0] == '}')
 551                expected_type = OBJ_NONE;
 552        else if (sp[0] == '/')
 553                expected_type = OBJ_COMMIT;
 554        else
 555                return -1;
 556
 557        if (get_sha1_1(name, sp - name - 2, outer))
 558                return -1;
 559
 560        o = parse_object(outer);
 561        if (!o)
 562                return -1;
 563        if (!expected_type) {
 564                o = deref_tag(o, name, sp - name - 2);
 565                if (!o || (!o->parsed && !parse_object(o->sha1)))
 566                        return -1;
 567                hashcpy(sha1, o->sha1);
 568                return 0;
 569        }
 570
 571        /*
 572         * At this point, the syntax look correct, so
 573         * if we do not get the needed object, we should
 574         * barf.
 575         */
 576        o = peel_to_type(name, len, o, expected_type);
 577        if (!o)
 578                return -1;
 579
 580        hashcpy(sha1, o->sha1);
 581        if (sp[0] == '/') {
 582                /* "$commit^{/foo}" */
 583                char *prefix;
 584                int ret;
 585                struct commit_list *list = NULL;
 586
 587                /*
 588                 * $commit^{/}. Some regex implementation may reject.
 589                 * We don't need regex anyway. '' pattern always matches.
 590                 */
 591                if (sp[1] == '}')
 592                        return 0;
 593
 594                prefix = xstrndup(sp + 1, name + len - 1 - (sp + 1));
 595                commit_list_insert((struct commit *)o, &list);
 596                ret = get_sha1_oneline(prefix, sha1, list);
 597                free(prefix);
 598                return ret;
 599        }
 600        return 0;
 601}
 602
 603static int get_describe_name(const char *name, int len, unsigned char *sha1)
 604{
 605        const char *cp;
 606
 607        for (cp = name + len - 1; name + 2 <= cp; cp--) {
 608                char ch = *cp;
 609                if (hexval(ch) & ~0377) {
 610                        /* We must be looking at g in "SOMETHING-g"
 611                         * for it to be describe output.
 612                         */
 613                        if (ch == 'g' && cp[-1] == '-') {
 614                                cp++;
 615                                len -= cp - name;
 616                                return get_short_sha1(cp, len, sha1, GET_SHA1_QUIETLY);
 617                        }
 618                }
 619        }
 620        return -1;
 621}
 622
 623static int get_sha1_1(const char *name, int len, unsigned char *sha1)
 624{
 625        int ret, has_suffix;
 626        const char *cp;
 627
 628        /*
 629         * "name~3" is "name^^^", "name~" is "name~1", and "name^" is "name^1".
 630         */
 631        has_suffix = 0;
 632        for (cp = name + len - 1; name <= cp; cp--) {
 633                int ch = *cp;
 634                if ('0' <= ch && ch <= '9')
 635                        continue;
 636                if (ch == '~' || ch == '^')
 637                        has_suffix = ch;
 638                break;
 639        }
 640
 641        if (has_suffix) {
 642                int num = 0;
 643                int len1 = cp - name;
 644                cp++;
 645                while (cp < name + len)
 646                        num = num * 10 + *cp++ - '0';
 647                if (!num && len1 == len - 1)
 648                        num = 1;
 649                if (has_suffix == '^')
 650                        return get_parent(name, len1, sha1, num);
 651                /* else if (has_suffix == '~') -- goes without saying */
 652                return get_nth_ancestor(name, len1, sha1, num);
 653        }
 654
 655        ret = peel_onion(name, len, sha1);
 656        if (!ret)
 657                return 0;
 658
 659        ret = get_sha1_basic(name, len, sha1);
 660        if (!ret)
 661                return 0;
 662
 663        /* It could be describe output that is "SOMETHING-gXXXX" */
 664        ret = get_describe_name(name, len, sha1);
 665        if (!ret)
 666                return 0;
 667
 668        return get_short_sha1(name, len, sha1, 0);
 669}
 670
 671/*
 672 * This interprets names like ':/Initial revision of "git"' by searching
 673 * through history and returning the first commit whose message starts
 674 * the given regular expression.
 675 *
 676 * For future extension, ':/!' is reserved. If you want to match a message
 677 * beginning with a '!', you have to repeat the exclamation mark.
 678 */
 679#define ONELINE_SEEN (1u<<20)
 680
 681static int handle_one_ref(const char *path,
 682                const unsigned char *sha1, int flag, void *cb_data)
 683{
 684        struct commit_list **list = cb_data;
 685        struct object *object = parse_object(sha1);
 686        if (!object)
 687                return 0;
 688        if (object->type == OBJ_TAG) {
 689                object = deref_tag(object, path, strlen(path));
 690                if (!object)
 691                        return 0;
 692        }
 693        if (object->type != OBJ_COMMIT)
 694                return 0;
 695        commit_list_insert_by_date((struct commit *)object, list);
 696        return 0;
 697}
 698
 699static int get_sha1_oneline(const char *prefix, unsigned char *sha1,
 700                            struct commit_list *list)
 701{
 702        struct commit_list *backup = NULL, *l;
 703        int found = 0;
 704        regex_t regex;
 705
 706        if (prefix[0] == '!') {
 707                if (prefix[1] != '!')
 708                        die ("Invalid search pattern: %s", prefix);
 709                prefix++;
 710        }
 711
 712        if (regcomp(&regex, prefix, REG_EXTENDED))
 713                die("Invalid search pattern: %s", prefix);
 714
 715        for (l = list; l; l = l->next) {
 716                l->item->object.flags |= ONELINE_SEEN;
 717                commit_list_insert(l->item, &backup);
 718        }
 719        while (list) {
 720                char *p, *to_free = NULL;
 721                struct commit *commit;
 722                enum object_type type;
 723                unsigned long size;
 724                int matches;
 725
 726                commit = pop_most_recent_commit(&list, ONELINE_SEEN);
 727                if (!parse_object(commit->object.sha1))
 728                        continue;
 729                if (commit->buffer)
 730                        p = commit->buffer;
 731                else {
 732                        p = read_sha1_file(commit->object.sha1, &type, &size);
 733                        if (!p)
 734                                continue;
 735                        to_free = p;
 736                }
 737
 738                p = strstr(p, "\n\n");
 739                matches = p && !regexec(&regex, p + 2, 0, NULL, 0);
 740                free(to_free);
 741
 742                if (matches) {
 743                        hashcpy(sha1, commit->object.sha1);
 744                        found = 1;
 745                        break;
 746                }
 747        }
 748        regfree(&regex);
 749        free_commit_list(list);
 750        for (l = backup; l; l = l->next)
 751                clear_commit_marks(l->item, ONELINE_SEEN);
 752        free_commit_list(backup);
 753        return found ? 0 : -1;
 754}
 755
 756struct grab_nth_branch_switch_cbdata {
 757        long cnt, alloc;
 758        struct strbuf *buf;
 759};
 760
 761static int grab_nth_branch_switch(unsigned char *osha1, unsigned char *nsha1,
 762                                  const char *email, unsigned long timestamp, int tz,
 763                                  const char *message, void *cb_data)
 764{
 765        struct grab_nth_branch_switch_cbdata *cb = cb_data;
 766        const char *match = NULL, *target = NULL;
 767        size_t len;
 768        int nth;
 769
 770        if (!prefixcmp(message, "checkout: moving from ")) {
 771                match = message + strlen("checkout: moving from ");
 772                target = strstr(match, " to ");
 773        }
 774
 775        if (!match || !target)
 776                return 0;
 777
 778        len = target - match;
 779        nth = cb->cnt++ % cb->alloc;
 780        strbuf_reset(&cb->buf[nth]);
 781        strbuf_add(&cb->buf[nth], match, len);
 782        return 0;
 783}
 784
 785/*
 786 * Parse @{-N} syntax, return the number of characters parsed
 787 * if successful; otherwise signal an error with negative value.
 788 */
 789static int interpret_nth_prior_checkout(const char *name, struct strbuf *buf)
 790{
 791        long nth;
 792        int i, retval;
 793        struct grab_nth_branch_switch_cbdata cb;
 794        const char *brace;
 795        char *num_end;
 796
 797        if (name[0] != '@' || name[1] != '{' || name[2] != '-')
 798                return -1;
 799        brace = strchr(name, '}');
 800        if (!brace)
 801                return -1;
 802        nth = strtol(name+3, &num_end, 10);
 803        if (num_end != brace)
 804                return -1;
 805        if (nth <= 0)
 806                return -1;
 807        cb.alloc = nth;
 808        cb.buf = xmalloc(nth * sizeof(struct strbuf));
 809        for (i = 0; i < nth; i++)
 810                strbuf_init(&cb.buf[i], 20);
 811        cb.cnt = 0;
 812        retval = 0;
 813        for_each_recent_reflog_ent("HEAD", grab_nth_branch_switch, 40960, &cb);
 814        if (cb.cnt < nth) {
 815                cb.cnt = 0;
 816                for_each_reflog_ent("HEAD", grab_nth_branch_switch, &cb);
 817        }
 818        if (cb.cnt < nth)
 819                goto release_return;
 820        i = cb.cnt % nth;
 821        strbuf_reset(buf);
 822        strbuf_add(buf, cb.buf[i].buf, cb.buf[i].len);
 823        retval = brace-name+1;
 824
 825release_return:
 826        for (i = 0; i < nth; i++)
 827                strbuf_release(&cb.buf[i]);
 828        free(cb.buf);
 829
 830        return retval;
 831}
 832
 833int get_sha1_mb(const char *name, unsigned char *sha1)
 834{
 835        struct commit *one, *two;
 836        struct commit_list *mbs;
 837        unsigned char sha1_tmp[20];
 838        const char *dots;
 839        int st;
 840
 841        dots = strstr(name, "...");
 842        if (!dots)
 843                return get_sha1(name, sha1);
 844        if (dots == name)
 845                st = get_sha1("HEAD", sha1_tmp);
 846        else {
 847                struct strbuf sb;
 848                strbuf_init(&sb, dots - name);
 849                strbuf_add(&sb, name, dots - name);
 850                st = get_sha1(sb.buf, sha1_tmp);
 851                strbuf_release(&sb);
 852        }
 853        if (st)
 854                return st;
 855        one = lookup_commit_reference_gently(sha1_tmp, 0);
 856        if (!one)
 857                return -1;
 858
 859        if (get_sha1(dots[3] ? (dots + 3) : "HEAD", sha1_tmp))
 860                return -1;
 861        two = lookup_commit_reference_gently(sha1_tmp, 0);
 862        if (!two)
 863                return -1;
 864        mbs = get_merge_bases(one, two, 1);
 865        if (!mbs || mbs->next)
 866                st = -1;
 867        else {
 868                st = 0;
 869                hashcpy(sha1, mbs->item->object.sha1);
 870        }
 871        free_commit_list(mbs);
 872        return st;
 873}
 874
 875/*
 876 * This reads short-hand syntax that not only evaluates to a commit
 877 * object name, but also can act as if the end user spelled the name
 878 * of the branch from the command line.
 879 *
 880 * - "@{-N}" finds the name of the Nth previous branch we were on, and
 881 *   places the name of the branch in the given buf and returns the
 882 *   number of characters parsed if successful.
 883 *
 884 * - "<branch>@{upstream}" finds the name of the other ref that
 885 *   <branch> is configured to merge with (missing <branch> defaults
 886 *   to the current branch), and places the name of the branch in the
 887 *   given buf and returns the number of characters parsed if
 888 *   successful.
 889 *
 890 * If the input is not of the accepted format, it returns a negative
 891 * number to signal an error.
 892 *
 893 * If the input was ok but there are not N branch switches in the
 894 * reflog, it returns 0.
 895 */
 896int interpret_branch_name(const char *name, struct strbuf *buf)
 897{
 898        char *cp;
 899        struct branch *upstream;
 900        int namelen = strlen(name);
 901        int len = interpret_nth_prior_checkout(name, buf);
 902        int tmp_len;
 903
 904        if (!len)
 905                return len; /* syntax Ok, not enough switches */
 906        if (0 < len && len == namelen)
 907                return len; /* consumed all */
 908        else if (0 < len) {
 909                /* we have extra data, which might need further processing */
 910                struct strbuf tmp = STRBUF_INIT;
 911                int used = buf->len;
 912                int ret;
 913
 914                strbuf_add(buf, name + len, namelen - len);
 915                ret = interpret_branch_name(buf->buf, &tmp);
 916                /* that data was not interpreted, remove our cruft */
 917                if (ret < 0) {
 918                        strbuf_setlen(buf, used);
 919                        return len;
 920                }
 921                strbuf_reset(buf);
 922                strbuf_addbuf(buf, &tmp);
 923                strbuf_release(&tmp);
 924                /* tweak for size of {-N} versus expanded ref name */
 925                return ret - used + len;
 926        }
 927
 928        cp = strchr(name, '@');
 929        if (!cp)
 930                return -1;
 931        tmp_len = upstream_mark(cp, namelen - (cp - name));
 932        if (!tmp_len)
 933                return -1;
 934        len = cp + tmp_len - name;
 935        cp = xstrndup(name, cp - name);
 936        upstream = branch_get(*cp ? cp : NULL);
 937        if (!upstream
 938            || !upstream->merge
 939            || !upstream->merge[0]->dst)
 940                return error("No upstream branch found for '%s'", cp);
 941        free(cp);
 942        cp = shorten_unambiguous_ref(upstream->merge[0]->dst, 0);
 943        strbuf_reset(buf);
 944        strbuf_addstr(buf, cp);
 945        free(cp);
 946        return len;
 947}
 948
 949int strbuf_branchname(struct strbuf *sb, const char *name)
 950{
 951        int len = strlen(name);
 952        if (interpret_branch_name(name, sb) == len)
 953                return 0;
 954        strbuf_add(sb, name, len);
 955        return len;
 956}
 957
 958int strbuf_check_branch_ref(struct strbuf *sb, const char *name)
 959{
 960        strbuf_branchname(sb, name);
 961        if (name[0] == '-')
 962                return -1;
 963        strbuf_splice(sb, 0, 0, "refs/heads/", 11);
 964        return check_refname_format(sb->buf, 0);
 965}
 966
 967/*
 968 * This is like "get_sha1_basic()", except it allows "sha1 expressions",
 969 * notably "xyz^" for "parent of xyz"
 970 */
 971int get_sha1(const char *name, unsigned char *sha1)
 972{
 973        struct object_context unused;
 974        return get_sha1_with_context(name, sha1, &unused);
 975}
 976
 977/* Must be called only when object_name:filename doesn't exist. */
 978static void diagnose_invalid_sha1_path(const char *prefix,
 979                                       const char *filename,
 980                                       const unsigned char *tree_sha1,
 981                                       const char *object_name)
 982{
 983        struct stat st;
 984        unsigned char sha1[20];
 985        unsigned mode;
 986
 987        if (!prefix)
 988                prefix = "";
 989
 990        if (!lstat(filename, &st))
 991                die("Path '%s' exists on disk, but not in '%s'.",
 992                    filename, object_name);
 993        if (errno == ENOENT || errno == ENOTDIR) {
 994                char *fullname = xmalloc(strlen(filename)
 995                                             + strlen(prefix) + 1);
 996                strcpy(fullname, prefix);
 997                strcat(fullname, filename);
 998
 999                if (!get_tree_entry(tree_sha1, fullname,
1000                                    sha1, &mode)) {
1001                        die("Path '%s' exists, but not '%s'.\n"
1002                            "Did you mean '%s:%s' aka '%s:./%s'?",
1003                            fullname,
1004                            filename,
1005                            object_name,
1006                            fullname,
1007                            object_name,
1008                            filename);
1009                }
1010                die("Path '%s' does not exist in '%s'",
1011                    filename, object_name);
1012        }
1013}
1014
1015/* Must be called only when :stage:filename doesn't exist. */
1016static void diagnose_invalid_index_path(int stage,
1017                                        const char *prefix,
1018                                        const char *filename)
1019{
1020        struct stat st;
1021        struct cache_entry *ce;
1022        int pos;
1023        unsigned namelen = strlen(filename);
1024        unsigned fullnamelen;
1025        char *fullname;
1026
1027        if (!prefix)
1028                prefix = "";
1029
1030        /* Wrong stage number? */
1031        pos = cache_name_pos(filename, namelen);
1032        if (pos < 0)
1033                pos = -pos - 1;
1034        if (pos < active_nr) {
1035                ce = active_cache[pos];
1036                if (ce_namelen(ce) == namelen &&
1037                    !memcmp(ce->name, filename, namelen))
1038                        die("Path '%s' is in the index, but not at stage %d.\n"
1039                            "Did you mean ':%d:%s'?",
1040                            filename, stage,
1041                            ce_stage(ce), filename);
1042        }
1043
1044        /* Confusion between relative and absolute filenames? */
1045        fullnamelen = namelen + strlen(prefix);
1046        fullname = xmalloc(fullnamelen + 1);
1047        strcpy(fullname, prefix);
1048        strcat(fullname, filename);
1049        pos = cache_name_pos(fullname, fullnamelen);
1050        if (pos < 0)
1051                pos = -pos - 1;
1052        if (pos < active_nr) {
1053                ce = active_cache[pos];
1054                if (ce_namelen(ce) == fullnamelen &&
1055                    !memcmp(ce->name, fullname, fullnamelen))
1056                        die("Path '%s' is in the index, but not '%s'.\n"
1057                            "Did you mean ':%d:%s' aka ':%d:./%s'?",
1058                            fullname, filename,
1059                            ce_stage(ce), fullname,
1060                            ce_stage(ce), filename);
1061        }
1062
1063        if (!lstat(filename, &st))
1064                die("Path '%s' exists on disk, but not in the index.", filename);
1065        if (errno == ENOENT || errno == ENOTDIR)
1066                die("Path '%s' does not exist (neither on disk nor in the index).",
1067                    filename);
1068
1069        free(fullname);
1070}
1071
1072
1073static char *resolve_relative_path(const char *rel)
1074{
1075        if (prefixcmp(rel, "./") && prefixcmp(rel, "../"))
1076                return NULL;
1077
1078        if (!startup_info)
1079                die("BUG: startup_info struct is not initialized.");
1080
1081        if (!is_inside_work_tree())
1082                die("relative path syntax can't be used outside working tree.");
1083
1084        /* die() inside prefix_path() if resolved path is outside worktree */
1085        return prefix_path(startup_info->prefix,
1086                           startup_info->prefix ? strlen(startup_info->prefix) : 0,
1087                           rel);
1088}
1089
1090static int get_sha1_with_context_1(const char *name, unsigned char *sha1,
1091                                   struct object_context *oc,
1092                                   int only_to_die, const char *prefix)
1093{
1094        int ret, bracket_depth;
1095        int namelen = strlen(name);
1096        const char *cp;
1097
1098        memset(oc, 0, sizeof(*oc));
1099        oc->mode = S_IFINVALID;
1100        ret = get_sha1_1(name, namelen, sha1);
1101        if (!ret)
1102                return ret;
1103        /* sha1:path --> object name of path in ent sha1
1104         * :path -> object name of absolute path in index
1105         * :./path -> object name of path relative to cwd in index
1106         * :[0-3]:path -> object name of path in index at stage
1107         * :/foo -> recent commit matching foo
1108         */
1109        if (name[0] == ':') {
1110                int stage = 0;
1111                struct cache_entry *ce;
1112                char *new_path = NULL;
1113                int pos;
1114                if (!only_to_die && namelen > 2 && name[1] == '/') {
1115                        struct commit_list *list = NULL;
1116                        for_each_ref(handle_one_ref, &list);
1117                        return get_sha1_oneline(name + 2, sha1, list);
1118                }
1119                if (namelen < 3 ||
1120                    name[2] != ':' ||
1121                    name[1] < '0' || '3' < name[1])
1122                        cp = name + 1;
1123                else {
1124                        stage = name[1] - '0';
1125                        cp = name + 3;
1126                }
1127                new_path = resolve_relative_path(cp);
1128                if (!new_path) {
1129                        namelen = namelen - (cp - name);
1130                } else {
1131                        cp = new_path;
1132                        namelen = strlen(cp);
1133                }
1134
1135                strncpy(oc->path, cp,
1136                        sizeof(oc->path));
1137                oc->path[sizeof(oc->path)-1] = '\0';
1138
1139                if (!active_cache)
1140                        read_cache();
1141                pos = cache_name_pos(cp, namelen);
1142                if (pos < 0)
1143                        pos = -pos - 1;
1144                while (pos < active_nr) {
1145                        ce = active_cache[pos];
1146                        if (ce_namelen(ce) != namelen ||
1147                            memcmp(ce->name, cp, namelen))
1148                                break;
1149                        if (ce_stage(ce) == stage) {
1150                                hashcpy(sha1, ce->sha1);
1151                                oc->mode = ce->ce_mode;
1152                                free(new_path);
1153                                return 0;
1154                        }
1155                        pos++;
1156                }
1157                if (only_to_die && name[1] && name[1] != '/')
1158                        diagnose_invalid_index_path(stage, prefix, cp);
1159                free(new_path);
1160                return -1;
1161        }
1162        for (cp = name, bracket_depth = 0; *cp; cp++) {
1163                if (*cp == '{')
1164                        bracket_depth++;
1165                else if (bracket_depth && *cp == '}')
1166                        bracket_depth--;
1167                else if (!bracket_depth && *cp == ':')
1168                        break;
1169        }
1170        if (*cp == ':') {
1171                unsigned char tree_sha1[20];
1172                char *object_name = NULL;
1173                if (only_to_die) {
1174                        object_name = xmalloc(cp-name+1);
1175                        strncpy(object_name, name, cp-name);
1176                        object_name[cp-name] = '\0';
1177                }
1178                if (!get_sha1_1(name, cp-name, tree_sha1)) {
1179                        const char *filename = cp+1;
1180                        char *new_filename = NULL;
1181
1182                        new_filename = resolve_relative_path(filename);
1183                        if (new_filename)
1184                                filename = new_filename;
1185                        ret = get_tree_entry(tree_sha1, filename, sha1, &oc->mode);
1186                        if (only_to_die) {
1187                                diagnose_invalid_sha1_path(prefix, filename,
1188                                                           tree_sha1, object_name);
1189                                free(object_name);
1190                        }
1191                        hashcpy(oc->tree, tree_sha1);
1192                        strncpy(oc->path, filename,
1193                                sizeof(oc->path));
1194                        oc->path[sizeof(oc->path)-1] = '\0';
1195
1196                        free(new_filename);
1197                        return ret;
1198                } else {
1199                        if (only_to_die)
1200                                die("Invalid object name '%s'.", object_name);
1201                }
1202        }
1203        return ret;
1204}
1205
1206/*
1207 * Call this function when you know "name" given by the end user must
1208 * name an object but it doesn't; the function _may_ die with a better
1209 * diagnostic message than "no such object 'name'", e.g. "Path 'doc' does not
1210 * exist in 'HEAD'" when given "HEAD:doc", or it may return in which case
1211 * you have a chance to diagnose the error further.
1212 */
1213void maybe_die_on_misspelt_object_name(const char *name, const char *prefix)
1214{
1215        struct object_context oc;
1216        unsigned char sha1[20];
1217        get_sha1_with_context_1(name, sha1, &oc, 1, prefix);
1218}
1219
1220int get_sha1_with_context(const char *str, unsigned char *sha1, struct object_context *orc)
1221{
1222        return get_sha1_with_context_1(str, sha1, orc, 0, NULL);
1223}