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