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