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