refs / files-backend.con commit packed-backend: new module for handling packed references (67be7c5)
   1#include "../cache.h"
   2#include "../refs.h"
   3#include "refs-internal.h"
   4#include "ref-cache.h"
   5#include "packed-backend.h"
   6#include "../iterator.h"
   7#include "../dir-iterator.h"
   8#include "../lockfile.h"
   9#include "../object.h"
  10#include "../dir.h"
  11
  12struct ref_lock {
  13        char *ref_name;
  14        struct lock_file *lk;
  15        struct object_id old_oid;
  16};
  17
  18/*
  19 * Future: need to be in "struct repository"
  20 * when doing a full libification.
  21 */
  22struct files_ref_store {
  23        struct ref_store base;
  24        unsigned int store_flags;
  25
  26        char *gitdir;
  27        char *gitcommondir;
  28
  29        struct ref_cache *loose;
  30
  31        struct packed_ref_store *packed_ref_store;
  32};
  33
  34static void clear_loose_ref_cache(struct files_ref_store *refs)
  35{
  36        if (refs->loose) {
  37                free_ref_cache(refs->loose);
  38                refs->loose = NULL;
  39        }
  40}
  41
  42/*
  43 * Create a new submodule ref cache and add it to the internal
  44 * set of caches.
  45 */
  46static struct ref_store *files_ref_store_create(const char *gitdir,
  47                                                unsigned int flags)
  48{
  49        struct files_ref_store *refs = xcalloc(1, sizeof(*refs));
  50        struct ref_store *ref_store = (struct ref_store *)refs;
  51        struct strbuf sb = STRBUF_INIT;
  52
  53        base_ref_store_init(ref_store, &refs_be_files);
  54        refs->store_flags = flags;
  55
  56        refs->gitdir = xstrdup(gitdir);
  57        get_common_dir_noenv(&sb, gitdir);
  58        refs->gitcommondir = strbuf_detach(&sb, NULL);
  59        strbuf_addf(&sb, "%s/packed-refs", refs->gitcommondir);
  60        refs->packed_ref_store = packed_ref_store_create(sb.buf, flags);
  61        strbuf_release(&sb);
  62
  63        return ref_store;
  64}
  65
  66/*
  67 * Die if refs is not the main ref store. caller is used in any
  68 * necessary error messages.
  69 */
  70static void files_assert_main_repository(struct files_ref_store *refs,
  71                                         const char *caller)
  72{
  73        if (refs->store_flags & REF_STORE_MAIN)
  74                return;
  75
  76        die("BUG: operation %s only allowed for main ref store", caller);
  77}
  78
  79/*
  80 * Downcast ref_store to files_ref_store. Die if ref_store is not a
  81 * files_ref_store. required_flags is compared with ref_store's
  82 * store_flags to ensure the ref_store has all required capabilities.
  83 * "caller" is used in any necessary error messages.
  84 */
  85static struct files_ref_store *files_downcast(struct ref_store *ref_store,
  86                                              unsigned int required_flags,
  87                                              const char *caller)
  88{
  89        struct files_ref_store *refs;
  90
  91        if (ref_store->be != &refs_be_files)
  92                die("BUG: ref_store is type \"%s\" not \"files\" in %s",
  93                    ref_store->be->name, caller);
  94
  95        refs = (struct files_ref_store *)ref_store;
  96
  97        if ((refs->store_flags & required_flags) != required_flags)
  98                die("BUG: operation %s requires abilities 0x%x, but only have 0x%x",
  99                    caller, required_flags, refs->store_flags);
 100
 101        return refs;
 102}
 103
 104static void files_reflog_path(struct files_ref_store *refs,
 105                              struct strbuf *sb,
 106                              const char *refname)
 107{
 108        if (!refname) {
 109                /*
 110                 * FIXME: of course this is wrong in multi worktree
 111                 * setting. To be fixed real soon.
 112                 */
 113                strbuf_addf(sb, "%s/logs", refs->gitcommondir);
 114                return;
 115        }
 116
 117        switch (ref_type(refname)) {
 118        case REF_TYPE_PER_WORKTREE:
 119        case REF_TYPE_PSEUDOREF:
 120                strbuf_addf(sb, "%s/logs/%s", refs->gitdir, refname);
 121                break;
 122        case REF_TYPE_NORMAL:
 123                strbuf_addf(sb, "%s/logs/%s", refs->gitcommondir, refname);
 124                break;
 125        default:
 126                die("BUG: unknown ref type %d of ref %s",
 127                    ref_type(refname), refname);
 128        }
 129}
 130
 131static void files_ref_path(struct files_ref_store *refs,
 132                           struct strbuf *sb,
 133                           const char *refname)
 134{
 135        switch (ref_type(refname)) {
 136        case REF_TYPE_PER_WORKTREE:
 137        case REF_TYPE_PSEUDOREF:
 138                strbuf_addf(sb, "%s/%s", refs->gitdir, refname);
 139                break;
 140        case REF_TYPE_NORMAL:
 141                strbuf_addf(sb, "%s/%s", refs->gitcommondir, refname);
 142                break;
 143        default:
 144                die("BUG: unknown ref type %d of ref %s",
 145                    ref_type(refname), refname);
 146        }
 147}
 148
 149/*
 150 * Read the loose references from the namespace dirname into dir
 151 * (without recursing).  dirname must end with '/'.  dir must be the
 152 * directory entry corresponding to dirname.
 153 */
 154static void loose_fill_ref_dir(struct ref_store *ref_store,
 155                               struct ref_dir *dir, const char *dirname)
 156{
 157        struct files_ref_store *refs =
 158                files_downcast(ref_store, REF_STORE_READ, "fill_ref_dir");
 159        DIR *d;
 160        struct dirent *de;
 161        int dirnamelen = strlen(dirname);
 162        struct strbuf refname;
 163        struct strbuf path = STRBUF_INIT;
 164        size_t path_baselen;
 165
 166        files_ref_path(refs, &path, dirname);
 167        path_baselen = path.len;
 168
 169        d = opendir(path.buf);
 170        if (!d) {
 171                strbuf_release(&path);
 172                return;
 173        }
 174
 175        strbuf_init(&refname, dirnamelen + 257);
 176        strbuf_add(&refname, dirname, dirnamelen);
 177
 178        while ((de = readdir(d)) != NULL) {
 179                struct object_id oid;
 180                struct stat st;
 181                int flag;
 182
 183                if (de->d_name[0] == '.')
 184                        continue;
 185                if (ends_with(de->d_name, ".lock"))
 186                        continue;
 187                strbuf_addstr(&refname, de->d_name);
 188                strbuf_addstr(&path, de->d_name);
 189                if (stat(path.buf, &st) < 0) {
 190                        ; /* silently ignore */
 191                } else if (S_ISDIR(st.st_mode)) {
 192                        strbuf_addch(&refname, '/');
 193                        add_entry_to_dir(dir,
 194                                         create_dir_entry(dir->cache, refname.buf,
 195                                                          refname.len, 1));
 196                } else {
 197                        if (!refs_resolve_ref_unsafe(&refs->base,
 198                                                     refname.buf,
 199                                                     RESOLVE_REF_READING,
 200                                                     oid.hash, &flag)) {
 201                                oidclr(&oid);
 202                                flag |= REF_ISBROKEN;
 203                        } else if (is_null_oid(&oid)) {
 204                                /*
 205                                 * It is so astronomically unlikely
 206                                 * that NULL_SHA1 is the SHA-1 of an
 207                                 * actual object that we consider its
 208                                 * appearance in a loose reference
 209                                 * file to be repo corruption
 210                                 * (probably due to a software bug).
 211                                 */
 212                                flag |= REF_ISBROKEN;
 213                        }
 214
 215                        if (check_refname_format(refname.buf,
 216                                                 REFNAME_ALLOW_ONELEVEL)) {
 217                                if (!refname_is_safe(refname.buf))
 218                                        die("loose refname is dangerous: %s", refname.buf);
 219                                oidclr(&oid);
 220                                flag |= REF_BAD_NAME | REF_ISBROKEN;
 221                        }
 222                        add_entry_to_dir(dir,
 223                                         create_ref_entry(refname.buf, &oid, flag));
 224                }
 225                strbuf_setlen(&refname, dirnamelen);
 226                strbuf_setlen(&path, path_baselen);
 227        }
 228        strbuf_release(&refname);
 229        strbuf_release(&path);
 230        closedir(d);
 231
 232        /*
 233         * Manually add refs/bisect, which, being per-worktree, might
 234         * not appear in the directory listing for refs/ in the main
 235         * repo.
 236         */
 237        if (!strcmp(dirname, "refs/")) {
 238                int pos = search_ref_dir(dir, "refs/bisect/", 12);
 239
 240                if (pos < 0) {
 241                        struct ref_entry *child_entry = create_dir_entry(
 242                                        dir->cache, "refs/bisect/", 12, 1);
 243                        add_entry_to_dir(dir, child_entry);
 244                }
 245        }
 246}
 247
 248static struct ref_cache *get_loose_ref_cache(struct files_ref_store *refs)
 249{
 250        if (!refs->loose) {
 251                /*
 252                 * Mark the top-level directory complete because we
 253                 * are about to read the only subdirectory that can
 254                 * hold references:
 255                 */
 256                refs->loose = create_ref_cache(&refs->base, loose_fill_ref_dir);
 257
 258                /* We're going to fill the top level ourselves: */
 259                refs->loose->root->flag &= ~REF_INCOMPLETE;
 260
 261                /*
 262                 * Add an incomplete entry for "refs/" (to be filled
 263                 * lazily):
 264                 */
 265                add_entry_to_dir(get_ref_dir(refs->loose->root),
 266                                 create_dir_entry(refs->loose, "refs/", 5, 1));
 267        }
 268        return refs->loose;
 269}
 270
 271static int files_read_raw_ref(struct ref_store *ref_store,
 272                              const char *refname, unsigned char *sha1,
 273                              struct strbuf *referent, unsigned int *type)
 274{
 275        struct files_ref_store *refs =
 276                files_downcast(ref_store, REF_STORE_READ, "read_raw_ref");
 277        struct strbuf sb_contents = STRBUF_INIT;
 278        struct strbuf sb_path = STRBUF_INIT;
 279        const char *path;
 280        const char *buf;
 281        struct stat st;
 282        int fd;
 283        int ret = -1;
 284        int save_errno;
 285        int remaining_retries = 3;
 286
 287        *type = 0;
 288        strbuf_reset(&sb_path);
 289
 290        files_ref_path(refs, &sb_path, refname);
 291
 292        path = sb_path.buf;
 293
 294stat_ref:
 295        /*
 296         * We might have to loop back here to avoid a race
 297         * condition: first we lstat() the file, then we try
 298         * to read it as a link or as a file.  But if somebody
 299         * changes the type of the file (file <-> directory
 300         * <-> symlink) between the lstat() and reading, then
 301         * we don't want to report that as an error but rather
 302         * try again starting with the lstat().
 303         *
 304         * We'll keep a count of the retries, though, just to avoid
 305         * any confusing situation sending us into an infinite loop.
 306         */
 307
 308        if (remaining_retries-- <= 0)
 309                goto out;
 310
 311        if (lstat(path, &st) < 0) {
 312                if (errno != ENOENT)
 313                        goto out;
 314                if (packed_read_raw_ref(refs->packed_ref_store, refname,
 315                                        sha1, referent, type)) {
 316                        errno = ENOENT;
 317                        goto out;
 318                }
 319                ret = 0;
 320                goto out;
 321        }
 322
 323        /* Follow "normalized" - ie "refs/.." symlinks by hand */
 324        if (S_ISLNK(st.st_mode)) {
 325                strbuf_reset(&sb_contents);
 326                if (strbuf_readlink(&sb_contents, path, 0) < 0) {
 327                        if (errno == ENOENT || errno == EINVAL)
 328                                /* inconsistent with lstat; retry */
 329                                goto stat_ref;
 330                        else
 331                                goto out;
 332                }
 333                if (starts_with(sb_contents.buf, "refs/") &&
 334                    !check_refname_format(sb_contents.buf, 0)) {
 335                        strbuf_swap(&sb_contents, referent);
 336                        *type |= REF_ISSYMREF;
 337                        ret = 0;
 338                        goto out;
 339                }
 340                /*
 341                 * It doesn't look like a refname; fall through to just
 342                 * treating it like a non-symlink, and reading whatever it
 343                 * points to.
 344                 */
 345        }
 346
 347        /* Is it a directory? */
 348        if (S_ISDIR(st.st_mode)) {
 349                /*
 350                 * Even though there is a directory where the loose
 351                 * ref is supposed to be, there could still be a
 352                 * packed ref:
 353                 */
 354                if (packed_read_raw_ref(refs->packed_ref_store, refname,
 355                                        sha1, referent, type)) {
 356                        errno = EISDIR;
 357                        goto out;
 358                }
 359                ret = 0;
 360                goto out;
 361        }
 362
 363        /*
 364         * Anything else, just open it and try to use it as
 365         * a ref
 366         */
 367        fd = open(path, O_RDONLY);
 368        if (fd < 0) {
 369                if (errno == ENOENT && !S_ISLNK(st.st_mode))
 370                        /* inconsistent with lstat; retry */
 371                        goto stat_ref;
 372                else
 373                        goto out;
 374        }
 375        strbuf_reset(&sb_contents);
 376        if (strbuf_read(&sb_contents, fd, 256) < 0) {
 377                int save_errno = errno;
 378                close(fd);
 379                errno = save_errno;
 380                goto out;
 381        }
 382        close(fd);
 383        strbuf_rtrim(&sb_contents);
 384        buf = sb_contents.buf;
 385        if (starts_with(buf, "ref:")) {
 386                buf += 4;
 387                while (isspace(*buf))
 388                        buf++;
 389
 390                strbuf_reset(referent);
 391                strbuf_addstr(referent, buf);
 392                *type |= REF_ISSYMREF;
 393                ret = 0;
 394                goto out;
 395        }
 396
 397        /*
 398         * Please note that FETCH_HEAD has additional
 399         * data after the sha.
 400         */
 401        if (get_sha1_hex(buf, sha1) ||
 402            (buf[40] != '\0' && !isspace(buf[40]))) {
 403                *type |= REF_ISBROKEN;
 404                errno = EINVAL;
 405                goto out;
 406        }
 407
 408        ret = 0;
 409
 410out:
 411        save_errno = errno;
 412        strbuf_release(&sb_path);
 413        strbuf_release(&sb_contents);
 414        errno = save_errno;
 415        return ret;
 416}
 417
 418static void unlock_ref(struct ref_lock *lock)
 419{
 420        /* Do not free lock->lk -- atexit() still looks at them */
 421        if (lock->lk)
 422                rollback_lock_file(lock->lk);
 423        free(lock->ref_name);
 424        free(lock);
 425}
 426
 427/*
 428 * Lock refname, without following symrefs, and set *lock_p to point
 429 * at a newly-allocated lock object. Fill in lock->old_oid, referent,
 430 * and type similarly to read_raw_ref().
 431 *
 432 * The caller must verify that refname is a "safe" reference name (in
 433 * the sense of refname_is_safe()) before calling this function.
 434 *
 435 * If the reference doesn't already exist, verify that refname doesn't
 436 * have a D/F conflict with any existing references. extras and skip
 437 * are passed to refs_verify_refname_available() for this check.
 438 *
 439 * If mustexist is not set and the reference is not found or is
 440 * broken, lock the reference anyway but clear sha1.
 441 *
 442 * Return 0 on success. On failure, write an error message to err and
 443 * return TRANSACTION_NAME_CONFLICT or TRANSACTION_GENERIC_ERROR.
 444 *
 445 * Implementation note: This function is basically
 446 *
 447 *     lock reference
 448 *     read_raw_ref()
 449 *
 450 * but it includes a lot more code to
 451 * - Deal with possible races with other processes
 452 * - Avoid calling refs_verify_refname_available() when it can be
 453 *   avoided, namely if we were successfully able to read the ref
 454 * - Generate informative error messages in the case of failure
 455 */
 456static int lock_raw_ref(struct files_ref_store *refs,
 457                        const char *refname, int mustexist,
 458                        const struct string_list *extras,
 459                        const struct string_list *skip,
 460                        struct ref_lock **lock_p,
 461                        struct strbuf *referent,
 462                        unsigned int *type,
 463                        struct strbuf *err)
 464{
 465        struct ref_lock *lock;
 466        struct strbuf ref_file = STRBUF_INIT;
 467        int attempts_remaining = 3;
 468        int ret = TRANSACTION_GENERIC_ERROR;
 469
 470        assert(err);
 471        files_assert_main_repository(refs, "lock_raw_ref");
 472
 473        *type = 0;
 474
 475        /* First lock the file so it can't change out from under us. */
 476
 477        *lock_p = lock = xcalloc(1, sizeof(*lock));
 478
 479        lock->ref_name = xstrdup(refname);
 480        files_ref_path(refs, &ref_file, refname);
 481
 482retry:
 483        switch (safe_create_leading_directories(ref_file.buf)) {
 484        case SCLD_OK:
 485                break; /* success */
 486        case SCLD_EXISTS:
 487                /*
 488                 * Suppose refname is "refs/foo/bar". We just failed
 489                 * to create the containing directory, "refs/foo",
 490                 * because there was a non-directory in the way. This
 491                 * indicates a D/F conflict, probably because of
 492                 * another reference such as "refs/foo". There is no
 493                 * reason to expect this error to be transitory.
 494                 */
 495                if (refs_verify_refname_available(&refs->base, refname,
 496                                                  extras, skip, err)) {
 497                        if (mustexist) {
 498                                /*
 499                                 * To the user the relevant error is
 500                                 * that the "mustexist" reference is
 501                                 * missing:
 502                                 */
 503                                strbuf_reset(err);
 504                                strbuf_addf(err, "unable to resolve reference '%s'",
 505                                            refname);
 506                        } else {
 507                                /*
 508                                 * The error message set by
 509                                 * refs_verify_refname_available() is
 510                                 * OK.
 511                                 */
 512                                ret = TRANSACTION_NAME_CONFLICT;
 513                        }
 514                } else {
 515                        /*
 516                         * The file that is in the way isn't a loose
 517                         * reference. Report it as a low-level
 518                         * failure.
 519                         */
 520                        strbuf_addf(err, "unable to create lock file %s.lock; "
 521                                    "non-directory in the way",
 522                                    ref_file.buf);
 523                }
 524                goto error_return;
 525        case SCLD_VANISHED:
 526                /* Maybe another process was tidying up. Try again. */
 527                if (--attempts_remaining > 0)
 528                        goto retry;
 529                /* fall through */
 530        default:
 531                strbuf_addf(err, "unable to create directory for %s",
 532                            ref_file.buf);
 533                goto error_return;
 534        }
 535
 536        if (!lock->lk)
 537                lock->lk = xcalloc(1, sizeof(struct lock_file));
 538
 539        if (hold_lock_file_for_update(lock->lk, ref_file.buf, LOCK_NO_DEREF) < 0) {
 540                if (errno == ENOENT && --attempts_remaining > 0) {
 541                        /*
 542                         * Maybe somebody just deleted one of the
 543                         * directories leading to ref_file.  Try
 544                         * again:
 545                         */
 546                        goto retry;
 547                } else {
 548                        unable_to_lock_message(ref_file.buf, errno, err);
 549                        goto error_return;
 550                }
 551        }
 552
 553        /*
 554         * Now we hold the lock and can read the reference without
 555         * fear that its value will change.
 556         */
 557
 558        if (files_read_raw_ref(&refs->base, refname,
 559                               lock->old_oid.hash, referent, type)) {
 560                if (errno == ENOENT) {
 561                        if (mustexist) {
 562                                /* Garden variety missing reference. */
 563                                strbuf_addf(err, "unable to resolve reference '%s'",
 564                                            refname);
 565                                goto error_return;
 566                        } else {
 567                                /*
 568                                 * Reference is missing, but that's OK. We
 569                                 * know that there is not a conflict with
 570                                 * another loose reference because
 571                                 * (supposing that we are trying to lock
 572                                 * reference "refs/foo/bar"):
 573                                 *
 574                                 * - We were successfully able to create
 575                                 *   the lockfile refs/foo/bar.lock, so we
 576                                 *   know there cannot be a loose reference
 577                                 *   named "refs/foo".
 578                                 *
 579                                 * - We got ENOENT and not EISDIR, so we
 580                                 *   know that there cannot be a loose
 581                                 *   reference named "refs/foo/bar/baz".
 582                                 */
 583                        }
 584                } else if (errno == EISDIR) {
 585                        /*
 586                         * There is a directory in the way. It might have
 587                         * contained references that have been deleted. If
 588                         * we don't require that the reference already
 589                         * exists, try to remove the directory so that it
 590                         * doesn't cause trouble when we want to rename the
 591                         * lockfile into place later.
 592                         */
 593                        if (mustexist) {
 594                                /* Garden variety missing reference. */
 595                                strbuf_addf(err, "unable to resolve reference '%s'",
 596                                            refname);
 597                                goto error_return;
 598                        } else if (remove_dir_recursively(&ref_file,
 599                                                          REMOVE_DIR_EMPTY_ONLY)) {
 600                                if (refs_verify_refname_available(
 601                                                    &refs->base, refname,
 602                                                    extras, skip, err)) {
 603                                        /*
 604                                         * The error message set by
 605                                         * verify_refname_available() is OK.
 606                                         */
 607                                        ret = TRANSACTION_NAME_CONFLICT;
 608                                        goto error_return;
 609                                } else {
 610                                        /*
 611                                         * We can't delete the directory,
 612                                         * but we also don't know of any
 613                                         * references that it should
 614                                         * contain.
 615                                         */
 616                                        strbuf_addf(err, "there is a non-empty directory '%s' "
 617                                                    "blocking reference '%s'",
 618                                                    ref_file.buf, refname);
 619                                        goto error_return;
 620                                }
 621                        }
 622                } else if (errno == EINVAL && (*type & REF_ISBROKEN)) {
 623                        strbuf_addf(err, "unable to resolve reference '%s': "
 624                                    "reference broken", refname);
 625                        goto error_return;
 626                } else {
 627                        strbuf_addf(err, "unable to resolve reference '%s': %s",
 628                                    refname, strerror(errno));
 629                        goto error_return;
 630                }
 631
 632                /*
 633                 * If the ref did not exist and we are creating it,
 634                 * make sure there is no existing ref that conflicts
 635                 * with refname:
 636                 */
 637                if (refs_verify_refname_available(
 638                                    &refs->base, refname,
 639                                    extras, skip, err))
 640                        goto error_return;
 641        }
 642
 643        ret = 0;
 644        goto out;
 645
 646error_return:
 647        unlock_ref(lock);
 648        *lock_p = NULL;
 649
 650out:
 651        strbuf_release(&ref_file);
 652        return ret;
 653}
 654
 655static int files_peel_ref(struct ref_store *ref_store,
 656                          const char *refname, unsigned char *sha1)
 657{
 658        struct files_ref_store *refs =
 659                files_downcast(ref_store, REF_STORE_READ | REF_STORE_ODB,
 660                               "peel_ref");
 661        int flag;
 662        unsigned char base[20];
 663
 664        if (current_ref_iter && current_ref_iter->refname == refname) {
 665                struct object_id peeled;
 666
 667                if (ref_iterator_peel(current_ref_iter, &peeled))
 668                        return -1;
 669                hashcpy(sha1, peeled.hash);
 670                return 0;
 671        }
 672
 673        if (refs_read_ref_full(ref_store, refname,
 674                               RESOLVE_REF_READING, base, &flag))
 675                return -1;
 676
 677        /*
 678         * If the reference is packed, read its ref_entry from the
 679         * cache in the hope that we already know its peeled value.
 680         * We only try this optimization on packed references because
 681         * (a) forcing the filling of the loose reference cache could
 682         * be expensive and (b) loose references anyway usually do not
 683         * have REF_KNOWS_PEELED.
 684         */
 685        if (flag & REF_ISPACKED &&
 686            !packed_peel_ref(refs->packed_ref_store, refname, sha1))
 687                return 0;
 688
 689        return peel_object(base, sha1);
 690}
 691
 692struct files_ref_iterator {
 693        struct ref_iterator base;
 694
 695        struct ref_iterator *iter0;
 696        unsigned int flags;
 697};
 698
 699static int files_ref_iterator_advance(struct ref_iterator *ref_iterator)
 700{
 701        struct files_ref_iterator *iter =
 702                (struct files_ref_iterator *)ref_iterator;
 703        int ok;
 704
 705        while ((ok = ref_iterator_advance(iter->iter0)) == ITER_OK) {
 706                if (iter->flags & DO_FOR_EACH_PER_WORKTREE_ONLY &&
 707                    ref_type(iter->iter0->refname) != REF_TYPE_PER_WORKTREE)
 708                        continue;
 709
 710                if (!(iter->flags & DO_FOR_EACH_INCLUDE_BROKEN) &&
 711                    !ref_resolves_to_object(iter->iter0->refname,
 712                                            iter->iter0->oid,
 713                                            iter->iter0->flags))
 714                        continue;
 715
 716                iter->base.refname = iter->iter0->refname;
 717                iter->base.oid = iter->iter0->oid;
 718                iter->base.flags = iter->iter0->flags;
 719                return ITER_OK;
 720        }
 721
 722        iter->iter0 = NULL;
 723        if (ref_iterator_abort(ref_iterator) != ITER_DONE)
 724                ok = ITER_ERROR;
 725
 726        return ok;
 727}
 728
 729static int files_ref_iterator_peel(struct ref_iterator *ref_iterator,
 730                                   struct object_id *peeled)
 731{
 732        struct files_ref_iterator *iter =
 733                (struct files_ref_iterator *)ref_iterator;
 734
 735        return ref_iterator_peel(iter->iter0, peeled);
 736}
 737
 738static int files_ref_iterator_abort(struct ref_iterator *ref_iterator)
 739{
 740        struct files_ref_iterator *iter =
 741                (struct files_ref_iterator *)ref_iterator;
 742        int ok = ITER_DONE;
 743
 744        if (iter->iter0)
 745                ok = ref_iterator_abort(iter->iter0);
 746
 747        base_ref_iterator_free(ref_iterator);
 748        return ok;
 749}
 750
 751static struct ref_iterator_vtable files_ref_iterator_vtable = {
 752        files_ref_iterator_advance,
 753        files_ref_iterator_peel,
 754        files_ref_iterator_abort
 755};
 756
 757static struct ref_iterator *files_ref_iterator_begin(
 758                struct ref_store *ref_store,
 759                const char *prefix, unsigned int flags)
 760{
 761        struct files_ref_store *refs;
 762        struct ref_iterator *loose_iter, *packed_iter;
 763        struct files_ref_iterator *iter;
 764        struct ref_iterator *ref_iterator;
 765        unsigned int required_flags = REF_STORE_READ;
 766
 767        if (!(flags & DO_FOR_EACH_INCLUDE_BROKEN))
 768                required_flags |= REF_STORE_ODB;
 769
 770        refs = files_downcast(ref_store, required_flags, "ref_iterator_begin");
 771
 772        iter = xcalloc(1, sizeof(*iter));
 773        ref_iterator = &iter->base;
 774        base_ref_iterator_init(ref_iterator, &files_ref_iterator_vtable);
 775
 776        /*
 777         * We must make sure that all loose refs are read before
 778         * accessing the packed-refs file; this avoids a race
 779         * condition if loose refs are migrated to the packed-refs
 780         * file by a simultaneous process, but our in-memory view is
 781         * from before the migration. We ensure this as follows:
 782         * First, we call start the loose refs iteration with its
 783         * `prime_ref` argument set to true. This causes the loose
 784         * references in the subtree to be pre-read into the cache.
 785         * (If they've already been read, that's OK; we only need to
 786         * guarantee that they're read before the packed refs, not
 787         * *how much* before.) After that, we call
 788         * packed_ref_iterator_begin(), which internally checks
 789         * whether the packed-ref cache is up to date with what is on
 790         * disk, and re-reads it if not.
 791         */
 792
 793        loose_iter = cache_ref_iterator_begin(get_loose_ref_cache(refs),
 794                                              prefix, 1);
 795
 796        /*
 797         * The packed-refs file might contain broken references, for
 798         * example an old version of a reference that points at an
 799         * object that has since been garbage-collected. This is OK as
 800         * long as there is a corresponding loose reference that
 801         * overrides it, and we don't want to emit an error message in
 802         * this case. So ask the packed_ref_store for all of its
 803         * references, and (if needed) do our own check for broken
 804         * ones in files_ref_iterator_advance(), after we have merged
 805         * the packed and loose references.
 806         */
 807        packed_iter = packed_ref_iterator_begin(
 808                        refs->packed_ref_store, prefix,
 809                        DO_FOR_EACH_INCLUDE_BROKEN);
 810
 811        iter->iter0 = overlay_ref_iterator_begin(loose_iter, packed_iter);
 812        iter->flags = flags;
 813
 814        return ref_iterator;
 815}
 816
 817/*
 818 * Verify that the reference locked by lock has the value old_sha1.
 819 * Fail if the reference doesn't exist and mustexist is set. Return 0
 820 * on success. On error, write an error message to err, set errno, and
 821 * return a negative value.
 822 */
 823static int verify_lock(struct ref_store *ref_store, struct ref_lock *lock,
 824                       const unsigned char *old_sha1, int mustexist,
 825                       struct strbuf *err)
 826{
 827        assert(err);
 828
 829        if (refs_read_ref_full(ref_store, lock->ref_name,
 830                               mustexist ? RESOLVE_REF_READING : 0,
 831                               lock->old_oid.hash, NULL)) {
 832                if (old_sha1) {
 833                        int save_errno = errno;
 834                        strbuf_addf(err, "can't verify ref '%s'", lock->ref_name);
 835                        errno = save_errno;
 836                        return -1;
 837                } else {
 838                        oidclr(&lock->old_oid);
 839                        return 0;
 840                }
 841        }
 842        if (old_sha1 && hashcmp(lock->old_oid.hash, old_sha1)) {
 843                strbuf_addf(err, "ref '%s' is at %s but expected %s",
 844                            lock->ref_name,
 845                            oid_to_hex(&lock->old_oid),
 846                            sha1_to_hex(old_sha1));
 847                errno = EBUSY;
 848                return -1;
 849        }
 850        return 0;
 851}
 852
 853static int remove_empty_directories(struct strbuf *path)
 854{
 855        /*
 856         * we want to create a file but there is a directory there;
 857         * if that is an empty directory (or a directory that contains
 858         * only empty directories), remove them.
 859         */
 860        return remove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY);
 861}
 862
 863static int create_reflock(const char *path, void *cb)
 864{
 865        struct lock_file *lk = cb;
 866
 867        return hold_lock_file_for_update(lk, path, LOCK_NO_DEREF) < 0 ? -1 : 0;
 868}
 869
 870/*
 871 * Locks a ref returning the lock on success and NULL on failure.
 872 * On failure errno is set to something meaningful.
 873 */
 874static struct ref_lock *lock_ref_sha1_basic(struct files_ref_store *refs,
 875                                            const char *refname,
 876                                            const unsigned char *old_sha1,
 877                                            const struct string_list *extras,
 878                                            const struct string_list *skip,
 879                                            unsigned int flags, int *type,
 880                                            struct strbuf *err)
 881{
 882        struct strbuf ref_file = STRBUF_INIT;
 883        struct ref_lock *lock;
 884        int last_errno = 0;
 885        int mustexist = (old_sha1 && !is_null_sha1(old_sha1));
 886        int resolve_flags = RESOLVE_REF_NO_RECURSE;
 887        int resolved;
 888
 889        files_assert_main_repository(refs, "lock_ref_sha1_basic");
 890        assert(err);
 891
 892        lock = xcalloc(1, sizeof(struct ref_lock));
 893
 894        if (mustexist)
 895                resolve_flags |= RESOLVE_REF_READING;
 896        if (flags & REF_DELETING)
 897                resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;
 898
 899        files_ref_path(refs, &ref_file, refname);
 900        resolved = !!refs_resolve_ref_unsafe(&refs->base,
 901                                             refname, resolve_flags,
 902                                             lock->old_oid.hash, type);
 903        if (!resolved && errno == EISDIR) {
 904                /*
 905                 * we are trying to lock foo but we used to
 906                 * have foo/bar which now does not exist;
 907                 * it is normal for the empty directory 'foo'
 908                 * to remain.
 909                 */
 910                if (remove_empty_directories(&ref_file)) {
 911                        last_errno = errno;
 912                        if (!refs_verify_refname_available(
 913                                            &refs->base,
 914                                            refname, extras, skip, err))
 915                                strbuf_addf(err, "there are still refs under '%s'",
 916                                            refname);
 917                        goto error_return;
 918                }
 919                resolved = !!refs_resolve_ref_unsafe(&refs->base,
 920                                                     refname, resolve_flags,
 921                                                     lock->old_oid.hash, type);
 922        }
 923        if (!resolved) {
 924                last_errno = errno;
 925                if (last_errno != ENOTDIR ||
 926                    !refs_verify_refname_available(&refs->base, refname,
 927                                                   extras, skip, err))
 928                        strbuf_addf(err, "unable to resolve reference '%s': %s",
 929                                    refname, strerror(last_errno));
 930
 931                goto error_return;
 932        }
 933
 934        /*
 935         * If the ref did not exist and we are creating it, make sure
 936         * there is no existing packed ref whose name begins with our
 937         * refname, nor a packed ref whose name is a proper prefix of
 938         * our refname.
 939         */
 940        if (is_null_oid(&lock->old_oid) &&
 941            refs_verify_refname_available(&refs->base, refname,
 942                                          extras, skip, err)) {
 943                last_errno = ENOTDIR;
 944                goto error_return;
 945        }
 946
 947        lock->lk = xcalloc(1, sizeof(struct lock_file));
 948
 949        lock->ref_name = xstrdup(refname);
 950
 951        if (raceproof_create_file(ref_file.buf, create_reflock, lock->lk)) {
 952                last_errno = errno;
 953                unable_to_lock_message(ref_file.buf, errno, err);
 954                goto error_return;
 955        }
 956
 957        if (verify_lock(&refs->base, lock, old_sha1, mustexist, err)) {
 958                last_errno = errno;
 959                goto error_return;
 960        }
 961        goto out;
 962
 963 error_return:
 964        unlock_ref(lock);
 965        lock = NULL;
 966
 967 out:
 968        strbuf_release(&ref_file);
 969        errno = last_errno;
 970        return lock;
 971}
 972
 973struct ref_to_prune {
 974        struct ref_to_prune *next;
 975        unsigned char sha1[20];
 976        char name[FLEX_ARRAY];
 977};
 978
 979enum {
 980        REMOVE_EMPTY_PARENTS_REF = 0x01,
 981        REMOVE_EMPTY_PARENTS_REFLOG = 0x02
 982};
 983
 984/*
 985 * Remove empty parent directories associated with the specified
 986 * reference and/or its reflog, but spare [logs/]refs/ and immediate
 987 * subdirs. flags is a combination of REMOVE_EMPTY_PARENTS_REF and/or
 988 * REMOVE_EMPTY_PARENTS_REFLOG.
 989 */
 990static void try_remove_empty_parents(struct files_ref_store *refs,
 991                                     const char *refname,
 992                                     unsigned int flags)
 993{
 994        struct strbuf buf = STRBUF_INIT;
 995        struct strbuf sb = STRBUF_INIT;
 996        char *p, *q;
 997        int i;
 998
 999        strbuf_addstr(&buf, refname);
1000        p = buf.buf;
1001        for (i = 0; i < 2; i++) { /* refs/{heads,tags,...}/ */
1002                while (*p && *p != '/')
1003                        p++;
1004                /* tolerate duplicate slashes; see check_refname_format() */
1005                while (*p == '/')
1006                        p++;
1007        }
1008        q = buf.buf + buf.len;
1009        while (flags & (REMOVE_EMPTY_PARENTS_REF | REMOVE_EMPTY_PARENTS_REFLOG)) {
1010                while (q > p && *q != '/')
1011                        q--;
1012                while (q > p && *(q-1) == '/')
1013                        q--;
1014                if (q == p)
1015                        break;
1016                strbuf_setlen(&buf, q - buf.buf);
1017
1018                strbuf_reset(&sb);
1019                files_ref_path(refs, &sb, buf.buf);
1020                if ((flags & REMOVE_EMPTY_PARENTS_REF) && rmdir(sb.buf))
1021                        flags &= ~REMOVE_EMPTY_PARENTS_REF;
1022
1023                strbuf_reset(&sb);
1024                files_reflog_path(refs, &sb, buf.buf);
1025                if ((flags & REMOVE_EMPTY_PARENTS_REFLOG) && rmdir(sb.buf))
1026                        flags &= ~REMOVE_EMPTY_PARENTS_REFLOG;
1027        }
1028        strbuf_release(&buf);
1029        strbuf_release(&sb);
1030}
1031
1032/* make sure nobody touched the ref, and unlink */
1033static void prune_ref(struct files_ref_store *refs, struct ref_to_prune *r)
1034{
1035        struct ref_transaction *transaction;
1036        struct strbuf err = STRBUF_INIT;
1037
1038        if (check_refname_format(r->name, 0))
1039                return;
1040
1041        transaction = ref_store_transaction_begin(&refs->base, &err);
1042        if (!transaction ||
1043            ref_transaction_delete(transaction, r->name, r->sha1,
1044                                   REF_ISPRUNING | REF_NODEREF, NULL, &err) ||
1045            ref_transaction_commit(transaction, &err)) {
1046                ref_transaction_free(transaction);
1047                error("%s", err.buf);
1048                strbuf_release(&err);
1049                return;
1050        }
1051        ref_transaction_free(transaction);
1052        strbuf_release(&err);
1053}
1054
1055static void prune_refs(struct files_ref_store *refs, struct ref_to_prune *r)
1056{
1057        while (r) {
1058                prune_ref(refs, r);
1059                r = r->next;
1060        }
1061}
1062
1063/*
1064 * Return true if the specified reference should be packed.
1065 */
1066static int should_pack_ref(const char *refname,
1067                           const struct object_id *oid, unsigned int ref_flags,
1068                           unsigned int pack_flags)
1069{
1070        /* Do not pack per-worktree refs: */
1071        if (ref_type(refname) != REF_TYPE_NORMAL)
1072                return 0;
1073
1074        /* Do not pack non-tags unless PACK_REFS_ALL is set: */
1075        if (!(pack_flags & PACK_REFS_ALL) && !starts_with(refname, "refs/tags/"))
1076                return 0;
1077
1078        /* Do not pack symbolic refs: */
1079        if (ref_flags & REF_ISSYMREF)
1080                return 0;
1081
1082        /* Do not pack broken refs: */
1083        if (!ref_resolves_to_object(refname, oid, ref_flags))
1084                return 0;
1085
1086        return 1;
1087}
1088
1089static int files_pack_refs(struct ref_store *ref_store, unsigned int flags)
1090{
1091        struct files_ref_store *refs =
1092                files_downcast(ref_store, REF_STORE_WRITE | REF_STORE_ODB,
1093                               "pack_refs");
1094        struct ref_iterator *iter;
1095        int ok;
1096        struct ref_to_prune *refs_to_prune = NULL;
1097
1098        lock_packed_refs(refs->packed_ref_store, LOCK_DIE_ON_ERROR);
1099
1100        iter = cache_ref_iterator_begin(get_loose_ref_cache(refs), NULL, 0);
1101        while ((ok = ref_iterator_advance(iter)) == ITER_OK) {
1102                /*
1103                 * If the loose reference can be packed, add an entry
1104                 * in the packed ref cache. If the reference should be
1105                 * pruned, also add it to refs_to_prune.
1106                 */
1107                if (!should_pack_ref(iter->refname, iter->oid, iter->flags,
1108                                     flags))
1109                        continue;
1110
1111                /*
1112                 * Create an entry in the packed-refs cache equivalent
1113                 * to the one from the loose ref cache, except that
1114                 * we don't copy the peeled status, because we want it
1115                 * to be re-peeled.
1116                 */
1117                add_packed_ref(refs->packed_ref_store, iter->refname, iter->oid);
1118
1119                /* Schedule the loose reference for pruning if requested. */
1120                if ((flags & PACK_REFS_PRUNE)) {
1121                        struct ref_to_prune *n;
1122                        FLEX_ALLOC_STR(n, name, iter->refname);
1123                        hashcpy(n->sha1, iter->oid->hash);
1124                        n->next = refs_to_prune;
1125                        refs_to_prune = n;
1126                }
1127        }
1128        if (ok != ITER_DONE)
1129                die("error while iterating over references");
1130
1131        if (commit_packed_refs(refs->packed_ref_store))
1132                die_errno("unable to overwrite old ref-pack file");
1133
1134        prune_refs(refs, refs_to_prune);
1135        return 0;
1136}
1137
1138static int files_delete_refs(struct ref_store *ref_store, const char *msg,
1139                             struct string_list *refnames, unsigned int flags)
1140{
1141        struct files_ref_store *refs =
1142                files_downcast(ref_store, REF_STORE_WRITE, "delete_refs");
1143        struct strbuf err = STRBUF_INIT;
1144        int i, result = 0;
1145
1146        if (!refnames->nr)
1147                return 0;
1148
1149        result = repack_without_refs(refs->packed_ref_store, refnames, &err);
1150        if (result) {
1151                /*
1152                 * If we failed to rewrite the packed-refs file, then
1153                 * it is unsafe to try to remove loose refs, because
1154                 * doing so might expose an obsolete packed value for
1155                 * a reference that might even point at an object that
1156                 * has been garbage collected.
1157                 */
1158                if (refnames->nr == 1)
1159                        error(_("could not delete reference %s: %s"),
1160                              refnames->items[0].string, err.buf);
1161                else
1162                        error(_("could not delete references: %s"), err.buf);
1163
1164                goto out;
1165        }
1166
1167        for (i = 0; i < refnames->nr; i++) {
1168                const char *refname = refnames->items[i].string;
1169
1170                if (refs_delete_ref(&refs->base, msg, refname, NULL, flags))
1171                        result |= error(_("could not remove reference %s"), refname);
1172        }
1173
1174out:
1175        strbuf_release(&err);
1176        return result;
1177}
1178
1179/*
1180 * People using contrib's git-new-workdir have .git/logs/refs ->
1181 * /some/other/path/.git/logs/refs, and that may live on another device.
1182 *
1183 * IOW, to avoid cross device rename errors, the temporary renamed log must
1184 * live into logs/refs.
1185 */
1186#define TMP_RENAMED_LOG  "refs/.tmp-renamed-log"
1187
1188struct rename_cb {
1189        const char *tmp_renamed_log;
1190        int true_errno;
1191};
1192
1193static int rename_tmp_log_callback(const char *path, void *cb_data)
1194{
1195        struct rename_cb *cb = cb_data;
1196
1197        if (rename(cb->tmp_renamed_log, path)) {
1198                /*
1199                 * rename(a, b) when b is an existing directory ought
1200                 * to result in ISDIR, but Solaris 5.8 gives ENOTDIR.
1201                 * Sheesh. Record the true errno for error reporting,
1202                 * but report EISDIR to raceproof_create_file() so
1203                 * that it knows to retry.
1204                 */
1205                cb->true_errno = errno;
1206                if (errno == ENOTDIR)
1207                        errno = EISDIR;
1208                return -1;
1209        } else {
1210                return 0;
1211        }
1212}
1213
1214static int rename_tmp_log(struct files_ref_store *refs, const char *newrefname)
1215{
1216        struct strbuf path = STRBUF_INIT;
1217        struct strbuf tmp = STRBUF_INIT;
1218        struct rename_cb cb;
1219        int ret;
1220
1221        files_reflog_path(refs, &path, newrefname);
1222        files_reflog_path(refs, &tmp, TMP_RENAMED_LOG);
1223        cb.tmp_renamed_log = tmp.buf;
1224        ret = raceproof_create_file(path.buf, rename_tmp_log_callback, &cb);
1225        if (ret) {
1226                if (errno == EISDIR)
1227                        error("directory not empty: %s", path.buf);
1228                else
1229                        error("unable to move logfile %s to %s: %s",
1230                              tmp.buf, path.buf,
1231                              strerror(cb.true_errno));
1232        }
1233
1234        strbuf_release(&path);
1235        strbuf_release(&tmp);
1236        return ret;
1237}
1238
1239static int write_ref_to_lockfile(struct ref_lock *lock,
1240                                 const struct object_id *oid, struct strbuf *err);
1241static int commit_ref_update(struct files_ref_store *refs,
1242                             struct ref_lock *lock,
1243                             const struct object_id *oid, const char *logmsg,
1244                             struct strbuf *err);
1245
1246static int files_rename_ref(struct ref_store *ref_store,
1247                            const char *oldrefname, const char *newrefname,
1248                            const char *logmsg)
1249{
1250        struct files_ref_store *refs =
1251                files_downcast(ref_store, REF_STORE_WRITE, "rename_ref");
1252        struct object_id oid, orig_oid;
1253        int flag = 0, logmoved = 0;
1254        struct ref_lock *lock;
1255        struct stat loginfo;
1256        struct strbuf sb_oldref = STRBUF_INIT;
1257        struct strbuf sb_newref = STRBUF_INIT;
1258        struct strbuf tmp_renamed_log = STRBUF_INIT;
1259        int log, ret;
1260        struct strbuf err = STRBUF_INIT;
1261
1262        files_reflog_path(refs, &sb_oldref, oldrefname);
1263        files_reflog_path(refs, &sb_newref, newrefname);
1264        files_reflog_path(refs, &tmp_renamed_log, TMP_RENAMED_LOG);
1265
1266        log = !lstat(sb_oldref.buf, &loginfo);
1267        if (log && S_ISLNK(loginfo.st_mode)) {
1268                ret = error("reflog for %s is a symlink", oldrefname);
1269                goto out;
1270        }
1271
1272        if (!refs_resolve_ref_unsafe(&refs->base, oldrefname,
1273                                     RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,
1274                                orig_oid.hash, &flag)) {
1275                ret = error("refname %s not found", oldrefname);
1276                goto out;
1277        }
1278
1279        if (flag & REF_ISSYMREF) {
1280                ret = error("refname %s is a symbolic ref, renaming it is not supported",
1281                            oldrefname);
1282                goto out;
1283        }
1284        if (!refs_rename_ref_available(&refs->base, oldrefname, newrefname)) {
1285                ret = 1;
1286                goto out;
1287        }
1288
1289        if (log && rename(sb_oldref.buf, tmp_renamed_log.buf)) {
1290                ret = error("unable to move logfile logs/%s to logs/"TMP_RENAMED_LOG": %s",
1291                            oldrefname, strerror(errno));
1292                goto out;
1293        }
1294
1295        if (refs_delete_ref(&refs->base, logmsg, oldrefname,
1296                            orig_oid.hash, REF_NODEREF)) {
1297                error("unable to delete old %s", oldrefname);
1298                goto rollback;
1299        }
1300
1301        /*
1302         * Since we are doing a shallow lookup, oid is not the
1303         * correct value to pass to delete_ref as old_oid. But that
1304         * doesn't matter, because an old_oid check wouldn't add to
1305         * the safety anyway; we want to delete the reference whatever
1306         * its current value.
1307         */
1308        if (!refs_read_ref_full(&refs->base, newrefname,
1309                                RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,
1310                                oid.hash, NULL) &&
1311            refs_delete_ref(&refs->base, NULL, newrefname,
1312                            NULL, REF_NODEREF)) {
1313                if (errno == EISDIR) {
1314                        struct strbuf path = STRBUF_INIT;
1315                        int result;
1316
1317                        files_ref_path(refs, &path, newrefname);
1318                        result = remove_empty_directories(&path);
1319                        strbuf_release(&path);
1320
1321                        if (result) {
1322                                error("Directory not empty: %s", newrefname);
1323                                goto rollback;
1324                        }
1325                } else {
1326                        error("unable to delete existing %s", newrefname);
1327                        goto rollback;
1328                }
1329        }
1330
1331        if (log && rename_tmp_log(refs, newrefname))
1332                goto rollback;
1333
1334        logmoved = log;
1335
1336        lock = lock_ref_sha1_basic(refs, newrefname, NULL, NULL, NULL,
1337                                   REF_NODEREF, NULL, &err);
1338        if (!lock) {
1339                error("unable to rename '%s' to '%s': %s", oldrefname, newrefname, err.buf);
1340                strbuf_release(&err);
1341                goto rollback;
1342        }
1343        oidcpy(&lock->old_oid, &orig_oid);
1344
1345        if (write_ref_to_lockfile(lock, &orig_oid, &err) ||
1346            commit_ref_update(refs, lock, &orig_oid, logmsg, &err)) {
1347                error("unable to write current sha1 into %s: %s", newrefname, err.buf);
1348                strbuf_release(&err);
1349                goto rollback;
1350        }
1351
1352        ret = 0;
1353        goto out;
1354
1355 rollback:
1356        lock = lock_ref_sha1_basic(refs, oldrefname, NULL, NULL, NULL,
1357                                   REF_NODEREF, NULL, &err);
1358        if (!lock) {
1359                error("unable to lock %s for rollback: %s", oldrefname, err.buf);
1360                strbuf_release(&err);
1361                goto rollbacklog;
1362        }
1363
1364        flag = log_all_ref_updates;
1365        log_all_ref_updates = LOG_REFS_NONE;
1366        if (write_ref_to_lockfile(lock, &orig_oid, &err) ||
1367            commit_ref_update(refs, lock, &orig_oid, NULL, &err)) {
1368                error("unable to write current sha1 into %s: %s", oldrefname, err.buf);
1369                strbuf_release(&err);
1370        }
1371        log_all_ref_updates = flag;
1372
1373 rollbacklog:
1374        if (logmoved && rename(sb_newref.buf, sb_oldref.buf))
1375                error("unable to restore logfile %s from %s: %s",
1376                        oldrefname, newrefname, strerror(errno));
1377        if (!logmoved && log &&
1378            rename(tmp_renamed_log.buf, sb_oldref.buf))
1379                error("unable to restore logfile %s from logs/"TMP_RENAMED_LOG": %s",
1380                        oldrefname, strerror(errno));
1381        ret = 1;
1382 out:
1383        strbuf_release(&sb_newref);
1384        strbuf_release(&sb_oldref);
1385        strbuf_release(&tmp_renamed_log);
1386
1387        return ret;
1388}
1389
1390static int close_ref(struct ref_lock *lock)
1391{
1392        if (close_lock_file(lock->lk))
1393                return -1;
1394        return 0;
1395}
1396
1397static int commit_ref(struct ref_lock *lock)
1398{
1399        char *path = get_locked_file_path(lock->lk);
1400        struct stat st;
1401
1402        if (!lstat(path, &st) && S_ISDIR(st.st_mode)) {
1403                /*
1404                 * There is a directory at the path we want to rename
1405                 * the lockfile to. Hopefully it is empty; try to
1406                 * delete it.
1407                 */
1408                size_t len = strlen(path);
1409                struct strbuf sb_path = STRBUF_INIT;
1410
1411                strbuf_attach(&sb_path, path, len, len);
1412
1413                /*
1414                 * If this fails, commit_lock_file() will also fail
1415                 * and will report the problem.
1416                 */
1417                remove_empty_directories(&sb_path);
1418                strbuf_release(&sb_path);
1419        } else {
1420                free(path);
1421        }
1422
1423        if (commit_lock_file(lock->lk))
1424                return -1;
1425        return 0;
1426}
1427
1428static int open_or_create_logfile(const char *path, void *cb)
1429{
1430        int *fd = cb;
1431
1432        *fd = open(path, O_APPEND | O_WRONLY | O_CREAT, 0666);
1433        return (*fd < 0) ? -1 : 0;
1434}
1435
1436/*
1437 * Create a reflog for a ref. If force_create = 0, only create the
1438 * reflog for certain refs (those for which should_autocreate_reflog
1439 * returns non-zero). Otherwise, create it regardless of the reference
1440 * name. If the logfile already existed or was created, return 0 and
1441 * set *logfd to the file descriptor opened for appending to the file.
1442 * If no logfile exists and we decided not to create one, return 0 and
1443 * set *logfd to -1. On failure, fill in *err, set *logfd to -1, and
1444 * return -1.
1445 */
1446static int log_ref_setup(struct files_ref_store *refs,
1447                         const char *refname, int force_create,
1448                         int *logfd, struct strbuf *err)
1449{
1450        struct strbuf logfile_sb = STRBUF_INIT;
1451        char *logfile;
1452
1453        files_reflog_path(refs, &logfile_sb, refname);
1454        logfile = strbuf_detach(&logfile_sb, NULL);
1455
1456        if (force_create || should_autocreate_reflog(refname)) {
1457                if (raceproof_create_file(logfile, open_or_create_logfile, logfd)) {
1458                        if (errno == ENOENT)
1459                                strbuf_addf(err, "unable to create directory for '%s': "
1460                                            "%s", logfile, strerror(errno));
1461                        else if (errno == EISDIR)
1462                                strbuf_addf(err, "there are still logs under '%s'",
1463                                            logfile);
1464                        else
1465                                strbuf_addf(err, "unable to append to '%s': %s",
1466                                            logfile, strerror(errno));
1467
1468                        goto error;
1469                }
1470        } else {
1471                *logfd = open(logfile, O_APPEND | O_WRONLY, 0666);
1472                if (*logfd < 0) {
1473                        if (errno == ENOENT || errno == EISDIR) {
1474                                /*
1475                                 * The logfile doesn't already exist,
1476                                 * but that is not an error; it only
1477                                 * means that we won't write log
1478                                 * entries to it.
1479                                 */
1480                                ;
1481                        } else {
1482                                strbuf_addf(err, "unable to append to '%s': %s",
1483                                            logfile, strerror(errno));
1484                                goto error;
1485                        }
1486                }
1487        }
1488
1489        if (*logfd >= 0)
1490                adjust_shared_perm(logfile);
1491
1492        free(logfile);
1493        return 0;
1494
1495error:
1496        free(logfile);
1497        return -1;
1498}
1499
1500static int files_create_reflog(struct ref_store *ref_store,
1501                               const char *refname, int force_create,
1502                               struct strbuf *err)
1503{
1504        struct files_ref_store *refs =
1505                files_downcast(ref_store, REF_STORE_WRITE, "create_reflog");
1506        int fd;
1507
1508        if (log_ref_setup(refs, refname, force_create, &fd, err))
1509                return -1;
1510
1511        if (fd >= 0)
1512                close(fd);
1513
1514        return 0;
1515}
1516
1517static int log_ref_write_fd(int fd, const struct object_id *old_oid,
1518                            const struct object_id *new_oid,
1519                            const char *committer, const char *msg)
1520{
1521        int msglen, written;
1522        unsigned maxlen, len;
1523        char *logrec;
1524
1525        msglen = msg ? strlen(msg) : 0;
1526        maxlen = strlen(committer) + msglen + 100;
1527        logrec = xmalloc(maxlen);
1528        len = xsnprintf(logrec, maxlen, "%s %s %s\n",
1529                        oid_to_hex(old_oid),
1530                        oid_to_hex(new_oid),
1531                        committer);
1532        if (msglen)
1533                len += copy_reflog_msg(logrec + len - 1, msg) - 1;
1534
1535        written = len <= maxlen ? write_in_full(fd, logrec, len) : -1;
1536        free(logrec);
1537        if (written != len)
1538                return -1;
1539
1540        return 0;
1541}
1542
1543static int files_log_ref_write(struct files_ref_store *refs,
1544                               const char *refname, const struct object_id *old_oid,
1545                               const struct object_id *new_oid, const char *msg,
1546                               int flags, struct strbuf *err)
1547{
1548        int logfd, result;
1549
1550        if (log_all_ref_updates == LOG_REFS_UNSET)
1551                log_all_ref_updates = is_bare_repository() ? LOG_REFS_NONE : LOG_REFS_NORMAL;
1552
1553        result = log_ref_setup(refs, refname,
1554                               flags & REF_FORCE_CREATE_REFLOG,
1555                               &logfd, err);
1556
1557        if (result)
1558                return result;
1559
1560        if (logfd < 0)
1561                return 0;
1562        result = log_ref_write_fd(logfd, old_oid, new_oid,
1563                                  git_committer_info(0), msg);
1564        if (result) {
1565                struct strbuf sb = STRBUF_INIT;
1566                int save_errno = errno;
1567
1568                files_reflog_path(refs, &sb, refname);
1569                strbuf_addf(err, "unable to append to '%s': %s",
1570                            sb.buf, strerror(save_errno));
1571                strbuf_release(&sb);
1572                close(logfd);
1573                return -1;
1574        }
1575        if (close(logfd)) {
1576                struct strbuf sb = STRBUF_INIT;
1577                int save_errno = errno;
1578
1579                files_reflog_path(refs, &sb, refname);
1580                strbuf_addf(err, "unable to append to '%s': %s",
1581                            sb.buf, strerror(save_errno));
1582                strbuf_release(&sb);
1583                return -1;
1584        }
1585        return 0;
1586}
1587
1588/*
1589 * Write sha1 into the open lockfile, then close the lockfile. On
1590 * errors, rollback the lockfile, fill in *err and
1591 * return -1.
1592 */
1593static int write_ref_to_lockfile(struct ref_lock *lock,
1594                                 const struct object_id *oid, struct strbuf *err)
1595{
1596        static char term = '\n';
1597        struct object *o;
1598        int fd;
1599
1600        o = parse_object(oid);
1601        if (!o) {
1602                strbuf_addf(err,
1603                            "trying to write ref '%s' with nonexistent object %s",
1604                            lock->ref_name, oid_to_hex(oid));
1605                unlock_ref(lock);
1606                return -1;
1607        }
1608        if (o->type != OBJ_COMMIT && is_branch(lock->ref_name)) {
1609                strbuf_addf(err,
1610                            "trying to write non-commit object %s to branch '%s'",
1611                            oid_to_hex(oid), lock->ref_name);
1612                unlock_ref(lock);
1613                return -1;
1614        }
1615        fd = get_lock_file_fd(lock->lk);
1616        if (write_in_full(fd, oid_to_hex(oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||
1617            write_in_full(fd, &term, 1) != 1 ||
1618            close_ref(lock) < 0) {
1619                strbuf_addf(err,
1620                            "couldn't write '%s'", get_lock_file_path(lock->lk));
1621                unlock_ref(lock);
1622                return -1;
1623        }
1624        return 0;
1625}
1626
1627/*
1628 * Commit a change to a loose reference that has already been written
1629 * to the loose reference lockfile. Also update the reflogs if
1630 * necessary, using the specified lockmsg (which can be NULL).
1631 */
1632static int commit_ref_update(struct files_ref_store *refs,
1633                             struct ref_lock *lock,
1634                             const struct object_id *oid, const char *logmsg,
1635                             struct strbuf *err)
1636{
1637        files_assert_main_repository(refs, "commit_ref_update");
1638
1639        clear_loose_ref_cache(refs);
1640        if (files_log_ref_write(refs, lock->ref_name,
1641                                &lock->old_oid, oid,
1642                                logmsg, 0, err)) {
1643                char *old_msg = strbuf_detach(err, NULL);
1644                strbuf_addf(err, "cannot update the ref '%s': %s",
1645                            lock->ref_name, old_msg);
1646                free(old_msg);
1647                unlock_ref(lock);
1648                return -1;
1649        }
1650
1651        if (strcmp(lock->ref_name, "HEAD") != 0) {
1652                /*
1653                 * Special hack: If a branch is updated directly and HEAD
1654                 * points to it (may happen on the remote side of a push
1655                 * for example) then logically the HEAD reflog should be
1656                 * updated too.
1657                 * A generic solution implies reverse symref information,
1658                 * but finding all symrefs pointing to the given branch
1659                 * would be rather costly for this rare event (the direct
1660                 * update of a branch) to be worth it.  So let's cheat and
1661                 * check with HEAD only which should cover 99% of all usage
1662                 * scenarios (even 100% of the default ones).
1663                 */
1664                struct object_id head_oid;
1665                int head_flag;
1666                const char *head_ref;
1667
1668                head_ref = refs_resolve_ref_unsafe(&refs->base, "HEAD",
1669                                                   RESOLVE_REF_READING,
1670                                                   head_oid.hash, &head_flag);
1671                if (head_ref && (head_flag & REF_ISSYMREF) &&
1672                    !strcmp(head_ref, lock->ref_name)) {
1673                        struct strbuf log_err = STRBUF_INIT;
1674                        if (files_log_ref_write(refs, "HEAD",
1675                                                &lock->old_oid, oid,
1676                                                logmsg, 0, &log_err)) {
1677                                error("%s", log_err.buf);
1678                                strbuf_release(&log_err);
1679                        }
1680                }
1681        }
1682
1683        if (commit_ref(lock)) {
1684                strbuf_addf(err, "couldn't set '%s'", lock->ref_name);
1685                unlock_ref(lock);
1686                return -1;
1687        }
1688
1689        unlock_ref(lock);
1690        return 0;
1691}
1692
1693static int create_ref_symlink(struct ref_lock *lock, const char *target)
1694{
1695        int ret = -1;
1696#ifndef NO_SYMLINK_HEAD
1697        char *ref_path = get_locked_file_path(lock->lk);
1698        unlink(ref_path);
1699        ret = symlink(target, ref_path);
1700        free(ref_path);
1701
1702        if (ret)
1703                fprintf(stderr, "no symlink - falling back to symbolic ref\n");
1704#endif
1705        return ret;
1706}
1707
1708static void update_symref_reflog(struct files_ref_store *refs,
1709                                 struct ref_lock *lock, const char *refname,
1710                                 const char *target, const char *logmsg)
1711{
1712        struct strbuf err = STRBUF_INIT;
1713        struct object_id new_oid;
1714        if (logmsg &&
1715            !refs_read_ref_full(&refs->base, target,
1716                                RESOLVE_REF_READING, new_oid.hash, NULL) &&
1717            files_log_ref_write(refs, refname, &lock->old_oid,
1718                                &new_oid, logmsg, 0, &err)) {
1719                error("%s", err.buf);
1720                strbuf_release(&err);
1721        }
1722}
1723
1724static int create_symref_locked(struct files_ref_store *refs,
1725                                struct ref_lock *lock, const char *refname,
1726                                const char *target, const char *logmsg)
1727{
1728        if (prefer_symlink_refs && !create_ref_symlink(lock, target)) {
1729                update_symref_reflog(refs, lock, refname, target, logmsg);
1730                return 0;
1731        }
1732
1733        if (!fdopen_lock_file(lock->lk, "w"))
1734                return error("unable to fdopen %s: %s",
1735                             lock->lk->tempfile.filename.buf, strerror(errno));
1736
1737        update_symref_reflog(refs, lock, refname, target, logmsg);
1738
1739        /* no error check; commit_ref will check ferror */
1740        fprintf(lock->lk->tempfile.fp, "ref: %s\n", target);
1741        if (commit_ref(lock) < 0)
1742                return error("unable to write symref for %s: %s", refname,
1743                             strerror(errno));
1744        return 0;
1745}
1746
1747static int files_create_symref(struct ref_store *ref_store,
1748                               const char *refname, const char *target,
1749                               const char *logmsg)
1750{
1751        struct files_ref_store *refs =
1752                files_downcast(ref_store, REF_STORE_WRITE, "create_symref");
1753        struct strbuf err = STRBUF_INIT;
1754        struct ref_lock *lock;
1755        int ret;
1756
1757        lock = lock_ref_sha1_basic(refs, refname, NULL,
1758                                   NULL, NULL, REF_NODEREF, NULL,
1759                                   &err);
1760        if (!lock) {
1761                error("%s", err.buf);
1762                strbuf_release(&err);
1763                return -1;
1764        }
1765
1766        ret = create_symref_locked(refs, lock, refname, target, logmsg);
1767        unlock_ref(lock);
1768        return ret;
1769}
1770
1771static int files_reflog_exists(struct ref_store *ref_store,
1772                               const char *refname)
1773{
1774        struct files_ref_store *refs =
1775                files_downcast(ref_store, REF_STORE_READ, "reflog_exists");
1776        struct strbuf sb = STRBUF_INIT;
1777        struct stat st;
1778        int ret;
1779
1780        files_reflog_path(refs, &sb, refname);
1781        ret = !lstat(sb.buf, &st) && S_ISREG(st.st_mode);
1782        strbuf_release(&sb);
1783        return ret;
1784}
1785
1786static int files_delete_reflog(struct ref_store *ref_store,
1787                               const char *refname)
1788{
1789        struct files_ref_store *refs =
1790                files_downcast(ref_store, REF_STORE_WRITE, "delete_reflog");
1791        struct strbuf sb = STRBUF_INIT;
1792        int ret;
1793
1794        files_reflog_path(refs, &sb, refname);
1795        ret = remove_path(sb.buf);
1796        strbuf_release(&sb);
1797        return ret;
1798}
1799
1800static int show_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn, void *cb_data)
1801{
1802        struct object_id ooid, noid;
1803        char *email_end, *message;
1804        timestamp_t timestamp;
1805        int tz;
1806        const char *p = sb->buf;
1807
1808        /* old SP new SP name <email> SP time TAB msg LF */
1809        if (!sb->len || sb->buf[sb->len - 1] != '\n' ||
1810            parse_oid_hex(p, &ooid, &p) || *p++ != ' ' ||
1811            parse_oid_hex(p, &noid, &p) || *p++ != ' ' ||
1812            !(email_end = strchr(p, '>')) ||
1813            email_end[1] != ' ' ||
1814            !(timestamp = parse_timestamp(email_end + 2, &message, 10)) ||
1815            !message || message[0] != ' ' ||
1816            (message[1] != '+' && message[1] != '-') ||
1817            !isdigit(message[2]) || !isdigit(message[3]) ||
1818            !isdigit(message[4]) || !isdigit(message[5]))
1819                return 0; /* corrupt? */
1820        email_end[1] = '\0';
1821        tz = strtol(message + 1, NULL, 10);
1822        if (message[6] != '\t')
1823                message += 6;
1824        else
1825                message += 7;
1826        return fn(&ooid, &noid, p, timestamp, tz, message, cb_data);
1827}
1828
1829static char *find_beginning_of_line(char *bob, char *scan)
1830{
1831        while (bob < scan && *(--scan) != '\n')
1832                ; /* keep scanning backwards */
1833        /*
1834         * Return either beginning of the buffer, or LF at the end of
1835         * the previous line.
1836         */
1837        return scan;
1838}
1839
1840static int files_for_each_reflog_ent_reverse(struct ref_store *ref_store,
1841                                             const char *refname,
1842                                             each_reflog_ent_fn fn,
1843                                             void *cb_data)
1844{
1845        struct files_ref_store *refs =
1846                files_downcast(ref_store, REF_STORE_READ,
1847                               "for_each_reflog_ent_reverse");
1848        struct strbuf sb = STRBUF_INIT;
1849        FILE *logfp;
1850        long pos;
1851        int ret = 0, at_tail = 1;
1852
1853        files_reflog_path(refs, &sb, refname);
1854        logfp = fopen(sb.buf, "r");
1855        strbuf_release(&sb);
1856        if (!logfp)
1857                return -1;
1858
1859        /* Jump to the end */
1860        if (fseek(logfp, 0, SEEK_END) < 0)
1861                ret = error("cannot seek back reflog for %s: %s",
1862                            refname, strerror(errno));
1863        pos = ftell(logfp);
1864        while (!ret && 0 < pos) {
1865                int cnt;
1866                size_t nread;
1867                char buf[BUFSIZ];
1868                char *endp, *scanp;
1869
1870                /* Fill next block from the end */
1871                cnt = (sizeof(buf) < pos) ? sizeof(buf) : pos;
1872                if (fseek(logfp, pos - cnt, SEEK_SET)) {
1873                        ret = error("cannot seek back reflog for %s: %s",
1874                                    refname, strerror(errno));
1875                        break;
1876                }
1877                nread = fread(buf, cnt, 1, logfp);
1878                if (nread != 1) {
1879                        ret = error("cannot read %d bytes from reflog for %s: %s",
1880                                    cnt, refname, strerror(errno));
1881                        break;
1882                }
1883                pos -= cnt;
1884
1885                scanp = endp = buf + cnt;
1886                if (at_tail && scanp[-1] == '\n')
1887                        /* Looking at the final LF at the end of the file */
1888                        scanp--;
1889                at_tail = 0;
1890
1891                while (buf < scanp) {
1892                        /*
1893                         * terminating LF of the previous line, or the beginning
1894                         * of the buffer.
1895                         */
1896                        char *bp;
1897
1898                        bp = find_beginning_of_line(buf, scanp);
1899
1900                        if (*bp == '\n') {
1901                                /*
1902                                 * The newline is the end of the previous line,
1903                                 * so we know we have complete line starting
1904                                 * at (bp + 1). Prefix it onto any prior data
1905                                 * we collected for the line and process it.
1906                                 */
1907                                strbuf_splice(&sb, 0, 0, bp + 1, endp - (bp + 1));
1908                                scanp = bp;
1909                                endp = bp + 1;
1910                                ret = show_one_reflog_ent(&sb, fn, cb_data);
1911                                strbuf_reset(&sb);
1912                                if (ret)
1913                                        break;
1914                        } else if (!pos) {
1915                                /*
1916                                 * We are at the start of the buffer, and the
1917                                 * start of the file; there is no previous
1918                                 * line, and we have everything for this one.
1919                                 * Process it, and we can end the loop.
1920                                 */
1921                                strbuf_splice(&sb, 0, 0, buf, endp - buf);
1922                                ret = show_one_reflog_ent(&sb, fn, cb_data);
1923                                strbuf_reset(&sb);
1924                                break;
1925                        }
1926
1927                        if (bp == buf) {
1928                                /*
1929                                 * We are at the start of the buffer, and there
1930                                 * is more file to read backwards. Which means
1931                                 * we are in the middle of a line. Note that we
1932                                 * may get here even if *bp was a newline; that
1933                                 * just means we are at the exact end of the
1934                                 * previous line, rather than some spot in the
1935                                 * middle.
1936                                 *
1937                                 * Save away what we have to be combined with
1938                                 * the data from the next read.
1939                                 */
1940                                strbuf_splice(&sb, 0, 0, buf, endp - buf);
1941                                break;
1942                        }
1943                }
1944
1945        }
1946        if (!ret && sb.len)
1947                die("BUG: reverse reflog parser had leftover data");
1948
1949        fclose(logfp);
1950        strbuf_release(&sb);
1951        return ret;
1952}
1953
1954static int files_for_each_reflog_ent(struct ref_store *ref_store,
1955                                     const char *refname,
1956                                     each_reflog_ent_fn fn, void *cb_data)
1957{
1958        struct files_ref_store *refs =
1959                files_downcast(ref_store, REF_STORE_READ,
1960                               "for_each_reflog_ent");
1961        FILE *logfp;
1962        struct strbuf sb = STRBUF_INIT;
1963        int ret = 0;
1964
1965        files_reflog_path(refs, &sb, refname);
1966        logfp = fopen(sb.buf, "r");
1967        strbuf_release(&sb);
1968        if (!logfp)
1969                return -1;
1970
1971        while (!ret && !strbuf_getwholeline(&sb, logfp, '\n'))
1972                ret = show_one_reflog_ent(&sb, fn, cb_data);
1973        fclose(logfp);
1974        strbuf_release(&sb);
1975        return ret;
1976}
1977
1978struct files_reflog_iterator {
1979        struct ref_iterator base;
1980
1981        struct ref_store *ref_store;
1982        struct dir_iterator *dir_iterator;
1983        struct object_id oid;
1984};
1985
1986static int files_reflog_iterator_advance(struct ref_iterator *ref_iterator)
1987{
1988        struct files_reflog_iterator *iter =
1989                (struct files_reflog_iterator *)ref_iterator;
1990        struct dir_iterator *diter = iter->dir_iterator;
1991        int ok;
1992
1993        while ((ok = dir_iterator_advance(diter)) == ITER_OK) {
1994                int flags;
1995
1996                if (!S_ISREG(diter->st.st_mode))
1997                        continue;
1998                if (diter->basename[0] == '.')
1999                        continue;
2000                if (ends_with(diter->basename, ".lock"))
2001                        continue;
2002
2003                if (refs_read_ref_full(iter->ref_store,
2004                                       diter->relative_path, 0,
2005                                       iter->oid.hash, &flags)) {
2006                        error("bad ref for %s", diter->path.buf);
2007                        continue;
2008                }
2009
2010                iter->base.refname = diter->relative_path;
2011                iter->base.oid = &iter->oid;
2012                iter->base.flags = flags;
2013                return ITER_OK;
2014        }
2015
2016        iter->dir_iterator = NULL;
2017        if (ref_iterator_abort(ref_iterator) == ITER_ERROR)
2018                ok = ITER_ERROR;
2019        return ok;
2020}
2021
2022static int files_reflog_iterator_peel(struct ref_iterator *ref_iterator,
2023                                   struct object_id *peeled)
2024{
2025        die("BUG: ref_iterator_peel() called for reflog_iterator");
2026}
2027
2028static int files_reflog_iterator_abort(struct ref_iterator *ref_iterator)
2029{
2030        struct files_reflog_iterator *iter =
2031                (struct files_reflog_iterator *)ref_iterator;
2032        int ok = ITER_DONE;
2033
2034        if (iter->dir_iterator)
2035                ok = dir_iterator_abort(iter->dir_iterator);
2036
2037        base_ref_iterator_free(ref_iterator);
2038        return ok;
2039}
2040
2041static struct ref_iterator_vtable files_reflog_iterator_vtable = {
2042        files_reflog_iterator_advance,
2043        files_reflog_iterator_peel,
2044        files_reflog_iterator_abort
2045};
2046
2047static struct ref_iterator *files_reflog_iterator_begin(struct ref_store *ref_store)
2048{
2049        struct files_ref_store *refs =
2050                files_downcast(ref_store, REF_STORE_READ,
2051                               "reflog_iterator_begin");
2052        struct files_reflog_iterator *iter = xcalloc(1, sizeof(*iter));
2053        struct ref_iterator *ref_iterator = &iter->base;
2054        struct strbuf sb = STRBUF_INIT;
2055
2056        base_ref_iterator_init(ref_iterator, &files_reflog_iterator_vtable);
2057        files_reflog_path(refs, &sb, NULL);
2058        iter->dir_iterator = dir_iterator_begin(sb.buf);
2059        iter->ref_store = ref_store;
2060        strbuf_release(&sb);
2061        return ref_iterator;
2062}
2063
2064/*
2065 * If update is a direct update of head_ref (the reference pointed to
2066 * by HEAD), then add an extra REF_LOG_ONLY update for HEAD.
2067 */
2068static int split_head_update(struct ref_update *update,
2069                             struct ref_transaction *transaction,
2070                             const char *head_ref,
2071                             struct string_list *affected_refnames,
2072                             struct strbuf *err)
2073{
2074        struct string_list_item *item;
2075        struct ref_update *new_update;
2076
2077        if ((update->flags & REF_LOG_ONLY) ||
2078            (update->flags & REF_ISPRUNING) ||
2079            (update->flags & REF_UPDATE_VIA_HEAD))
2080                return 0;
2081
2082        if (strcmp(update->refname, head_ref))
2083                return 0;
2084
2085        /*
2086         * First make sure that HEAD is not already in the
2087         * transaction. This insertion is O(N) in the transaction
2088         * size, but it happens at most once per transaction.
2089         */
2090        item = string_list_insert(affected_refnames, "HEAD");
2091        if (item->util) {
2092                /* An entry already existed */
2093                strbuf_addf(err,
2094                            "multiple updates for 'HEAD' (including one "
2095                            "via its referent '%s') are not allowed",
2096                            update->refname);
2097                return TRANSACTION_NAME_CONFLICT;
2098        }
2099
2100        new_update = ref_transaction_add_update(
2101                        transaction, "HEAD",
2102                        update->flags | REF_LOG_ONLY | REF_NODEREF,
2103                        update->new_oid.hash, update->old_oid.hash,
2104                        update->msg);
2105
2106        item->util = new_update;
2107
2108        return 0;
2109}
2110
2111/*
2112 * update is for a symref that points at referent and doesn't have
2113 * REF_NODEREF set. Split it into two updates:
2114 * - The original update, but with REF_LOG_ONLY and REF_NODEREF set
2115 * - A new, separate update for the referent reference
2116 * Note that the new update will itself be subject to splitting when
2117 * the iteration gets to it.
2118 */
2119static int split_symref_update(struct files_ref_store *refs,
2120                               struct ref_update *update,
2121                               const char *referent,
2122                               struct ref_transaction *transaction,
2123                               struct string_list *affected_refnames,
2124                               struct strbuf *err)
2125{
2126        struct string_list_item *item;
2127        struct ref_update *new_update;
2128        unsigned int new_flags;
2129
2130        /*
2131         * First make sure that referent is not already in the
2132         * transaction. This insertion is O(N) in the transaction
2133         * size, but it happens at most once per symref in a
2134         * transaction.
2135         */
2136        item = string_list_insert(affected_refnames, referent);
2137        if (item->util) {
2138                /* An entry already existed */
2139                strbuf_addf(err,
2140                            "multiple updates for '%s' (including one "
2141                            "via symref '%s') are not allowed",
2142                            referent, update->refname);
2143                return TRANSACTION_NAME_CONFLICT;
2144        }
2145
2146        new_flags = update->flags;
2147        if (!strcmp(update->refname, "HEAD")) {
2148                /*
2149                 * Record that the new update came via HEAD, so that
2150                 * when we process it, split_head_update() doesn't try
2151                 * to add another reflog update for HEAD. Note that
2152                 * this bit will be propagated if the new_update
2153                 * itself needs to be split.
2154                 */
2155                new_flags |= REF_UPDATE_VIA_HEAD;
2156        }
2157
2158        new_update = ref_transaction_add_update(
2159                        transaction, referent, new_flags,
2160                        update->new_oid.hash, update->old_oid.hash,
2161                        update->msg);
2162
2163        new_update->parent_update = update;
2164
2165        /*
2166         * Change the symbolic ref update to log only. Also, it
2167         * doesn't need to check its old SHA-1 value, as that will be
2168         * done when new_update is processed.
2169         */
2170        update->flags |= REF_LOG_ONLY | REF_NODEREF;
2171        update->flags &= ~REF_HAVE_OLD;
2172
2173        item->util = new_update;
2174
2175        return 0;
2176}
2177
2178/*
2179 * Return the refname under which update was originally requested.
2180 */
2181static const char *original_update_refname(struct ref_update *update)
2182{
2183        while (update->parent_update)
2184                update = update->parent_update;
2185
2186        return update->refname;
2187}
2188
2189/*
2190 * Check whether the REF_HAVE_OLD and old_oid values stored in update
2191 * are consistent with oid, which is the reference's current value. If
2192 * everything is OK, return 0; otherwise, write an error message to
2193 * err and return -1.
2194 */
2195static int check_old_oid(struct ref_update *update, struct object_id *oid,
2196                         struct strbuf *err)
2197{
2198        if (!(update->flags & REF_HAVE_OLD) ||
2199                   !oidcmp(oid, &update->old_oid))
2200                return 0;
2201
2202        if (is_null_oid(&update->old_oid))
2203                strbuf_addf(err, "cannot lock ref '%s': "
2204                            "reference already exists",
2205                            original_update_refname(update));
2206        else if (is_null_oid(oid))
2207                strbuf_addf(err, "cannot lock ref '%s': "
2208                            "reference is missing but expected %s",
2209                            original_update_refname(update),
2210                            oid_to_hex(&update->old_oid));
2211        else
2212                strbuf_addf(err, "cannot lock ref '%s': "
2213                            "is at %s but expected %s",
2214                            original_update_refname(update),
2215                            oid_to_hex(oid),
2216                            oid_to_hex(&update->old_oid));
2217
2218        return -1;
2219}
2220
2221/*
2222 * Prepare for carrying out update:
2223 * - Lock the reference referred to by update.
2224 * - Read the reference under lock.
2225 * - Check that its old SHA-1 value (if specified) is correct, and in
2226 *   any case record it in update->lock->old_oid for later use when
2227 *   writing the reflog.
2228 * - If it is a symref update without REF_NODEREF, split it up into a
2229 *   REF_LOG_ONLY update of the symref and add a separate update for
2230 *   the referent to transaction.
2231 * - If it is an update of head_ref, add a corresponding REF_LOG_ONLY
2232 *   update of HEAD.
2233 */
2234static int lock_ref_for_update(struct files_ref_store *refs,
2235                               struct ref_update *update,
2236                               struct ref_transaction *transaction,
2237                               const char *head_ref,
2238                               struct string_list *affected_refnames,
2239                               struct strbuf *err)
2240{
2241        struct strbuf referent = STRBUF_INIT;
2242        int mustexist = (update->flags & REF_HAVE_OLD) &&
2243                !is_null_oid(&update->old_oid);
2244        int ret;
2245        struct ref_lock *lock;
2246
2247        files_assert_main_repository(refs, "lock_ref_for_update");
2248
2249        if ((update->flags & REF_HAVE_NEW) && is_null_oid(&update->new_oid))
2250                update->flags |= REF_DELETING;
2251
2252        if (head_ref) {
2253                ret = split_head_update(update, transaction, head_ref,
2254                                        affected_refnames, err);
2255                if (ret)
2256                        return ret;
2257        }
2258
2259        ret = lock_raw_ref(refs, update->refname, mustexist,
2260                           affected_refnames, NULL,
2261                           &lock, &referent,
2262                           &update->type, err);
2263        if (ret) {
2264                char *reason;
2265
2266                reason = strbuf_detach(err, NULL);
2267                strbuf_addf(err, "cannot lock ref '%s': %s",
2268                            original_update_refname(update), reason);
2269                free(reason);
2270                return ret;
2271        }
2272
2273        update->backend_data = lock;
2274
2275        if (update->type & REF_ISSYMREF) {
2276                if (update->flags & REF_NODEREF) {
2277                        /*
2278                         * We won't be reading the referent as part of
2279                         * the transaction, so we have to read it here
2280                         * to record and possibly check old_sha1:
2281                         */
2282                        if (refs_read_ref_full(&refs->base,
2283                                               referent.buf, 0,
2284                                               lock->old_oid.hash, NULL)) {
2285                                if (update->flags & REF_HAVE_OLD) {
2286                                        strbuf_addf(err, "cannot lock ref '%s': "
2287                                                    "error reading reference",
2288                                                    original_update_refname(update));
2289                                        return -1;
2290                                }
2291                        } else if (check_old_oid(update, &lock->old_oid, err)) {
2292                                return TRANSACTION_GENERIC_ERROR;
2293                        }
2294                } else {
2295                        /*
2296                         * Create a new update for the reference this
2297                         * symref is pointing at. Also, we will record
2298                         * and verify old_sha1 for this update as part
2299                         * of processing the split-off update, so we
2300                         * don't have to do it here.
2301                         */
2302                        ret = split_symref_update(refs, update,
2303                                                  referent.buf, transaction,
2304                                                  affected_refnames, err);
2305                        if (ret)
2306                                return ret;
2307                }
2308        } else {
2309                struct ref_update *parent_update;
2310
2311                if (check_old_oid(update, &lock->old_oid, err))
2312                        return TRANSACTION_GENERIC_ERROR;
2313
2314                /*
2315                 * If this update is happening indirectly because of a
2316                 * symref update, record the old SHA-1 in the parent
2317                 * update:
2318                 */
2319                for (parent_update = update->parent_update;
2320                     parent_update;
2321                     parent_update = parent_update->parent_update) {
2322                        struct ref_lock *parent_lock = parent_update->backend_data;
2323                        oidcpy(&parent_lock->old_oid, &lock->old_oid);
2324                }
2325        }
2326
2327        if ((update->flags & REF_HAVE_NEW) &&
2328            !(update->flags & REF_DELETING) &&
2329            !(update->flags & REF_LOG_ONLY)) {
2330                if (!(update->type & REF_ISSYMREF) &&
2331                    !oidcmp(&lock->old_oid, &update->new_oid)) {
2332                        /*
2333                         * The reference already has the desired
2334                         * value, so we don't need to write it.
2335                         */
2336                } else if (write_ref_to_lockfile(lock, &update->new_oid,
2337                                                 err)) {
2338                        char *write_err = strbuf_detach(err, NULL);
2339
2340                        /*
2341                         * The lock was freed upon failure of
2342                         * write_ref_to_lockfile():
2343                         */
2344                        update->backend_data = NULL;
2345                        strbuf_addf(err,
2346                                    "cannot update ref '%s': %s",
2347                                    update->refname, write_err);
2348                        free(write_err);
2349                        return TRANSACTION_GENERIC_ERROR;
2350                } else {
2351                        update->flags |= REF_NEEDS_COMMIT;
2352                }
2353        }
2354        if (!(update->flags & REF_NEEDS_COMMIT)) {
2355                /*
2356                 * We didn't call write_ref_to_lockfile(), so
2357                 * the lockfile is still open. Close it to
2358                 * free up the file descriptor:
2359                 */
2360                if (close_ref(lock)) {
2361                        strbuf_addf(err, "couldn't close '%s.lock'",
2362                                    update->refname);
2363                        return TRANSACTION_GENERIC_ERROR;
2364                }
2365        }
2366        return 0;
2367}
2368
2369/*
2370 * Unlock any references in `transaction` that are still locked, and
2371 * mark the transaction closed.
2372 */
2373static void files_transaction_cleanup(struct ref_transaction *transaction)
2374{
2375        size_t i;
2376
2377        for (i = 0; i < transaction->nr; i++) {
2378                struct ref_update *update = transaction->updates[i];
2379                struct ref_lock *lock = update->backend_data;
2380
2381                if (lock) {
2382                        unlock_ref(lock);
2383                        update->backend_data = NULL;
2384                }
2385        }
2386
2387        transaction->state = REF_TRANSACTION_CLOSED;
2388}
2389
2390static int files_transaction_prepare(struct ref_store *ref_store,
2391                                     struct ref_transaction *transaction,
2392                                     struct strbuf *err)
2393{
2394        struct files_ref_store *refs =
2395                files_downcast(ref_store, REF_STORE_WRITE,
2396                               "ref_transaction_prepare");
2397        size_t i;
2398        int ret = 0;
2399        struct string_list affected_refnames = STRING_LIST_INIT_NODUP;
2400        char *head_ref = NULL;
2401        int head_type;
2402        struct object_id head_oid;
2403
2404        assert(err);
2405
2406        if (!transaction->nr)
2407                goto cleanup;
2408
2409        /*
2410         * Fail if a refname appears more than once in the
2411         * transaction. (If we end up splitting up any updates using
2412         * split_symref_update() or split_head_update(), those
2413         * functions will check that the new updates don't have the
2414         * same refname as any existing ones.)
2415         */
2416        for (i = 0; i < transaction->nr; i++) {
2417                struct ref_update *update = transaction->updates[i];
2418                struct string_list_item *item =
2419                        string_list_append(&affected_refnames, update->refname);
2420
2421                /*
2422                 * We store a pointer to update in item->util, but at
2423                 * the moment we never use the value of this field
2424                 * except to check whether it is non-NULL.
2425                 */
2426                item->util = update;
2427        }
2428        string_list_sort(&affected_refnames);
2429        if (ref_update_reject_duplicates(&affected_refnames, err)) {
2430                ret = TRANSACTION_GENERIC_ERROR;
2431                goto cleanup;
2432        }
2433
2434        /*
2435         * Special hack: If a branch is updated directly and HEAD
2436         * points to it (may happen on the remote side of a push
2437         * for example) then logically the HEAD reflog should be
2438         * updated too.
2439         *
2440         * A generic solution would require reverse symref lookups,
2441         * but finding all symrefs pointing to a given branch would be
2442         * rather costly for this rare event (the direct update of a
2443         * branch) to be worth it. So let's cheat and check with HEAD
2444         * only, which should cover 99% of all usage scenarios (even
2445         * 100% of the default ones).
2446         *
2447         * So if HEAD is a symbolic reference, then record the name of
2448         * the reference that it points to. If we see an update of
2449         * head_ref within the transaction, then split_head_update()
2450         * arranges for the reflog of HEAD to be updated, too.
2451         */
2452        head_ref = refs_resolve_refdup(ref_store, "HEAD",
2453                                       RESOLVE_REF_NO_RECURSE,
2454                                       head_oid.hash, &head_type);
2455
2456        if (head_ref && !(head_type & REF_ISSYMREF)) {
2457                free(head_ref);
2458                head_ref = NULL;
2459        }
2460
2461        /*
2462         * Acquire all locks, verify old values if provided, check
2463         * that new values are valid, and write new values to the
2464         * lockfiles, ready to be activated. Only keep one lockfile
2465         * open at a time to avoid running out of file descriptors.
2466         * Note that lock_ref_for_update() might append more updates
2467         * to the transaction.
2468         */
2469        for (i = 0; i < transaction->nr; i++) {
2470                struct ref_update *update = transaction->updates[i];
2471
2472                ret = lock_ref_for_update(refs, update, transaction,
2473                                          head_ref, &affected_refnames, err);
2474                if (ret)
2475                        break;
2476        }
2477
2478cleanup:
2479        free(head_ref);
2480        string_list_clear(&affected_refnames, 0);
2481
2482        if (ret)
2483                files_transaction_cleanup(transaction);
2484        else
2485                transaction->state = REF_TRANSACTION_PREPARED;
2486
2487        return ret;
2488}
2489
2490static int files_transaction_finish(struct ref_store *ref_store,
2491                                    struct ref_transaction *transaction,
2492                                    struct strbuf *err)
2493{
2494        struct files_ref_store *refs =
2495                files_downcast(ref_store, 0, "ref_transaction_finish");
2496        size_t i;
2497        int ret = 0;
2498        struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;
2499        struct string_list_item *ref_to_delete;
2500        struct strbuf sb = STRBUF_INIT;
2501
2502        assert(err);
2503
2504        if (!transaction->nr) {
2505                transaction->state = REF_TRANSACTION_CLOSED;
2506                return 0;
2507        }
2508
2509        /* Perform updates first so live commits remain referenced */
2510        for (i = 0; i < transaction->nr; i++) {
2511                struct ref_update *update = transaction->updates[i];
2512                struct ref_lock *lock = update->backend_data;
2513
2514                if (update->flags & REF_NEEDS_COMMIT ||
2515                    update->flags & REF_LOG_ONLY) {
2516                        if (files_log_ref_write(refs,
2517                                                lock->ref_name,
2518                                                &lock->old_oid,
2519                                                &update->new_oid,
2520                                                update->msg, update->flags,
2521                                                err)) {
2522                                char *old_msg = strbuf_detach(err, NULL);
2523
2524                                strbuf_addf(err, "cannot update the ref '%s': %s",
2525                                            lock->ref_name, old_msg);
2526                                free(old_msg);
2527                                unlock_ref(lock);
2528                                update->backend_data = NULL;
2529                                ret = TRANSACTION_GENERIC_ERROR;
2530                                goto cleanup;
2531                        }
2532                }
2533                if (update->flags & REF_NEEDS_COMMIT) {
2534                        clear_loose_ref_cache(refs);
2535                        if (commit_ref(lock)) {
2536                                strbuf_addf(err, "couldn't set '%s'", lock->ref_name);
2537                                unlock_ref(lock);
2538                                update->backend_data = NULL;
2539                                ret = TRANSACTION_GENERIC_ERROR;
2540                                goto cleanup;
2541                        }
2542                }
2543        }
2544        /* Perform deletes now that updates are safely completed */
2545        for (i = 0; i < transaction->nr; i++) {
2546                struct ref_update *update = transaction->updates[i];
2547                struct ref_lock *lock = update->backend_data;
2548
2549                if (update->flags & REF_DELETING &&
2550                    !(update->flags & REF_LOG_ONLY)) {
2551                        if (!(update->type & REF_ISPACKED) ||
2552                            update->type & REF_ISSYMREF) {
2553                                /* It is a loose reference. */
2554                                strbuf_reset(&sb);
2555                                files_ref_path(refs, &sb, lock->ref_name);
2556                                if (unlink_or_msg(sb.buf, err)) {
2557                                        ret = TRANSACTION_GENERIC_ERROR;
2558                                        goto cleanup;
2559                                }
2560                                update->flags |= REF_DELETED_LOOSE;
2561                        }
2562
2563                        if (!(update->flags & REF_ISPRUNING))
2564                                string_list_append(&refs_to_delete,
2565                                                   lock->ref_name);
2566                }
2567        }
2568
2569        if (repack_without_refs(refs->packed_ref_store, &refs_to_delete, err)) {
2570                ret = TRANSACTION_GENERIC_ERROR;
2571                goto cleanup;
2572        }
2573
2574        /* Delete the reflogs of any references that were deleted: */
2575        for_each_string_list_item(ref_to_delete, &refs_to_delete) {
2576                strbuf_reset(&sb);
2577                files_reflog_path(refs, &sb, ref_to_delete->string);
2578                if (!unlink_or_warn(sb.buf))
2579                        try_remove_empty_parents(refs, ref_to_delete->string,
2580                                                 REMOVE_EMPTY_PARENTS_REFLOG);
2581        }
2582
2583        clear_loose_ref_cache(refs);
2584
2585cleanup:
2586        files_transaction_cleanup(transaction);
2587
2588        for (i = 0; i < transaction->nr; i++) {
2589                struct ref_update *update = transaction->updates[i];
2590
2591                if (update->flags & REF_DELETED_LOOSE) {
2592                        /*
2593                         * The loose reference was deleted. Delete any
2594                         * empty parent directories. (Note that this
2595                         * can only work because we have already
2596                         * removed the lockfile.)
2597                         */
2598                        try_remove_empty_parents(refs, update->refname,
2599                                                 REMOVE_EMPTY_PARENTS_REF);
2600                }
2601        }
2602
2603        strbuf_release(&sb);
2604        string_list_clear(&refs_to_delete, 0);
2605        return ret;
2606}
2607
2608static int files_transaction_abort(struct ref_store *ref_store,
2609                                   struct ref_transaction *transaction,
2610                                   struct strbuf *err)
2611{
2612        files_transaction_cleanup(transaction);
2613        return 0;
2614}
2615
2616static int ref_present(const char *refname,
2617                       const struct object_id *oid, int flags, void *cb_data)
2618{
2619        struct string_list *affected_refnames = cb_data;
2620
2621        return string_list_has_string(affected_refnames, refname);
2622}
2623
2624static int files_initial_transaction_commit(struct ref_store *ref_store,
2625                                            struct ref_transaction *transaction,
2626                                            struct strbuf *err)
2627{
2628        struct files_ref_store *refs =
2629                files_downcast(ref_store, REF_STORE_WRITE,
2630                               "initial_ref_transaction_commit");
2631        size_t i;
2632        int ret = 0;
2633        struct string_list affected_refnames = STRING_LIST_INIT_NODUP;
2634
2635        assert(err);
2636
2637        if (transaction->state != REF_TRANSACTION_OPEN)
2638                die("BUG: commit called for transaction that is not open");
2639
2640        /* Fail if a refname appears more than once in the transaction: */
2641        for (i = 0; i < transaction->nr; i++)
2642                string_list_append(&affected_refnames,
2643                                   transaction->updates[i]->refname);
2644        string_list_sort(&affected_refnames);
2645        if (ref_update_reject_duplicates(&affected_refnames, err)) {
2646                ret = TRANSACTION_GENERIC_ERROR;
2647                goto cleanup;
2648        }
2649
2650        /*
2651         * It's really undefined to call this function in an active
2652         * repository or when there are existing references: we are
2653         * only locking and changing packed-refs, so (1) any
2654         * simultaneous processes might try to change a reference at
2655         * the same time we do, and (2) any existing loose versions of
2656         * the references that we are setting would have precedence
2657         * over our values. But some remote helpers create the remote
2658         * "HEAD" and "master" branches before calling this function,
2659         * so here we really only check that none of the references
2660         * that we are creating already exists.
2661         */
2662        if (refs_for_each_rawref(&refs->base, ref_present,
2663                                 &affected_refnames))
2664                die("BUG: initial ref transaction called with existing refs");
2665
2666        for (i = 0; i < transaction->nr; i++) {
2667                struct ref_update *update = transaction->updates[i];
2668
2669                if ((update->flags & REF_HAVE_OLD) &&
2670                    !is_null_oid(&update->old_oid))
2671                        die("BUG: initial ref transaction with old_sha1 set");
2672                if (refs_verify_refname_available(&refs->base, update->refname,
2673                                                  &affected_refnames, NULL,
2674                                                  err)) {
2675                        ret = TRANSACTION_NAME_CONFLICT;
2676                        goto cleanup;
2677                }
2678        }
2679
2680        if (lock_packed_refs(refs->packed_ref_store, 0)) {
2681                strbuf_addf(err, "unable to lock packed-refs file: %s",
2682                            strerror(errno));
2683                ret = TRANSACTION_GENERIC_ERROR;
2684                goto cleanup;
2685        }
2686
2687        for (i = 0; i < transaction->nr; i++) {
2688                struct ref_update *update = transaction->updates[i];
2689
2690                if ((update->flags & REF_HAVE_NEW) &&
2691                    !is_null_oid(&update->new_oid))
2692                        add_packed_ref(refs->packed_ref_store, update->refname,
2693                                       &update->new_oid);
2694        }
2695
2696        if (commit_packed_refs(refs->packed_ref_store)) {
2697                strbuf_addf(err, "unable to commit packed-refs file: %s",
2698                            strerror(errno));
2699                ret = TRANSACTION_GENERIC_ERROR;
2700                goto cleanup;
2701        }
2702
2703cleanup:
2704        transaction->state = REF_TRANSACTION_CLOSED;
2705        string_list_clear(&affected_refnames, 0);
2706        return ret;
2707}
2708
2709struct expire_reflog_cb {
2710        unsigned int flags;
2711        reflog_expiry_should_prune_fn *should_prune_fn;
2712        void *policy_cb;
2713        FILE *newlog;
2714        struct object_id last_kept_oid;
2715};
2716
2717static int expire_reflog_ent(struct object_id *ooid, struct object_id *noid,
2718                             const char *email, timestamp_t timestamp, int tz,
2719                             const char *message, void *cb_data)
2720{
2721        struct expire_reflog_cb *cb = cb_data;
2722        struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;
2723
2724        if (cb->flags & EXPIRE_REFLOGS_REWRITE)
2725                ooid = &cb->last_kept_oid;
2726
2727        if ((*cb->should_prune_fn)(ooid, noid, email, timestamp, tz,
2728                                   message, policy_cb)) {
2729                if (!cb->newlog)
2730                        printf("would prune %s", message);
2731                else if (cb->flags & EXPIRE_REFLOGS_VERBOSE)
2732                        printf("prune %s", message);
2733        } else {
2734                if (cb->newlog) {
2735                        fprintf(cb->newlog, "%s %s %s %"PRItime" %+05d\t%s",
2736                                oid_to_hex(ooid), oid_to_hex(noid),
2737                                email, timestamp, tz, message);
2738                        oidcpy(&cb->last_kept_oid, noid);
2739                }
2740                if (cb->flags & EXPIRE_REFLOGS_VERBOSE)
2741                        printf("keep %s", message);
2742        }
2743        return 0;
2744}
2745
2746static int files_reflog_expire(struct ref_store *ref_store,
2747                               const char *refname, const unsigned char *sha1,
2748                               unsigned int flags,
2749                               reflog_expiry_prepare_fn prepare_fn,
2750                               reflog_expiry_should_prune_fn should_prune_fn,
2751                               reflog_expiry_cleanup_fn cleanup_fn,
2752                               void *policy_cb_data)
2753{
2754        struct files_ref_store *refs =
2755                files_downcast(ref_store, REF_STORE_WRITE, "reflog_expire");
2756        static struct lock_file reflog_lock;
2757        struct expire_reflog_cb cb;
2758        struct ref_lock *lock;
2759        struct strbuf log_file_sb = STRBUF_INIT;
2760        char *log_file;
2761        int status = 0;
2762        int type;
2763        struct strbuf err = STRBUF_INIT;
2764        struct object_id oid;
2765
2766        memset(&cb, 0, sizeof(cb));
2767        cb.flags = flags;
2768        cb.policy_cb = policy_cb_data;
2769        cb.should_prune_fn = should_prune_fn;
2770
2771        /*
2772         * The reflog file is locked by holding the lock on the
2773         * reference itself, plus we might need to update the
2774         * reference if --updateref was specified:
2775         */
2776        lock = lock_ref_sha1_basic(refs, refname, sha1,
2777                                   NULL, NULL, REF_NODEREF,
2778                                   &type, &err);
2779        if (!lock) {
2780                error("cannot lock ref '%s': %s", refname, err.buf);
2781                strbuf_release(&err);
2782                return -1;
2783        }
2784        if (!refs_reflog_exists(ref_store, refname)) {
2785                unlock_ref(lock);
2786                return 0;
2787        }
2788
2789        files_reflog_path(refs, &log_file_sb, refname);
2790        log_file = strbuf_detach(&log_file_sb, NULL);
2791        if (!(flags & EXPIRE_REFLOGS_DRY_RUN)) {
2792                /*
2793                 * Even though holding $GIT_DIR/logs/$reflog.lock has
2794                 * no locking implications, we use the lock_file
2795                 * machinery here anyway because it does a lot of the
2796                 * work we need, including cleaning up if the program
2797                 * exits unexpectedly.
2798                 */
2799                if (hold_lock_file_for_update(&reflog_lock, log_file, 0) < 0) {
2800                        struct strbuf err = STRBUF_INIT;
2801                        unable_to_lock_message(log_file, errno, &err);
2802                        error("%s", err.buf);
2803                        strbuf_release(&err);
2804                        goto failure;
2805                }
2806                cb.newlog = fdopen_lock_file(&reflog_lock, "w");
2807                if (!cb.newlog) {
2808                        error("cannot fdopen %s (%s)",
2809                              get_lock_file_path(&reflog_lock), strerror(errno));
2810                        goto failure;
2811                }
2812        }
2813
2814        hashcpy(oid.hash, sha1);
2815
2816        (*prepare_fn)(refname, &oid, cb.policy_cb);
2817        refs_for_each_reflog_ent(ref_store, refname, expire_reflog_ent, &cb);
2818        (*cleanup_fn)(cb.policy_cb);
2819
2820        if (!(flags & EXPIRE_REFLOGS_DRY_RUN)) {
2821                /*
2822                 * It doesn't make sense to adjust a reference pointed
2823                 * to by a symbolic ref based on expiring entries in
2824                 * the symbolic reference's reflog. Nor can we update
2825                 * a reference if there are no remaining reflog
2826                 * entries.
2827                 */
2828                int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&
2829                        !(type & REF_ISSYMREF) &&
2830                        !is_null_oid(&cb.last_kept_oid);
2831
2832                if (close_lock_file(&reflog_lock)) {
2833                        status |= error("couldn't write %s: %s", log_file,
2834                                        strerror(errno));
2835                } else if (update &&
2836                           (write_in_full(get_lock_file_fd(lock->lk),
2837                                oid_to_hex(&cb.last_kept_oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||
2838                            write_str_in_full(get_lock_file_fd(lock->lk), "\n") != 1 ||
2839                            close_ref(lock) < 0)) {
2840                        status |= error("couldn't write %s",
2841                                        get_lock_file_path(lock->lk));
2842                        rollback_lock_file(&reflog_lock);
2843                } else if (commit_lock_file(&reflog_lock)) {
2844                        status |= error("unable to write reflog '%s' (%s)",
2845                                        log_file, strerror(errno));
2846                } else if (update && commit_ref(lock)) {
2847                        status |= error("couldn't set %s", lock->ref_name);
2848                }
2849        }
2850        free(log_file);
2851        unlock_ref(lock);
2852        return status;
2853
2854 failure:
2855        rollback_lock_file(&reflog_lock);
2856        free(log_file);
2857        unlock_ref(lock);
2858        return -1;
2859}
2860
2861static int files_init_db(struct ref_store *ref_store, struct strbuf *err)
2862{
2863        struct files_ref_store *refs =
2864                files_downcast(ref_store, REF_STORE_WRITE, "init_db");
2865        struct strbuf sb = STRBUF_INIT;
2866
2867        /*
2868         * Create .git/refs/{heads,tags}
2869         */
2870        files_ref_path(refs, &sb, "refs/heads");
2871        safe_create_dir(sb.buf, 1);
2872
2873        strbuf_reset(&sb);
2874        files_ref_path(refs, &sb, "refs/tags");
2875        safe_create_dir(sb.buf, 1);
2876
2877        strbuf_release(&sb);
2878        return 0;
2879}
2880
2881struct ref_storage_be refs_be_files = {
2882        NULL,
2883        "files",
2884        files_ref_store_create,
2885        files_init_db,
2886        files_transaction_prepare,
2887        files_transaction_finish,
2888        files_transaction_abort,
2889        files_initial_transaction_commit,
2890
2891        files_pack_refs,
2892        files_peel_ref,
2893        files_create_symref,
2894        files_delete_refs,
2895        files_rename_ref,
2896
2897        files_ref_iterator_begin,
2898        files_read_raw_ref,
2899
2900        files_reflog_iterator_begin,
2901        files_for_each_reflog_ent,
2902        files_for_each_reflog_ent_reverse,
2903        files_reflog_exists,
2904        files_create_reflog,
2905        files_delete_reflog,
2906        files_reflog_expire
2907};