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