refs.con commit Teach resolve_gitlink_ref() about the .git file (842abf0)
   1#include "cache.h"
   2#include "refs.h"
   3#include "object.h"
   4#include "tag.h"
   5#include "dir.h"
   6
   7/* ISSYMREF=01 and ISPACKED=02 are public interfaces */
   8#define REF_KNOWS_PEELED 04
   9
  10struct ref_list {
  11        struct ref_list *next;
  12        unsigned char flag; /* ISSYMREF? ISPACKED? */
  13        unsigned char sha1[20];
  14        unsigned char peeled[20];
  15        char name[FLEX_ARRAY];
  16};
  17
  18static const char *parse_ref_line(char *line, unsigned char *sha1)
  19{
  20        /*
  21         * 42: the answer to everything.
  22         *
  23         * In this case, it happens to be the answer to
  24         *  40 (length of sha1 hex representation)
  25         *  +1 (space in between hex and name)
  26         *  +1 (newline at the end of the line)
  27         */
  28        int len = strlen(line) - 42;
  29
  30        if (len <= 0)
  31                return NULL;
  32        if (get_sha1_hex(line, sha1) < 0)
  33                return NULL;
  34        if (!isspace(line[40]))
  35                return NULL;
  36        line += 41;
  37        if (isspace(*line))
  38                return NULL;
  39        if (line[len] != '\n')
  40                return NULL;
  41        line[len] = 0;
  42
  43        return line;
  44}
  45
  46static struct ref_list *add_ref(const char *name, const unsigned char *sha1,
  47                                int flag, struct ref_list *list,
  48                                struct ref_list **new_entry)
  49{
  50        int len;
  51        struct ref_list *entry;
  52
  53        /* Allocate it and add it in.. */
  54        len = strlen(name) + 1;
  55        entry = xmalloc(sizeof(struct ref_list) + len);
  56        hashcpy(entry->sha1, sha1);
  57        hashclr(entry->peeled);
  58        memcpy(entry->name, name, len);
  59        entry->flag = flag;
  60        entry->next = list;
  61        if (new_entry)
  62                *new_entry = entry;
  63        return entry;
  64}
  65
  66/* merge sort the ref list */
  67static struct ref_list *sort_ref_list(struct ref_list *list)
  68{
  69        int psize, qsize, last_merge_count, cmp;
  70        struct ref_list *p, *q, *l, *e;
  71        struct ref_list *new_list = list;
  72        int k = 1;
  73        int merge_count = 0;
  74
  75        if (!list)
  76                return list;
  77
  78        do {
  79                last_merge_count = merge_count;
  80                merge_count = 0;
  81
  82                psize = 0;
  83
  84                p = new_list;
  85                q = new_list;
  86                new_list = NULL;
  87                l = NULL;
  88
  89                while (p) {
  90                        merge_count++;
  91
  92                        while (psize < k && q->next) {
  93                                q = q->next;
  94                                psize++;
  95                        }
  96                        qsize = k;
  97
  98                        while ((psize > 0) || (qsize > 0 && q)) {
  99                                if (qsize == 0 || !q) {
 100                                        e = p;
 101                                        p = p->next;
 102                                        psize--;
 103                                } else if (psize == 0) {
 104                                        e = q;
 105                                        q = q->next;
 106                                        qsize--;
 107                                } else {
 108                                        cmp = strcmp(q->name, p->name);
 109                                        if (cmp < 0) {
 110                                                e = q;
 111                                                q = q->next;
 112                                                qsize--;
 113                                        } else if (cmp > 0) {
 114                                                e = p;
 115                                                p = p->next;
 116                                                psize--;
 117                                        } else {
 118                                                if (hashcmp(q->sha1, p->sha1))
 119                                                        die("Duplicated ref, and SHA1s don't match: %s",
 120                                                            q->name);
 121                                                warning("Duplicated ref: %s", q->name);
 122                                                e = q;
 123                                                q = q->next;
 124                                                qsize--;
 125                                                free(e);
 126                                                e = p;
 127                                                p = p->next;
 128                                                psize--;
 129                                        }
 130                                }
 131
 132                                e->next = NULL;
 133
 134                                if (l)
 135                                        l->next = e;
 136                                if (!new_list)
 137                                        new_list = e;
 138                                l = e;
 139                        }
 140
 141                        p = q;
 142                };
 143
 144                k = k * 2;
 145        } while ((last_merge_count != merge_count) || (last_merge_count != 1));
 146
 147        return new_list;
 148}
 149
 150/*
 151 * Future: need to be in "struct repository"
 152 * when doing a full libification.
 153 */
 154static struct cached_refs {
 155        char did_loose;
 156        char did_packed;
 157        struct ref_list *loose;
 158        struct ref_list *packed;
 159} cached_refs;
 160static struct ref_list *current_ref;
 161
 162static void free_ref_list(struct ref_list *list)
 163{
 164        struct ref_list *next;
 165        for ( ; list; list = next) {
 166                next = list->next;
 167                free(list);
 168        }
 169}
 170
 171static void invalidate_cached_refs(void)
 172{
 173        struct cached_refs *ca = &cached_refs;
 174
 175        if (ca->did_loose && ca->loose)
 176                free_ref_list(ca->loose);
 177        if (ca->did_packed && ca->packed)
 178                free_ref_list(ca->packed);
 179        ca->loose = ca->packed = NULL;
 180        ca->did_loose = ca->did_packed = 0;
 181}
 182
 183static void read_packed_refs(FILE *f, struct cached_refs *cached_refs)
 184{
 185        struct ref_list *list = NULL;
 186        struct ref_list *last = NULL;
 187        char refline[PATH_MAX];
 188        int flag = REF_ISPACKED;
 189
 190        while (fgets(refline, sizeof(refline), f)) {
 191                unsigned char sha1[20];
 192                const char *name;
 193                static const char header[] = "# pack-refs with:";
 194
 195                if (!strncmp(refline, header, sizeof(header)-1)) {
 196                        const char *traits = refline + sizeof(header) - 1;
 197                        if (strstr(traits, " peeled "))
 198                                flag |= REF_KNOWS_PEELED;
 199                        /* perhaps other traits later as well */
 200                        continue;
 201                }
 202
 203                name = parse_ref_line(refline, sha1);
 204                if (name) {
 205                        list = add_ref(name, sha1, flag, list, &last);
 206                        continue;
 207                }
 208                if (last &&
 209                    refline[0] == '^' &&
 210                    strlen(refline) == 42 &&
 211                    refline[41] == '\n' &&
 212                    !get_sha1_hex(refline + 1, sha1))
 213                        hashcpy(last->peeled, sha1);
 214        }
 215        cached_refs->packed = sort_ref_list(list);
 216}
 217
 218static struct ref_list *get_packed_refs(void)
 219{
 220        if (!cached_refs.did_packed) {
 221                FILE *f = fopen(git_path("packed-refs"), "r");
 222                cached_refs.packed = NULL;
 223                if (f) {
 224                        read_packed_refs(f, &cached_refs);
 225                        fclose(f);
 226                }
 227                cached_refs.did_packed = 1;
 228        }
 229        return cached_refs.packed;
 230}
 231
 232static struct ref_list *get_ref_dir(const char *base, struct ref_list *list)
 233{
 234        DIR *dir = opendir(git_path("%s", base));
 235
 236        if (dir) {
 237                struct dirent *de;
 238                int baselen = strlen(base);
 239                char *ref = xmalloc(baselen + 257);
 240
 241                memcpy(ref, base, baselen);
 242                if (baselen && base[baselen-1] != '/')
 243                        ref[baselen++] = '/';
 244
 245                while ((de = readdir(dir)) != NULL) {
 246                        unsigned char sha1[20];
 247                        struct stat st;
 248                        int flag;
 249                        int namelen;
 250
 251                        if (de->d_name[0] == '.')
 252                                continue;
 253                        namelen = strlen(de->d_name);
 254                        if (namelen > 255)
 255                                continue;
 256                        if (has_extension(de->d_name, ".lock"))
 257                                continue;
 258                        memcpy(ref + baselen, de->d_name, namelen+1);
 259                        if (stat(git_path("%s", ref), &st) < 0)
 260                                continue;
 261                        if (S_ISDIR(st.st_mode)) {
 262                                list = get_ref_dir(ref, list);
 263                                continue;
 264                        }
 265                        if (!resolve_ref(ref, sha1, 1, &flag)) {
 266                                error("%s points nowhere!", ref);
 267                                continue;
 268                        }
 269                        list = add_ref(ref, sha1, flag, list, NULL);
 270                }
 271                free(ref);
 272                closedir(dir);
 273        }
 274        return sort_ref_list(list);
 275}
 276
 277static struct ref_list *get_loose_refs(void)
 278{
 279        if (!cached_refs.did_loose) {
 280                cached_refs.loose = get_ref_dir("refs", NULL);
 281                cached_refs.did_loose = 1;
 282        }
 283        return cached_refs.loose;
 284}
 285
 286/* We allow "recursive" symbolic refs. Only within reason, though */
 287#define MAXDEPTH 5
 288#define MAXREFLEN (1024)
 289
 290static int resolve_gitlink_packed_ref(char *name, int pathlen, const char *refname, unsigned char *result)
 291{
 292        FILE *f;
 293        struct cached_refs refs;
 294        struct ref_list *ref;
 295        int retval;
 296
 297        strcpy(name + pathlen, "packed-refs");
 298        f = fopen(name, "r");
 299        if (!f)
 300                return -1;
 301        read_packed_refs(f, &refs);
 302        fclose(f);
 303        ref = refs.packed;
 304        retval = -1;
 305        while (ref) {
 306                if (!strcmp(ref->name, refname)) {
 307                        retval = 0;
 308                        memcpy(result, ref->sha1, 20);
 309                        break;
 310                }
 311                ref = ref->next;
 312        }
 313        free_ref_list(refs.packed);
 314        return retval;
 315}
 316
 317static int resolve_gitlink_ref_recursive(char *name, int pathlen, const char *refname, unsigned char *result, int recursion)
 318{
 319        int fd, len = strlen(refname);
 320        char buffer[128], *p;
 321
 322        if (recursion > MAXDEPTH || len > MAXREFLEN)
 323                return -1;
 324        memcpy(name + pathlen, refname, len+1);
 325        fd = open(name, O_RDONLY);
 326        if (fd < 0)
 327                return resolve_gitlink_packed_ref(name, pathlen, refname, result);
 328
 329        len = read(fd, buffer, sizeof(buffer)-1);
 330        close(fd);
 331        if (len < 0)
 332                return -1;
 333        while (len && isspace(buffer[len-1]))
 334                len--;
 335        buffer[len] = 0;
 336
 337        /* Was it a detached head or an old-fashioned symlink? */
 338        if (!get_sha1_hex(buffer, result))
 339                return 0;
 340
 341        /* Symref? */
 342        if (strncmp(buffer, "ref:", 4))
 343                return -1;
 344        p = buffer + 4;
 345        while (isspace(*p))
 346                p++;
 347
 348        return resolve_gitlink_ref_recursive(name, pathlen, p, result, recursion+1);
 349}
 350
 351int resolve_gitlink_ref(const char *path, const char *refname, unsigned char *result)
 352{
 353        int len = strlen(path), retval;
 354        char *gitdir;
 355        const char *tmp;
 356
 357        while (len && path[len-1] == '/')
 358                len--;
 359        if (!len)
 360                return -1;
 361        gitdir = xmalloc(len + MAXREFLEN + 8);
 362        memcpy(gitdir, path, len);
 363        memcpy(gitdir + len, "/.git", 6);
 364        len += 5;
 365
 366        tmp = read_gitfile_gently(gitdir);
 367        if (tmp) {
 368                free(gitdir);
 369                len = strlen(tmp);
 370                gitdir = xmalloc(len + MAXREFLEN + 3);
 371                memcpy(gitdir, tmp, len);
 372        }
 373        gitdir[len] = '/';
 374        gitdir[++len] = '\0';
 375        retval = resolve_gitlink_ref_recursive(gitdir, len, refname, result, 0);
 376        free(gitdir);
 377        return retval;
 378}
 379
 380const char *resolve_ref(const char *ref, unsigned char *sha1, int reading, int *flag)
 381{
 382        int depth = MAXDEPTH, len;
 383        char buffer[256];
 384        static char ref_buffer[256];
 385
 386        if (flag)
 387                *flag = 0;
 388
 389        for (;;) {
 390                const char *path = git_path("%s", ref);
 391                struct stat st;
 392                char *buf;
 393                int fd;
 394
 395                if (--depth < 0)
 396                        return NULL;
 397
 398                /* Special case: non-existing file.
 399                 * Not having the refs/heads/new-branch is OK
 400                 * if we are writing into it, so is .git/HEAD
 401                 * that points at refs/heads/master still to be
 402                 * born.  It is NOT OK if we are resolving for
 403                 * reading.
 404                 */
 405                if (lstat(path, &st) < 0) {
 406                        struct ref_list *list = get_packed_refs();
 407                        while (list) {
 408                                if (!strcmp(ref, list->name)) {
 409                                        hashcpy(sha1, list->sha1);
 410                                        if (flag)
 411                                                *flag |= REF_ISPACKED;
 412                                        return ref;
 413                                }
 414                                list = list->next;
 415                        }
 416                        if (reading || errno != ENOENT)
 417                                return NULL;
 418                        hashclr(sha1);
 419                        return ref;
 420                }
 421
 422                /* Follow "normalized" - ie "refs/.." symlinks by hand */
 423                if (S_ISLNK(st.st_mode)) {
 424                        len = readlink(path, buffer, sizeof(buffer)-1);
 425                        if (len >= 5 && !memcmp("refs/", buffer, 5)) {
 426                                buffer[len] = 0;
 427                                strcpy(ref_buffer, buffer);
 428                                ref = ref_buffer;
 429                                if (flag)
 430                                        *flag |= REF_ISSYMREF;
 431                                continue;
 432                        }
 433                }
 434
 435                /* Is it a directory? */
 436                if (S_ISDIR(st.st_mode)) {
 437                        errno = EISDIR;
 438                        return NULL;
 439                }
 440
 441                /*
 442                 * Anything else, just open it and try to use it as
 443                 * a ref
 444                 */
 445                fd = open(path, O_RDONLY);
 446                if (fd < 0)
 447                        return NULL;
 448                len = read_in_full(fd, buffer, sizeof(buffer)-1);
 449                close(fd);
 450
 451                /*
 452                 * Is it a symbolic ref?
 453                 */
 454                if (len < 4 || memcmp("ref:", buffer, 4))
 455                        break;
 456                buf = buffer + 4;
 457                len -= 4;
 458                while (len && isspace(*buf))
 459                        buf++, len--;
 460                while (len && isspace(buf[len-1]))
 461                        len--;
 462                buf[len] = 0;
 463                memcpy(ref_buffer, buf, len + 1);
 464                ref = ref_buffer;
 465                if (flag)
 466                        *flag |= REF_ISSYMREF;
 467        }
 468        if (len < 40 || get_sha1_hex(buffer, sha1))
 469                return NULL;
 470        return ref;
 471}
 472
 473int read_ref(const char *ref, unsigned char *sha1)
 474{
 475        if (resolve_ref(ref, sha1, 1, NULL))
 476                return 0;
 477        return -1;
 478}
 479
 480static int do_one_ref(const char *base, each_ref_fn fn, int trim,
 481                      void *cb_data, struct ref_list *entry)
 482{
 483        if (strncmp(base, entry->name, trim))
 484                return 0;
 485        if (is_null_sha1(entry->sha1))
 486                return 0;
 487        if (!has_sha1_file(entry->sha1)) {
 488                error("%s does not point to a valid object!", entry->name);
 489                return 0;
 490        }
 491        current_ref = entry;
 492        return fn(entry->name + trim, entry->sha1, entry->flag, cb_data);
 493}
 494
 495int peel_ref(const char *ref, unsigned char *sha1)
 496{
 497        int flag;
 498        unsigned char base[20];
 499        struct object *o;
 500
 501        if (current_ref && (current_ref->name == ref
 502                || !strcmp(current_ref->name, ref))) {
 503                if (current_ref->flag & REF_KNOWS_PEELED) {
 504                        hashcpy(sha1, current_ref->peeled);
 505                        return 0;
 506                }
 507                hashcpy(base, current_ref->sha1);
 508                goto fallback;
 509        }
 510
 511        if (!resolve_ref(ref, base, 1, &flag))
 512                return -1;
 513
 514        if ((flag & REF_ISPACKED)) {
 515                struct ref_list *list = get_packed_refs();
 516
 517                while (list) {
 518                        if (!strcmp(list->name, ref)) {
 519                                if (list->flag & REF_KNOWS_PEELED) {
 520                                        hashcpy(sha1, list->peeled);
 521                                        return 0;
 522                                }
 523                                /* older pack-refs did not leave peeled ones */
 524                                break;
 525                        }
 526                        list = list->next;
 527                }
 528        }
 529
 530fallback:
 531        o = parse_object(base);
 532        if (o && o->type == OBJ_TAG) {
 533                o = deref_tag(o, ref, 0);
 534                if (o) {
 535                        hashcpy(sha1, o->sha1);
 536                        return 0;
 537                }
 538        }
 539        return -1;
 540}
 541
 542static int do_for_each_ref(const char *base, each_ref_fn fn, int trim,
 543                           void *cb_data)
 544{
 545        int retval = 0;
 546        struct ref_list *packed = get_packed_refs();
 547        struct ref_list *loose = get_loose_refs();
 548
 549        while (packed && loose) {
 550                struct ref_list *entry;
 551                int cmp = strcmp(packed->name, loose->name);
 552                if (!cmp) {
 553                        packed = packed->next;
 554                        continue;
 555                }
 556                if (cmp > 0) {
 557                        entry = loose;
 558                        loose = loose->next;
 559                } else {
 560                        entry = packed;
 561                        packed = packed->next;
 562                }
 563                retval = do_one_ref(base, fn, trim, cb_data, entry);
 564                if (retval)
 565                        goto end_each;
 566        }
 567
 568        for (packed = packed ? packed : loose; packed; packed = packed->next) {
 569                retval = do_one_ref(base, fn, trim, cb_data, packed);
 570                if (retval)
 571                        goto end_each;
 572        }
 573
 574end_each:
 575        current_ref = NULL;
 576        return retval;
 577}
 578
 579int head_ref(each_ref_fn fn, void *cb_data)
 580{
 581        unsigned char sha1[20];
 582        int flag;
 583
 584        if (resolve_ref("HEAD", sha1, 1, &flag))
 585                return fn("HEAD", sha1, flag, cb_data);
 586        return 0;
 587}
 588
 589int for_each_ref(each_ref_fn fn, void *cb_data)
 590{
 591        return do_for_each_ref("refs/", fn, 0, cb_data);
 592}
 593
 594int for_each_tag_ref(each_ref_fn fn, void *cb_data)
 595{
 596        return do_for_each_ref("refs/tags/", fn, 10, cb_data);
 597}
 598
 599int for_each_branch_ref(each_ref_fn fn, void *cb_data)
 600{
 601        return do_for_each_ref("refs/heads/", fn, 11, cb_data);
 602}
 603
 604int for_each_remote_ref(each_ref_fn fn, void *cb_data)
 605{
 606        return do_for_each_ref("refs/remotes/", fn, 13, cb_data);
 607}
 608
 609/*
 610 * Make sure "ref" is something reasonable to have under ".git/refs/";
 611 * We do not like it if:
 612 *
 613 * - any path component of it begins with ".", or
 614 * - it has double dots "..", or
 615 * - it has ASCII control character, "~", "^", ":" or SP, anywhere, or
 616 * - it ends with a "/".
 617 */
 618
 619static inline int bad_ref_char(int ch)
 620{
 621        if (((unsigned) ch) <= ' ' ||
 622            ch == '~' || ch == '^' || ch == ':')
 623                return 1;
 624        /* 2.13 Pattern Matching Notation */
 625        if (ch == '?' || ch == '[') /* Unsupported */
 626                return 1;
 627        if (ch == '*') /* Supported at the end */
 628                return 2;
 629        return 0;
 630}
 631
 632int check_ref_format(const char *ref)
 633{
 634        int ch, level, bad_type;
 635        const char *cp = ref;
 636
 637        level = 0;
 638        while (1) {
 639                while ((ch = *cp++) == '/')
 640                        ; /* tolerate duplicated slashes */
 641                if (!ch)
 642                        /* should not end with slashes */
 643                        return CHECK_REF_FORMAT_ERROR;
 644
 645                /* we are at the beginning of the path component */
 646                if (ch == '.')
 647                        return CHECK_REF_FORMAT_ERROR;
 648                bad_type = bad_ref_char(ch);
 649                if (bad_type) {
 650                        return (bad_type == 2 && !*cp)
 651                                ? CHECK_REF_FORMAT_WILDCARD
 652                                : CHECK_REF_FORMAT_ERROR;
 653                }
 654
 655                /* scan the rest of the path component */
 656                while ((ch = *cp++) != 0) {
 657                        bad_type = bad_ref_char(ch);
 658                        if (bad_type) {
 659                                return (bad_type == 2 && !*cp)
 660                                        ? CHECK_REF_FORMAT_WILDCARD
 661                                        : CHECK_REF_FORMAT_ERROR;
 662                        }
 663                        if (ch == '/')
 664                                break;
 665                        if (ch == '.' && *cp == '.')
 666                                return CHECK_REF_FORMAT_ERROR;
 667                }
 668                level++;
 669                if (!ch) {
 670                        if (level < 2)
 671                                return CHECK_REF_FORMAT_ONELEVEL;
 672                        return CHECK_REF_FORMAT_OK;
 673                }
 674        }
 675}
 676
 677const char *ref_rev_parse_rules[] = {
 678        "%.*s",
 679        "refs/%.*s",
 680        "refs/tags/%.*s",
 681        "refs/heads/%.*s",
 682        "refs/remotes/%.*s",
 683        "refs/remotes/%.*s/HEAD",
 684        NULL
 685};
 686
 687const char *ref_fetch_rules[] = {
 688        "%.*s",
 689        "refs/%.*s",
 690        "refs/heads/%.*s",
 691        NULL
 692};
 693
 694int refname_match(const char *abbrev_name, const char *full_name, const char **rules)
 695{
 696        const char **p;
 697        const int abbrev_name_len = strlen(abbrev_name);
 698
 699        for (p = rules; *p; p++) {
 700                if (!strcmp(full_name, mkpath(*p, abbrev_name_len, abbrev_name))) {
 701                        return 1;
 702                }
 703        }
 704
 705        return 0;
 706}
 707
 708static struct ref_lock *verify_lock(struct ref_lock *lock,
 709        const unsigned char *old_sha1, int mustexist)
 710{
 711        if (!resolve_ref(lock->ref_name, lock->old_sha1, mustexist, NULL)) {
 712                error("Can't verify ref %s", lock->ref_name);
 713                unlock_ref(lock);
 714                return NULL;
 715        }
 716        if (hashcmp(lock->old_sha1, old_sha1)) {
 717                error("Ref %s is at %s but expected %s", lock->ref_name,
 718                        sha1_to_hex(lock->old_sha1), sha1_to_hex(old_sha1));
 719                unlock_ref(lock);
 720                return NULL;
 721        }
 722        return lock;
 723}
 724
 725static int remove_empty_directories(const char *file)
 726{
 727        /* we want to create a file but there is a directory there;
 728         * if that is an empty directory (or a directory that contains
 729         * only empty directories), remove them.
 730         */
 731        struct strbuf path;
 732        int result;
 733
 734        strbuf_init(&path, 20);
 735        strbuf_addstr(&path, file);
 736
 737        result = remove_dir_recursively(&path, 1);
 738
 739        strbuf_release(&path);
 740
 741        return result;
 742}
 743
 744static int is_refname_available(const char *ref, const char *oldref,
 745                                struct ref_list *list, int quiet)
 746{
 747        int namlen = strlen(ref); /* e.g. 'foo/bar' */
 748        while (list) {
 749                /* list->name could be 'foo' or 'foo/bar/baz' */
 750                if (!oldref || strcmp(oldref, list->name)) {
 751                        int len = strlen(list->name);
 752                        int cmplen = (namlen < len) ? namlen : len;
 753                        const char *lead = (namlen < len) ? list->name : ref;
 754                        if (!strncmp(ref, list->name, cmplen) &&
 755                            lead[cmplen] == '/') {
 756                                if (!quiet)
 757                                        error("'%s' exists; cannot create '%s'",
 758                                              list->name, ref);
 759                                return 0;
 760                        }
 761                }
 762                list = list->next;
 763        }
 764        return 1;
 765}
 766
 767static struct ref_lock *lock_ref_sha1_basic(const char *ref, const unsigned char *old_sha1, int flags, int *type_p)
 768{
 769        char *ref_file;
 770        const char *orig_ref = ref;
 771        struct ref_lock *lock;
 772        struct stat st;
 773        int last_errno = 0;
 774        int type;
 775        int mustexist = (old_sha1 && !is_null_sha1(old_sha1));
 776
 777        lock = xcalloc(1, sizeof(struct ref_lock));
 778        lock->lock_fd = -1;
 779
 780        ref = resolve_ref(ref, lock->old_sha1, mustexist, &type);
 781        if (!ref && errno == EISDIR) {
 782                /* we are trying to lock foo but we used to
 783                 * have foo/bar which now does not exist;
 784                 * it is normal for the empty directory 'foo'
 785                 * to remain.
 786                 */
 787                ref_file = git_path("%s", orig_ref);
 788                if (remove_empty_directories(ref_file)) {
 789                        last_errno = errno;
 790                        error("there are still refs under '%s'", orig_ref);
 791                        goto error_return;
 792                }
 793                ref = resolve_ref(orig_ref, lock->old_sha1, mustexist, &type);
 794        }
 795        if (type_p)
 796            *type_p = type;
 797        if (!ref) {
 798                last_errno = errno;
 799                error("unable to resolve reference %s: %s",
 800                        orig_ref, strerror(errno));
 801                goto error_return;
 802        }
 803        /* When the ref did not exist and we are creating it,
 804         * make sure there is no existing ref that is packed
 805         * whose name begins with our refname, nor a ref whose
 806         * name is a proper prefix of our refname.
 807         */
 808        if (is_null_sha1(lock->old_sha1) &&
 809            !is_refname_available(ref, NULL, get_packed_refs(), 0))
 810                goto error_return;
 811
 812        lock->lk = xcalloc(1, sizeof(struct lock_file));
 813
 814        if (flags & REF_NODEREF)
 815                ref = orig_ref;
 816        lock->ref_name = xstrdup(ref);
 817        lock->orig_ref_name = xstrdup(orig_ref);
 818        ref_file = git_path("%s", ref);
 819        if (lstat(ref_file, &st) && errno == ENOENT)
 820                lock->force_write = 1;
 821        if ((flags & REF_NODEREF) && (type & REF_ISSYMREF))
 822                lock->force_write = 1;
 823
 824        if (safe_create_leading_directories(ref_file)) {
 825                last_errno = errno;
 826                error("unable to create directory for %s", ref_file);
 827                goto error_return;
 828        }
 829        lock->lock_fd = hold_lock_file_for_update(lock->lk, ref_file, 1);
 830
 831        return old_sha1 ? verify_lock(lock, old_sha1, mustexist) : lock;
 832
 833 error_return:
 834        unlock_ref(lock);
 835        errno = last_errno;
 836        return NULL;
 837}
 838
 839struct ref_lock *lock_ref_sha1(const char *ref, const unsigned char *old_sha1)
 840{
 841        char refpath[PATH_MAX];
 842        if (check_ref_format(ref))
 843                return NULL;
 844        strcpy(refpath, mkpath("refs/%s", ref));
 845        return lock_ref_sha1_basic(refpath, old_sha1, 0, NULL);
 846}
 847
 848struct ref_lock *lock_any_ref_for_update(const char *ref, const unsigned char *old_sha1, int flags)
 849{
 850        switch (check_ref_format(ref)) {
 851        default:
 852                return NULL;
 853        case 0:
 854        case CHECK_REF_FORMAT_ONELEVEL:
 855                return lock_ref_sha1_basic(ref, old_sha1, flags, NULL);
 856        }
 857}
 858
 859static struct lock_file packlock;
 860
 861static int repack_without_ref(const char *refname)
 862{
 863        struct ref_list *list, *packed_ref_list;
 864        int fd;
 865        int found = 0;
 866
 867        packed_ref_list = get_packed_refs();
 868        for (list = packed_ref_list; list; list = list->next) {
 869                if (!strcmp(refname, list->name)) {
 870                        found = 1;
 871                        break;
 872                }
 873        }
 874        if (!found)
 875                return 0;
 876        fd = hold_lock_file_for_update(&packlock, git_path("packed-refs"), 0);
 877        if (fd < 0)
 878                return error("cannot delete '%s' from packed refs", refname);
 879
 880        for (list = packed_ref_list; list; list = list->next) {
 881                char line[PATH_MAX + 100];
 882                int len;
 883
 884                if (!strcmp(refname, list->name))
 885                        continue;
 886                len = snprintf(line, sizeof(line), "%s %s\n",
 887                               sha1_to_hex(list->sha1), list->name);
 888                /* this should not happen but just being defensive */
 889                if (len > sizeof(line))
 890                        die("too long a refname '%s'", list->name);
 891                write_or_die(fd, line, len);
 892        }
 893        return commit_lock_file(&packlock);
 894}
 895
 896int delete_ref(const char *refname, const unsigned char *sha1)
 897{
 898        struct ref_lock *lock;
 899        int err, i, ret = 0, flag = 0;
 900
 901        lock = lock_ref_sha1_basic(refname, sha1, 0, &flag);
 902        if (!lock)
 903                return 1;
 904        if (!(flag & REF_ISPACKED)) {
 905                /* loose */
 906                i = strlen(lock->lk->filename) - 5; /* .lock */
 907                lock->lk->filename[i] = 0;
 908                err = unlink(lock->lk->filename);
 909                if (err) {
 910                        ret = 1;
 911                        error("unlink(%s) failed: %s",
 912                              lock->lk->filename, strerror(errno));
 913                }
 914                lock->lk->filename[i] = '.';
 915        }
 916        /* removing the loose one could have resurrected an earlier
 917         * packed one.  Also, if it was not loose we need to repack
 918         * without it.
 919         */
 920        ret |= repack_without_ref(refname);
 921
 922        err = unlink(git_path("logs/%s", lock->ref_name));
 923        if (err && errno != ENOENT)
 924                fprintf(stderr, "warning: unlink(%s) failed: %s",
 925                        git_path("logs/%s", lock->ref_name), strerror(errno));
 926        invalidate_cached_refs();
 927        unlock_ref(lock);
 928        return ret;
 929}
 930
 931int rename_ref(const char *oldref, const char *newref, const char *logmsg)
 932{
 933        static const char renamed_ref[] = "RENAMED-REF";
 934        unsigned char sha1[20], orig_sha1[20];
 935        int flag = 0, logmoved = 0;
 936        struct ref_lock *lock;
 937        struct stat loginfo;
 938        int log = !lstat(git_path("logs/%s", oldref), &loginfo);
 939
 940        if (S_ISLNK(loginfo.st_mode))
 941                return error("reflog for %s is a symlink", oldref);
 942
 943        if (!resolve_ref(oldref, orig_sha1, 1, &flag))
 944                return error("refname %s not found", oldref);
 945
 946        if (!is_refname_available(newref, oldref, get_packed_refs(), 0))
 947                return 1;
 948
 949        if (!is_refname_available(newref, oldref, get_loose_refs(), 0))
 950                return 1;
 951
 952        lock = lock_ref_sha1_basic(renamed_ref, NULL, 0, NULL);
 953        if (!lock)
 954                return error("unable to lock %s", renamed_ref);
 955        lock->force_write = 1;
 956        if (write_ref_sha1(lock, orig_sha1, logmsg))
 957                return error("unable to save current sha1 in %s", renamed_ref);
 958
 959        if (log && rename(git_path("logs/%s", oldref), git_path("tmp-renamed-log")))
 960                return error("unable to move logfile logs/%s to tmp-renamed-log: %s",
 961                        oldref, strerror(errno));
 962
 963        if (delete_ref(oldref, orig_sha1)) {
 964                error("unable to delete old %s", oldref);
 965                goto rollback;
 966        }
 967
 968        if (resolve_ref(newref, sha1, 1, &flag) && delete_ref(newref, sha1)) {
 969                if (errno==EISDIR) {
 970                        if (remove_empty_directories(git_path("%s", newref))) {
 971                                error("Directory not empty: %s", newref);
 972                                goto rollback;
 973                        }
 974                } else {
 975                        error("unable to delete existing %s", newref);
 976                        goto rollback;
 977                }
 978        }
 979
 980        if (log && safe_create_leading_directories(git_path("logs/%s", newref))) {
 981                error("unable to create directory for %s", newref);
 982                goto rollback;
 983        }
 984
 985 retry:
 986        if (log && rename(git_path("tmp-renamed-log"), git_path("logs/%s", newref))) {
 987                if (errno==EISDIR || errno==ENOTDIR) {
 988                        /*
 989                         * rename(a, b) when b is an existing
 990                         * directory ought to result in ISDIR, but
 991                         * Solaris 5.8 gives ENOTDIR.  Sheesh.
 992                         */
 993                        if (remove_empty_directories(git_path("logs/%s", newref))) {
 994                                error("Directory not empty: logs/%s", newref);
 995                                goto rollback;
 996                        }
 997                        goto retry;
 998                } else {
 999                        error("unable to move logfile tmp-renamed-log to logs/%s: %s",
1000                                newref, strerror(errno));
1001                        goto rollback;
1002                }
1003        }
1004        logmoved = log;
1005
1006        lock = lock_ref_sha1_basic(newref, NULL, 0, NULL);
1007        if (!lock) {
1008                error("unable to lock %s for update", newref);
1009                goto rollback;
1010        }
1011
1012        lock->force_write = 1;
1013        hashcpy(lock->old_sha1, orig_sha1);
1014        if (write_ref_sha1(lock, orig_sha1, logmsg)) {
1015                error("unable to write current sha1 into %s", newref);
1016                goto rollback;
1017        }
1018
1019        return 0;
1020
1021 rollback:
1022        lock = lock_ref_sha1_basic(oldref, NULL, 0, NULL);
1023        if (!lock) {
1024                error("unable to lock %s for rollback", oldref);
1025                goto rollbacklog;
1026        }
1027
1028        lock->force_write = 1;
1029        flag = log_all_ref_updates;
1030        log_all_ref_updates = 0;
1031        if (write_ref_sha1(lock, orig_sha1, NULL))
1032                error("unable to write current sha1 into %s", oldref);
1033        log_all_ref_updates = flag;
1034
1035 rollbacklog:
1036        if (logmoved && rename(git_path("logs/%s", newref), git_path("logs/%s", oldref)))
1037                error("unable to restore logfile %s from %s: %s",
1038                        oldref, newref, strerror(errno));
1039        if (!logmoved && log &&
1040            rename(git_path("tmp-renamed-log"), git_path("logs/%s", oldref)))
1041                error("unable to restore logfile %s from tmp-renamed-log: %s",
1042                        oldref, strerror(errno));
1043
1044        return 1;
1045}
1046
1047int close_ref(struct ref_lock *lock)
1048{
1049        if (close_lock_file(lock->lk))
1050                return -1;
1051        lock->lock_fd = -1;
1052        return 0;
1053}
1054
1055int commit_ref(struct ref_lock *lock)
1056{
1057        if (commit_lock_file(lock->lk))
1058                return -1;
1059        lock->lock_fd = -1;
1060        return 0;
1061}
1062
1063void unlock_ref(struct ref_lock *lock)
1064{
1065        /* Do not free lock->lk -- atexit() still looks at them */
1066        if (lock->lk)
1067                rollback_lock_file(lock->lk);
1068        free(lock->ref_name);
1069        free(lock->orig_ref_name);
1070        free(lock);
1071}
1072
1073/*
1074 * copy the reflog message msg to buf, which has been allocated sufficiently
1075 * large, while cleaning up the whitespaces.  Especially, convert LF to space,
1076 * because reflog file is one line per entry.
1077 */
1078static int copy_msg(char *buf, const char *msg)
1079{
1080        char *cp = buf;
1081        char c;
1082        int wasspace = 1;
1083
1084        *cp++ = '\t';
1085        while ((c = *msg++)) {
1086                if (wasspace && isspace(c))
1087                        continue;
1088                wasspace = isspace(c);
1089                if (wasspace)
1090                        c = ' ';
1091                *cp++ = c;
1092        }
1093        while (buf < cp && isspace(cp[-1]))
1094                cp--;
1095        *cp++ = '\n';
1096        return cp - buf;
1097}
1098
1099static int log_ref_write(const char *ref_name, const unsigned char *old_sha1,
1100                         const unsigned char *new_sha1, const char *msg)
1101{
1102        int logfd, written, oflags = O_APPEND | O_WRONLY;
1103        unsigned maxlen, len;
1104        int msglen;
1105        char *log_file, *logrec;
1106        const char *committer;
1107
1108        if (log_all_ref_updates < 0)
1109                log_all_ref_updates = !is_bare_repository();
1110
1111        log_file = git_path("logs/%s", ref_name);
1112
1113        if (log_all_ref_updates &&
1114            (!prefixcmp(ref_name, "refs/heads/") ||
1115             !prefixcmp(ref_name, "refs/remotes/") ||
1116             !strcmp(ref_name, "HEAD"))) {
1117                if (safe_create_leading_directories(log_file) < 0)
1118                        return error("unable to create directory for %s",
1119                                     log_file);
1120                oflags |= O_CREAT;
1121        }
1122
1123        logfd = open(log_file, oflags, 0666);
1124        if (logfd < 0) {
1125                if (!(oflags & O_CREAT) && errno == ENOENT)
1126                        return 0;
1127
1128                if ((oflags & O_CREAT) && errno == EISDIR) {
1129                        if (remove_empty_directories(log_file)) {
1130                                return error("There are still logs under '%s'",
1131                                             log_file);
1132                        }
1133                        logfd = open(log_file, oflags, 0666);
1134                }
1135
1136                if (logfd < 0)
1137                        return error("Unable to append to %s: %s",
1138                                     log_file, strerror(errno));
1139        }
1140
1141        adjust_shared_perm(log_file);
1142
1143        msglen = msg ? strlen(msg) : 0;
1144        committer = git_committer_info(0);
1145        maxlen = strlen(committer) + msglen + 100;
1146        logrec = xmalloc(maxlen);
1147        len = sprintf(logrec, "%s %s %s\n",
1148                      sha1_to_hex(old_sha1),
1149                      sha1_to_hex(new_sha1),
1150                      committer);
1151        if (msglen)
1152                len += copy_msg(logrec + len - 1, msg) - 1;
1153        written = len <= maxlen ? write_in_full(logfd, logrec, len) : -1;
1154        free(logrec);
1155        if (close(logfd) != 0 || written != len)
1156                return error("Unable to append to %s", log_file);
1157        return 0;
1158}
1159
1160static int is_branch(const char *refname)
1161{
1162        return !strcmp(refname, "HEAD") || !prefixcmp(refname, "refs/heads/");
1163}
1164
1165int write_ref_sha1(struct ref_lock *lock,
1166        const unsigned char *sha1, const char *logmsg)
1167{
1168        static char term = '\n';
1169        struct object *o;
1170
1171        if (!lock)
1172                return -1;
1173        if (!lock->force_write && !hashcmp(lock->old_sha1, sha1)) {
1174                unlock_ref(lock);
1175                return 0;
1176        }
1177        o = parse_object(sha1);
1178        if (!o) {
1179                error("Trying to write ref %s with nonexistant object %s",
1180                        lock->ref_name, sha1_to_hex(sha1));
1181                unlock_ref(lock);
1182                return -1;
1183        }
1184        if (o->type != OBJ_COMMIT && is_branch(lock->ref_name)) {
1185                error("Trying to write non-commit object %s to branch %s",
1186                        sha1_to_hex(sha1), lock->ref_name);
1187                unlock_ref(lock);
1188                return -1;
1189        }
1190        if (write_in_full(lock->lock_fd, sha1_to_hex(sha1), 40) != 40 ||
1191            write_in_full(lock->lock_fd, &term, 1) != 1
1192                || close_ref(lock) < 0) {
1193                error("Couldn't write %s", lock->lk->filename);
1194                unlock_ref(lock);
1195                return -1;
1196        }
1197        invalidate_cached_refs();
1198        if (log_ref_write(lock->ref_name, lock->old_sha1, sha1, logmsg) < 0 ||
1199            (strcmp(lock->ref_name, lock->orig_ref_name) &&
1200             log_ref_write(lock->orig_ref_name, lock->old_sha1, sha1, logmsg) < 0)) {
1201                unlock_ref(lock);
1202                return -1;
1203        }
1204        if (strcmp(lock->orig_ref_name, "HEAD") != 0) {
1205                /*
1206                 * Special hack: If a branch is updated directly and HEAD
1207                 * points to it (may happen on the remote side of a push
1208                 * for example) then logically the HEAD reflog should be
1209                 * updated too.
1210                 * A generic solution implies reverse symref information,
1211                 * but finding all symrefs pointing to the given branch
1212                 * would be rather costly for this rare event (the direct
1213                 * update of a branch) to be worth it.  So let's cheat and
1214                 * check with HEAD only which should cover 99% of all usage
1215                 * scenarios (even 100% of the default ones).
1216                 */
1217                unsigned char head_sha1[20];
1218                int head_flag;
1219                const char *head_ref;
1220                head_ref = resolve_ref("HEAD", head_sha1, 1, &head_flag);
1221                if (head_ref && (head_flag & REF_ISSYMREF) &&
1222                    !strcmp(head_ref, lock->ref_name))
1223                        log_ref_write("HEAD", lock->old_sha1, sha1, logmsg);
1224        }
1225        if (commit_ref(lock)) {
1226                error("Couldn't set %s", lock->ref_name);
1227                unlock_ref(lock);
1228                return -1;
1229        }
1230        unlock_ref(lock);
1231        return 0;
1232}
1233
1234int create_symref(const char *ref_target, const char *refs_heads_master,
1235                  const char *logmsg)
1236{
1237        const char *lockpath;
1238        char ref[1000];
1239        int fd, len, written;
1240        char *git_HEAD = xstrdup(git_path("%s", ref_target));
1241        unsigned char old_sha1[20], new_sha1[20];
1242
1243        if (logmsg && read_ref(ref_target, old_sha1))
1244                hashclr(old_sha1);
1245
1246        if (safe_create_leading_directories(git_HEAD) < 0)
1247                return error("unable to create directory for %s", git_HEAD);
1248
1249#ifndef NO_SYMLINK_HEAD
1250        if (prefer_symlink_refs) {
1251                unlink(git_HEAD);
1252                if (!symlink(refs_heads_master, git_HEAD))
1253                        goto done;
1254                fprintf(stderr, "no symlink - falling back to symbolic ref\n");
1255        }
1256#endif
1257
1258        len = snprintf(ref, sizeof(ref), "ref: %s\n", refs_heads_master);
1259        if (sizeof(ref) <= len) {
1260                error("refname too long: %s", refs_heads_master);
1261                goto error_free_return;
1262        }
1263        lockpath = mkpath("%s.lock", git_HEAD);
1264        fd = open(lockpath, O_CREAT | O_EXCL | O_WRONLY, 0666);
1265        if (fd < 0) {
1266                error("Unable to open %s for writing", lockpath);
1267                goto error_free_return;
1268        }
1269        written = write_in_full(fd, ref, len);
1270        if (close(fd) != 0 || written != len) {
1271                error("Unable to write to %s", lockpath);
1272                goto error_unlink_return;
1273        }
1274        if (rename(lockpath, git_HEAD) < 0) {
1275                error("Unable to create %s", git_HEAD);
1276                goto error_unlink_return;
1277        }
1278        if (adjust_shared_perm(git_HEAD)) {
1279                error("Unable to fix permissions on %s", lockpath);
1280        error_unlink_return:
1281                unlink(lockpath);
1282        error_free_return:
1283                free(git_HEAD);
1284                return -1;
1285        }
1286
1287#ifndef NO_SYMLINK_HEAD
1288        done:
1289#endif
1290        if (logmsg && !read_ref(refs_heads_master, new_sha1))
1291                log_ref_write(ref_target, old_sha1, new_sha1, logmsg);
1292
1293        free(git_HEAD);
1294        return 0;
1295}
1296
1297static char *ref_msg(const char *line, const char *endp)
1298{
1299        const char *ep;
1300        line += 82;
1301        ep = memchr(line, '\n', endp - line);
1302        if (!ep)
1303                ep = endp;
1304        return xmemdupz(line, ep - line);
1305}
1306
1307int read_ref_at(const char *ref, unsigned long at_time, int cnt, unsigned char *sha1, char **msg, unsigned long *cutoff_time, int *cutoff_tz, int *cutoff_cnt)
1308{
1309        const char *logfile, *logdata, *logend, *rec, *lastgt, *lastrec;
1310        char *tz_c;
1311        int logfd, tz, reccnt = 0;
1312        struct stat st;
1313        unsigned long date;
1314        unsigned char logged_sha1[20];
1315        void *log_mapped;
1316        size_t mapsz;
1317
1318        logfile = git_path("logs/%s", ref);
1319        logfd = open(logfile, O_RDONLY, 0);
1320        if (logfd < 0)
1321                die("Unable to read log %s: %s", logfile, strerror(errno));
1322        fstat(logfd, &st);
1323        if (!st.st_size)
1324                die("Log %s is empty.", logfile);
1325        mapsz = xsize_t(st.st_size);
1326        log_mapped = xmmap(NULL, mapsz, PROT_READ, MAP_PRIVATE, logfd, 0);
1327        logdata = log_mapped;
1328        close(logfd);
1329
1330        lastrec = NULL;
1331        rec = logend = logdata + st.st_size;
1332        while (logdata < rec) {
1333                reccnt++;
1334                if (logdata < rec && *(rec-1) == '\n')
1335                        rec--;
1336                lastgt = NULL;
1337                while (logdata < rec && *(rec-1) != '\n') {
1338                        rec--;
1339                        if (*rec == '>')
1340                                lastgt = rec;
1341                }
1342                if (!lastgt)
1343                        die("Log %s is corrupt.", logfile);
1344                date = strtoul(lastgt + 1, &tz_c, 10);
1345                if (date <= at_time || cnt == 0) {
1346                        tz = strtoul(tz_c, NULL, 10);
1347                        if (msg)
1348                                *msg = ref_msg(rec, logend);
1349                        if (cutoff_time)
1350                                *cutoff_time = date;
1351                        if (cutoff_tz)
1352                                *cutoff_tz = tz;
1353                        if (cutoff_cnt)
1354                                *cutoff_cnt = reccnt - 1;
1355                        if (lastrec) {
1356                                if (get_sha1_hex(lastrec, logged_sha1))
1357                                        die("Log %s is corrupt.", logfile);
1358                                if (get_sha1_hex(rec + 41, sha1))
1359                                        die("Log %s is corrupt.", logfile);
1360                                if (hashcmp(logged_sha1, sha1)) {
1361                                        fprintf(stderr,
1362                                                "warning: Log %s has gap after %s.\n",
1363                                                logfile, show_date(date, tz, DATE_RFC2822));
1364                                }
1365                        }
1366                        else if (date == at_time) {
1367                                if (get_sha1_hex(rec + 41, sha1))
1368                                        die("Log %s is corrupt.", logfile);
1369                        }
1370                        else {
1371                                if (get_sha1_hex(rec + 41, logged_sha1))
1372                                        die("Log %s is corrupt.", logfile);
1373                                if (hashcmp(logged_sha1, sha1)) {
1374                                        fprintf(stderr,
1375                                                "warning: Log %s unexpectedly ended on %s.\n",
1376                                                logfile, show_date(date, tz, DATE_RFC2822));
1377                                }
1378                        }
1379                        munmap(log_mapped, mapsz);
1380                        return 0;
1381                }
1382                lastrec = rec;
1383                if (cnt > 0)
1384                        cnt--;
1385        }
1386
1387        rec = logdata;
1388        while (rec < logend && *rec != '>' && *rec != '\n')
1389                rec++;
1390        if (rec == logend || *rec == '\n')
1391                die("Log %s is corrupt.", logfile);
1392        date = strtoul(rec + 1, &tz_c, 10);
1393        tz = strtoul(tz_c, NULL, 10);
1394        if (get_sha1_hex(logdata, sha1))
1395                die("Log %s is corrupt.", logfile);
1396        if (msg)
1397                *msg = ref_msg(logdata, logend);
1398        munmap(log_mapped, mapsz);
1399
1400        if (cutoff_time)
1401                *cutoff_time = date;
1402        if (cutoff_tz)
1403                *cutoff_tz = tz;
1404        if (cutoff_cnt)
1405                *cutoff_cnt = reccnt;
1406        return 1;
1407}
1408
1409int for_each_reflog_ent(const char *ref, each_reflog_ent_fn fn, void *cb_data)
1410{
1411        const char *logfile;
1412        FILE *logfp;
1413        char buf[1024];
1414        int ret = 0;
1415
1416        logfile = git_path("logs/%s", ref);
1417        logfp = fopen(logfile, "r");
1418        if (!logfp)
1419                return -1;
1420        while (fgets(buf, sizeof(buf), logfp)) {
1421                unsigned char osha1[20], nsha1[20];
1422                char *email_end, *message;
1423                unsigned long timestamp;
1424                int len, tz;
1425
1426                /* old SP new SP name <email> SP time TAB msg LF */
1427                len = strlen(buf);
1428                if (len < 83 || buf[len-1] != '\n' ||
1429                    get_sha1_hex(buf, osha1) || buf[40] != ' ' ||
1430                    get_sha1_hex(buf + 41, nsha1) || buf[81] != ' ' ||
1431                    !(email_end = strchr(buf + 82, '>')) ||
1432                    email_end[1] != ' ' ||
1433                    !(timestamp = strtoul(email_end + 2, &message, 10)) ||
1434                    !message || message[0] != ' ' ||
1435                    (message[1] != '+' && message[1] != '-') ||
1436                    !isdigit(message[2]) || !isdigit(message[3]) ||
1437                    !isdigit(message[4]) || !isdigit(message[5]))
1438                        continue; /* corrupt? */
1439                email_end[1] = '\0';
1440                tz = strtol(message + 1, NULL, 10);
1441                if (message[6] != '\t')
1442                        message += 6;
1443                else
1444                        message += 7;
1445                ret = fn(osha1, nsha1, buf+82, timestamp, tz, message, cb_data);
1446                if (ret)
1447                        break;
1448        }
1449        fclose(logfp);
1450        return ret;
1451}
1452
1453static int do_for_each_reflog(const char *base, each_ref_fn fn, void *cb_data)
1454{
1455        DIR *dir = opendir(git_path("logs/%s", base));
1456        int retval = 0;
1457
1458        if (dir) {
1459                struct dirent *de;
1460                int baselen = strlen(base);
1461                char *log = xmalloc(baselen + 257);
1462
1463                memcpy(log, base, baselen);
1464                if (baselen && base[baselen-1] != '/')
1465                        log[baselen++] = '/';
1466
1467                while ((de = readdir(dir)) != NULL) {
1468                        struct stat st;
1469                        int namelen;
1470
1471                        if (de->d_name[0] == '.')
1472                                continue;
1473                        namelen = strlen(de->d_name);
1474                        if (namelen > 255)
1475                                continue;
1476                        if (has_extension(de->d_name, ".lock"))
1477                                continue;
1478                        memcpy(log + baselen, de->d_name, namelen+1);
1479                        if (stat(git_path("logs/%s", log), &st) < 0)
1480                                continue;
1481                        if (S_ISDIR(st.st_mode)) {
1482                                retval = do_for_each_reflog(log, fn, cb_data);
1483                        } else {
1484                                unsigned char sha1[20];
1485                                if (!resolve_ref(log, sha1, 0, NULL))
1486                                        retval = error("bad ref for %s", log);
1487                                else
1488                                        retval = fn(log, sha1, 0, cb_data);
1489                        }
1490                        if (retval)
1491                                break;
1492                }
1493                free(log);
1494                closedir(dir);
1495        }
1496        else if (*base)
1497                return errno;
1498        return retval;
1499}
1500
1501int for_each_reflog(each_ref_fn fn, void *cb_data)
1502{
1503        return do_for_each_reflog("", fn, cb_data);
1504}
1505
1506int update_ref(const char *action, const char *refname,
1507                const unsigned char *sha1, const unsigned char *oldval,
1508                int flags, enum action_on_err onerr)
1509{
1510        static struct ref_lock *lock;
1511        lock = lock_any_ref_for_update(refname, oldval, flags);
1512        if (!lock) {
1513                const char *str = "Cannot lock the ref '%s'.";
1514                switch (onerr) {
1515                case MSG_ON_ERR: error(str, refname); break;
1516                case DIE_ON_ERR: die(str, refname); break;
1517                case QUIET_ON_ERR: break;
1518                }
1519                return 1;
1520        }
1521        if (write_ref_sha1(lock, sha1, action) < 0) {
1522                const char *str = "Cannot update the ref '%s'.";
1523                switch (onerr) {
1524                case MSG_ON_ERR: error(str, refname); break;
1525                case DIE_ON_ERR: die(str, refname); break;
1526                case QUIET_ON_ERR: break;
1527                }
1528                return 1;
1529        }
1530        return 0;
1531}
1532
1533struct ref *find_ref_by_name(struct ref *list, const char *name)
1534{
1535        for ( ; list; list = list->next)
1536                if (!strcmp(list->name, name))
1537                        return list;
1538        return NULL;
1539}