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