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